ryuk-cli 0.1.1

The `ryuk` command: scaffold a Ryuk app (axum, SeaORM, Inertia/Svelte), generate controllers, models, jobs and mails, run migrations and the dev server.
//! Credential revocation and account deletion, shared by the api (`DELETE /api/me`) and the web.
use crate::{
    AppState,
    models::{oauth_identity, post, project, user},
};
use ryuk::{
    auth,
    apikey::api_keys,
    oauth_server::{codes, tokens as oauth_tokens},
    passkey::passkeys,
    push::push_devices,
    tokens::one_time_tokens,
};
use ryuk::throttle::Throttle;
use sea_orm::{ColumnTrait, DbErr, EntityTrait, QueryFilter, TransactionTrait};

/// A valid hash nobody knows the password of: unknown emails and missing passwords still pay one argon2
/// verification, so timing says nothing.
pub async fn dummy_hash() -> String {
    static DUMMY: tokio::sync::OnceCell<String> = tokio::sync::OnceCell::const_new();
    DUMMY.get_or_init(|| async { auth::hash_password_async("ryuk-dummy".into()).await.unwrap_or_default() }).await.clone()
}

/// Re-check the password before a sensitive action. Accounts without a usable password (social-only) pass:
/// the session already proves who they are. `Throttle::attempt` (atomic, per user+IP) so parallel guesses
/// cannot overshoot the limit. `Err(message)` is for the form; `Ok` means proceed.
pub async fn confirm_password(s: &AppState, ip: Option<std::net::IpAddr>, u: &user::Model, given: Option<&str>) -> Result<Result<(), String>, crate::controllers::AppError> {
    if !u.has_usable_password {
        return Ok(Ok(()));
    }
    let key = Throttle::key(&format!("account:{}", u.id), ip);
    if let Err(locked) = s.throttle.attempt(&key).await {
        return Ok(Err(format!("Too many attempts. Try again in {} seconds.", locked.retry_after.as_secs())));
    }
    let ok = match given {
        Some(p) => auth::verify_password_async(p.to_string(), u.password.clone()).await,
        None => {
            auth::verify_password_async(String::new(), dummy_hash().await).await;
            false
        }
    };
    if ok {
        s.throttle.clear(&key).await?;
        Ok(Ok(()))
    } else {
        Ok(Err("The password is incorrect.".into()))
    }
}

/// Revoke every way of acting as `uid` except the password: OAuth grants (and unused codes) and DbStore sessions.
/// API keys are NOT touched: a password CHANGE keeps them (keys are machine credentials, not tied to the password;
/// a user who suspects compromise resets the password, logs out everywhere, or revokes keys in the UI).
/// Reset and log-out-everywhere call `ApiKeys::revoke_all` themselves; deletion does it in `revoke_credentials`.
pub async fn sign_out_everywhere(s: &AppState, uid: i64) -> Result<(), crate::controllers::AppError> {
    s.oauth.revoke_user_tokens(uid).await?;
    s.session_store.delete_for_user(uid).await?;
    Ok(())
}

async fn revoke_credentials(s: &AppState, uid: i64) -> Result<(), crate::controllers::AppError> {
    s.api_keys.revoke_all(uid).await?;
    s.passkeys.delete_all(uid).await?;
    sign_out_everywhere(s, uid).await
}

/// Delete an organization with everything in it: its projects (deleted explicitly, not only by the foreign
/// key), members and invitations. Add your own tenant-owned tables here when you create them.
pub async fn delete_org(s: &AppState, org_id: i64) -> Result<(), crate::controllers::AppError> {
    project::Entity::delete_many().filter(project::Column::OrgId.eq(org_id)).exec(&s.db).await?;
    s.tenancy.delete_org(org_id).await?;
    Ok(())
}

/// Names of the organizations that stop `uid` deleting their account: they are the only owner and other
/// people are still members. They must hand over ownership (or delete the org) first.
/// shortcut: checked before the deletion, not locked; a member added in between is dropped with the user.
pub async fn orgs_blocking_deletion(s: &AppState, uid: i64) -> Result<Vec<String>, crate::controllers::AppError> {
    let mut names = vec![];
    for (org, role) in s.tenancy.orgs_of(uid).await? {
        let members = s.tenancy.members(org.id).await?;
        let other_owner = members.iter().any(|m| m.user_id != uid && m.role == "owner");
        if role == ryuk::tenancy::Role::Owner && !other_owner && members.len() > 1 {
            names.push(org.name);
        }
    }
    Ok(names)
}

/// Delete the user and everything of theirs. Idempotent: running it again (after a failure, or for a
/// user already gone) is harmless.
///
/// Order matters. (1) Revoke every credential first, so a failure later never leaves a usable token,
/// key or session behind; the password still works, which is what lets the user retry.
/// (2) Delete the data and the user row in ONE transaction: all or nothing.
/// (3) Revoke again: anything minted between (1) and the commit (a login or a code exchange racing us)
/// is swept, and a deleted user can never be signed in as.
pub async fn delete_user(s: &AppState, uid: i64) -> Result<(), crate::controllers::AppError> {
    revoke_credentials(s, uid).await?;
    // Organizations: one they alone belong to goes with them; from the others they are REMOVED through the
    // library, whose last-owner guard is row-locked: two owners deleting their accounts at the same time cannot
    // both leave (the loser fails here, nothing is deleted yet, and a retry sees the friendly refusal from
    // `orgs_blocking_deletion`). The foreign key alone would drop the membership without that guard.
    for (org, _) in s.tenancy.orgs_of(uid).await? {
        if s.tenancy.members(org.id).await?.len() == 1 {
            delete_org(s, org.id).await?;
        } else {
            s.tenancy.remove_member(org.id, uid).await?;
        }
    }
    s.db.transaction::<_, (), DbErr>(|tx| {
        Box::pin(async move {
            post::Entity::delete_many().filter(post::Column::UserId.eq(uid)).exec(tx).await?;
            push_devices::Entity::delete_many().filter(push_devices::Column::UserId.eq(uid)).exec(tx).await?;
            oauth_identity::Entity::delete_many().filter(oauth_identity::Column::UserId.eq(uid)).exec(tx).await?;
            one_time_tokens::Entity::delete_many().filter(one_time_tokens::Column::UserId.eq(uid)).exec(tx).await?;
            api_keys::Entity::delete_many().filter(api_keys::Column::OwnerId.eq(uid)).exec(tx).await?;
            passkeys::Entity::delete_many().filter(passkeys::Column::OwnerId.eq(uid)).exec(tx).await?;
            codes::Entity::delete_many().filter(codes::Column::UserId.eq(uid)).exec(tx).await?;
            oauth_tokens::Entity::delete_many().filter(oauth_tokens::Column::UserId.eq(uid)).exec(tx).await?;
            user::Entity::delete_by_id(uid).exec(tx).await?;
            Ok(())
        })
    })
    .await?;
    revoke_credentials(s, uid).await
}