ryuk-cli 0.1.0

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, 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 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?;
    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
}