Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/src/console/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use laravel::schedule::{self, Schedule};
pub use crate::heartbeat;
pub mod demo;
pub mod retention;
pub mod staff;

#[schedule::tasks]
fn schedule(schedule: &mut Schedule) {
Expand Down
257 changes: 257 additions & 0 deletions app/src/console/staff.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,257 @@
//! Staff commands, run in a web pod (`visualci-app <command>`), ported from the Loco server's tasks with the same
//! arguments and behaviour: make someone staff, add someone to an organization, put an organization on a plan, delete
//! an empty organization, and set up the Stripe catalog. Each refuses clearly (an error naming what's wrong) where the
//! old task did, and running one again with the same arguments changes nothing more.

use laravel::console::{Console, clap, command};
use laravel::db;

use crate::auth::Role;
use crate::auth::memberships::MembershipChanged;
use crate::billing::stripe::{self, Method};
use crate::models::{Organization, User};

fn refuse(message: impl Into<String>) -> laravel::Error {
laravel::Error::msg(message.into())
}

async fn organization(slug: &str) -> laravel::Result<Organization> {
Organization::query()
.filter(Organization::slug.eq(slug))
.first()
.await?
.ok_or_else(|| refuse(format!("no organization {slug}")))
}

/// The configured Stripe key, or why there's none.
fn stripe_key(why: &str) -> laravel::Result<String> {
laravel::config()
.section::<crate::config::Stripe>()
.secret_key
.clone()
.filter(|k| !k.is_empty())
.ok_or_else(|| refuse(why))
}

/// `user:set-staff --email <address> --staff <true|false>`: make a user staff, or not. Staff read every
/// organization's data through the admin MCP server (`/mcp/admin`) and the staff pages. Only Nathan and DocSpring's own
/// agents. Taking staff away also revokes their admin connections ([`revoke_admin_connections`]).
#[derive(clap::Parser)]
#[command(name = "user:set-staff")]
pub struct UserSetStaff {
/// The user's email address.
#[arg(long)]
email: String,
/// `true` or `false`.
#[arg(long, action = clap::ArgAction::Set)]
staff: bool,
}

#[command]
impl UserSetStaff {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
let (email, staff) = (self.email.trim().to_lowercase(), self.staff);
let updated: Option<(i64, String)> = db::query!(
"UPDATE users SET staff = {staff}, updated_at = now() WHERE lower(email) = {email} RETURNING id, pid::text"
)
.select()
.await?
.first()
.map(|r| Ok::<_, laravel::Error>((r.try_get("id")?, r.try_get("pid")?)))
.transpose()?;
let Some((_, pid)) = updated else { return Err(refuse(format!("no user {}", self.email))) };
if staff {
console.line(format!("{}: staff true", self.email));
} else {
let revoked = revoke_admin_connections(&pid).await?;
console.line(format!("{}: staff false; {revoked} admin connections revoked", self.email));
}
Ok(())
}
}

/// Ends every OAuth connection of someone's that holds the `admin` scope (the admin MCP endpoint): its access and
/// refresh tokens stop working, and a code not yet exchanged can't be. The endpoint also checks `users.staff` on
/// every call; this makes the tokens themselves useless. Their other connections (`mcp`) are left alone. Returns
/// how many connections it ended.
///
/// # Errors
/// On a database error.
pub async fn revoke_admin_connections(subject: &str) -> laravel::Result<u64> {
let now = laravel::now().timestamp().as_microsecond();
let families: Vec<String> = db::query!(
"SELECT family_id FROM oauth_tokens WHERE subject = {subject} AND ' ' || scope || ' ' LIKE '% admin %' \
AND revoked_at IS NULL \
UNION SELECT family_id FROM oauth_codes WHERE subject = {subject} AND ' ' || scope || ' ' LIKE '% admin %' \
AND used_at IS NULL AND NOT EXISTS (SELECT 1 FROM oauth_families f \
WHERE f.family_id = oauth_codes.family_id AND f.revoked_at IS NOT NULL)"
)
.select_as::<String>()
.await?;
for family in &families {
db::query!(
"INSERT INTO oauth_families (family_id, revoked_at) VALUES ({family}, {now}) \
ON CONFLICT (family_id) DO UPDATE SET revoked_at = COALESCE(oauth_families.revoked_at, excluded.revoked_at)"
)
.insert()
.await?;
db::query!("UPDATE oauth_tokens SET revoked_at = {now} WHERE family_id = {family} AND revoked_at IS NULL")
.update()
.await?;
}
Ok(families.len() as u64)
}

/// `org:add-member --org <slug> --user <email or forge login> [--role admin|member|read]`: add an existing user to an
/// organization, or change their role there, as staff (`memberships.source = staff`, which the forge's sync never
/// changes). For support: someone whose forge permission doesn't cover them. The role defaults to `member`. Someone new
/// to the organization is told, as an invitation's joiner is.
#[derive(clap::Parser)]
#[command(name = "org:add-member")]
pub struct OrgAddMember {
/// The organization's slug.
#[arg(long)]
org: String,
/// The user's email address, or a forge login (`octocat` or `@octocat`).
#[arg(long)]
user: String,
/// `admin`, `member` or `read`.
#[arg(long, default_value = "member")]
role: String,
}

#[command]
impl OrgAddMember {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
let role = Role::parse(&self.role).ok_or_else(|| refuse("role must be admin, member or read"))?;
let org = organization(&self.org).await?;
let login = self.user.trim_start_matches('@').to_lowercase();
let email = self.user.to_lowercase();
let user: Option<Option<i64>> = db::query!(
"SELECT COALESCE((SELECT user_id FROM identities WHERE lower(login) = {login} ORDER BY id LIMIT 1), \
(SELECT id FROM users WHERE lower(email) = {email} LIMIT 1))"
)
.scalar()
.await?;
let user = match user.flatten() {
Some(id) => User::find_or_fail(id).await?,
None => return Err(refuse(format!("no user with the email or forge login {}", self.user))),
};
let (org_id, user_id, role_name) = (org.id, user.id, role.as_str());
let added: Option<i64> = db::query!(
"INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \
VALUES ({org_id}, {user_id}, {role_name}, 'staff', now(), now()) \
ON CONFLICT (organization_id, user_id) DO NOTHING RETURNING id"
)
.scalar()
.await?;
if added.is_some() {
MembershipChanged::now(org_id, user_id, Some(role)).dispatch().await?;
} else {
db::query!(
"UPDATE memberships SET role = {role_name}, source = 'staff', synced_at = NULL, updated_at = now() \
WHERE organization_id = {org_id} AND user_id = {user_id}"
)
.update()
.await?;
}
console.line(format!("{} is now {} of {} (staff)", user.email, role.as_str(), org.slug));
Ok(())
}
}

/// `org:set-plan --org <slug> --plan <free|team|staff>`: put an organization on a plan by hand. For DocSpring's own
/// organizations (Staff: unlimited, never offered) and for support. Team normally comes from a Stripe subscription, so
/// setting it here doesn't bill anyone.
#[derive(clap::Parser)]
#[command(name = "org:set-plan")]
pub struct OrgSetPlan {
/// The organization's slug.
#[arg(long)]
org: String,
/// `free`, `team` or `staff`.
#[arg(long)]
plan: String,
}

#[command]
impl OrgSetPlan {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
let plan = self.plan.clone();
if ![crate::billing::FREE.id, crate::billing::TEAM.id, crate::billing::STAFF.id].contains(&plan.as_str()) {
return Err(refuse("plan must be free, team or staff"));
}
let id = organization(&self.org).await?.id;
db::query!("UPDATE organizations SET plan = {plan}, updated_at = now() WHERE id = {id}").update().await?;
console.line(format!("{} is on the {} plan", self.org, self.plan));
Ok(())
}
}

/// `org:delete --org <slug>`: delete an empty organization (a test or a mistake) and its Stripe customer. It refuses
/// an organization with projects, a subscription or any Stripe invoice: those have data or money attached and need a
/// person's decision, not a command.
#[derive(clap::Parser)]
#[command(name = "org:delete")]
pub struct OrgDelete {
/// The organization's slug.
#[arg(long)]
org: String,
}

#[command]
impl OrgDelete {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
let slug = &self.org;
let org = organization(slug).await?;
let id = org.id;
let projects: i64 =
db::query!("SELECT COUNT(*) FROM projects WHERE organization_id = {id}").scalar().await?.unwrap_or(0);
if projects > 0 {
return Err(refuse(format!("{slug} has {projects} projects; not deleting it")));
}
if org.stripe_subscription_id.is_some() {
return Err(refuse(format!("{slug} has a Stripe subscription; not deleting it")));
}
if let Some(customer) = &org.stripe_customer_id {
let key = stripe_key("the organization has a Stripe customer, but Stripe isn't configured")?;
let customer_query = ("customer", customer.clone());
let subs = stripe::get(
&key,
"subscriptions",
&[customer_query.clone(), ("status", "all".into()), ("limit", "1".into())],
)
.await?;
let invoices = stripe::get(&key, "invoices", &[customer_query, ("limit", "1".into())]).await?;
let has = |v: &serde_json::Value| v["data"].as_array().is_some_and(|d| !d.is_empty());
if has(&subs) || has(&invoices) {
return Err(refuse(format!("{customer} has subscriptions or invoices; not deleting it")));
}
stripe::request(&key, Method::Delete, &format!("customers/{customer}"), &[], None).await?;
console.line(format!("deleted Stripe customer {customer}"));
}
db::query!("DELETE FROM organizations WHERE id = {id}").delete().await?;
console.line(format!("deleted organization {slug}"));
Ok(())
}
}

/// `stripe:setup`: create or update VisualCI's Stripe products, prices (Team monthly, the credit pack) and customer
/// portal configuration. The app does the same the first time it needs them, so this is for checking a new Stripe
/// account, or applying a price change before anyone pays.
#[derive(clap::Parser)]
#[command(name = "stripe:setup")]
pub struct StripeSetup;

#[command]
impl StripeSetup {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
let key = stripe_key("Stripe isn't configured (VISUALCI_STRIPE_SECRET_KEY)")?;
let catalog = stripe::ensure_catalog(&key).await?;
console.line(format!(
"Team price {}, credit pack price {}, portal configuration {}",
catalog.team_price, catalog.pack_price, catalog.portal_configuration
));
Ok(())
}
}
5 changes: 5 additions & 0 deletions app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,5 +112,10 @@ pub fn configure() -> ApplicationBuilder {
commands.add::<console::retention::GroupsCheck>();
commands.add::<console::demo::DemoReset>();
commands.add::<console::demo::ScreenshotsSeed>();
commands.add::<console::staff::UserSetStaff>();
commands.add::<console::staff::OrgAddMember>();
commands.add::<console::staff::OrgSetPlan>();
commands.add::<console::staff::OrgDelete>();
commands.add::<console::staff::StripeSetup>();
})
}
Loading
Loading