rustio-admin 0.21.0

Django Admin, but for Rust. A small, focused admin framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Emergency-recovery primitives — the framework-side surface called
//! by the `rustio user <op>` CLI commands.
//!
//! Each function performs the atomic DB-mutation chain for one
//! emergency operation and returns a typed outcome the CLI uses to
//! render its post-mutation summary.
//!
//! ## D12 — CLI-only audit emission
//!
//! These functions deliberately do NOT write the
//! `AuditEvent::EmergencyRecovery` row. That emission lives in the
//! CLI crate (`crates/rustio-admin-cli/`), so the audit row's
//! call-stack-of-record is always rooted in the CLI binary. The
//! framework provides the DB transaction; the CLI provides the
//! audit trail. The
//! [`admin::audit::tests::emergency_recovery_is_cli_only`] unit
//! test enforces this — adding an `AuditEvent::EmergencyRecovery`
//! emission anywhere in `crates/rustio-admin/src/` fails the
//! default test gate.
//!
//! ## D11 — atomic per command
//!
//! Each function that mutates more than one row runs its mutations
//! inside a single sqlx transaction. Partial failures roll back so
//! half-applied state never lands — e.g. a `reset_password` that
//! hashed + stored the new password but then failed to flip
//! `must_change_password` would leave the user in a worse state
//! than before.
//!
//! ## Building blocks reused
//!
//! - [`crate::auth::users::hash_password`] for Argon2id-hashed
//!   password storage
//! - [`crate::auth::invalidate_sessions`] for revocation under
//!   doctrine 22 (single writer of `revoked_at`)
//!
//! See `DESIGN_R4_EMERGENCY.md` §6 for the building-block table per
//! operation and §3 for the locked scope.

use crate::auth::sessions::{
    invalidate_sessions, InvalidationOutcome, SessionInvalidationReason, SessionTarget,
};
use crate::auth::users::hash_password;
use crate::auth::Role;
use crate::error::{Error, Result};
use crate::orm::Db;

// ---- Outcomes ------------------------------------------------------------

// public:
/// Outcome of [`reset_password`]. The CLI uses this to compose the
/// post-mutation summary line ("password set, N sessions revoked"
/// or "user not found").
#[derive(Debug, Clone)]
pub enum ResetOutcome {
    Ok { revoked_session_count: usize },
    UnknownTarget,
}

// public:
/// Outcome of [`unlock`].
#[derive(Debug, Clone)]
pub enum UnlockOutcome {
    Ok { previously_locked: bool },
    UnknownTarget,
}

// public:
/// Outcome of [`disable_mfa`].
#[derive(Debug, Clone)]
pub enum DisableMfaOutcome {
    Ok {
        was_enabled: bool,
        deleted_backup_codes: usize,
        revoked_session_count: usize,
    },
    UnknownTarget,
}

// public:
/// Outcome of [`promote`]. `SoleAdministratorDemoteRefused` is the
/// only "refuse the operation outright" branch — the rest of the
/// emergency surface allows action on any extant target (the
/// operator already has DB access; the framework's role is
/// audit-visibility, not gatekeeping).
#[derive(Debug, Clone)]
pub enum PromoteOutcome {
    Ok {
        previous_role: Role,
        new_role: Role,
        revoked_session_count: usize,
    },
    /// Target already carries `new_role`. No DB write, no session
    /// revocation. The CLI surfaces this as a benign no-op.
    NoChange {
        current_role: Role,
    },
    UnknownTarget,
    /// Demoting from `Administrator` would leave zero active
    /// administrators. Refused per `DESIGN_R4_EMERGENCY.md` §3.4.
    SoleAdministratorDemoteRefused,
}

// public:
/// Outcome of [`emergency_access`].
#[derive(Debug, Clone)]
pub enum EmergencyAccessOutcome {
    Ok {
        token_id: i64,
        url_path: String,
        expires_at: chrono::DateTime<chrono::Utc>,
    },
    UnknownTarget,
    InactiveTarget,
}

// ---- Helpers -------------------------------------------------------------

/// Confirm the target row exists. Returns the `is_active` flag when
/// present, `None` when no row matches. Used by every emergency
/// function as the first gate (UnknownTarget short-circuit).
async fn target_exists(db: &Db, user_id: i64) -> Result<Option<bool>> {
    let row: Option<(bool,)> = sqlx::query_as("SELECT is_active FROM rustio_users WHERE id = $1")
        .bind(user_id)
        .fetch_optional(db.pool())
        .await
        .map_err(Error::from)?;
    Ok(row.map(|(active,)| active))
}

// ---- reset_password ------------------------------------------------------

/// Set a new password for `target_user_id`, raise
/// `must_change_password = TRUE`, revoke every session for the user.
///
/// The CLI supplies `new_password` — either operator-provided via
/// `--temp-password` or a CLI-generated random string. This function
/// does not generate or echo the plaintext; the caller owns it and
/// is responsible for displaying it exactly once.
///
/// Atomic: the password update + must-change flag flip + audit
/// columns (`password_changed_at = NOW()`) land in one transaction.
/// Session revocation runs after commit because
/// [`invalidate_sessions`] is the single writer of `revoked_at`
/// (doctrine 22) and runs its own atomic statement; a transaction
/// boundary here keeps the password mutation isolated from the
/// session sweep.
// public:
pub async fn reset_password(
    db: &Db,
    target_user_id: i64,
    new_password: &str,
) -> Result<ResetOutcome> {
    if target_exists(db, target_user_id).await?.is_none() {
        return Ok(ResetOutcome::UnknownTarget);
    }

    let hash = hash_password(new_password)?;

    let mut tx = db.pool().begin().await.map_err(Error::from)?;
    sqlx::query(
        "UPDATE rustio_users \
         SET password_hash = $1, \
             password_changed_at = NOW(), \
             must_change_password = TRUE \
         WHERE id = $2",
    )
    .bind(&hash)
    .bind(target_user_id)
    .execute(&mut *tx)
    .await
    .map_err(Error::from)?;
    tx.commit().await.map_err(Error::from)?;

    let outcome = invalidate_sessions(
        db,
        SessionTarget::User {
            user_id: target_user_id,
        },
        SessionInvalidationReason::PasswordResetByOther,
    )
    .await?;

    Ok(ResetOutcome::Ok {
        revoked_session_count: outcome.revoked_session_ids.len(),
    })
}

// ---- unlock --------------------------------------------------------------

/// Clear `locked_until` and reset `failed_login_count = 0` on the
/// target. Does NOT touch sessions — an unlock is not a session
/// event per `DESIGN_R4_EMERGENCY.md` §7.
///
/// Returns `previously_locked` so the CLI can render "the account
/// was indeed locked, now cleared" vs. "the account was already
/// open, this was a no-op" without an extra round-trip.
// public:
pub async fn unlock(db: &Db, target_user_id: i64) -> Result<UnlockOutcome> {
    if target_exists(db, target_user_id).await?.is_none() {
        return Ok(UnlockOutcome::UnknownTarget);
    }

    // Capture the pre-state so the outcome can distinguish "no-op"
    // from "actually unlocked." Both rows still write — clearing
    // an already-clear column is benign.
    let was_locked: bool = sqlx::query_scalar(
        "SELECT (locked_until IS NOT NULL AND locked_until > NOW()) \
                OR failed_login_count > 0 \
         FROM rustio_users WHERE id = $1",
    )
    .bind(target_user_id)
    .fetch_one(db.pool())
    .await
    .map_err(Error::from)?;

    sqlx::query(
        "UPDATE rustio_users \
         SET locked_until = NULL, failed_login_count = 0 \
         WHERE id = $1",
    )
    .bind(target_user_id)
    .execute(db.pool())
    .await
    .map_err(Error::from)?;

    Ok(UnlockOutcome::Ok {
        previously_locked: was_locked,
    })
}

// ---- disable_mfa ---------------------------------------------------------

/// Clear every MFA column on the target user, delete every backup-
/// code row, revoke every session for the user.
///
/// **Session-revocation scope.** `DESIGN_R4_EMERGENCY.md` §7 calls
/// for revoking only sessions with `trust_level = 'mfa_verified'`
/// (other sessions stay valid). The current [`SessionTarget`] enum
/// has no trust-level filter; rather than introduce a new variant
/// in commit #3, this function revokes ALL of the target's sessions
/// via `SessionTarget::User`. The over-broad revoke is conservative
/// — every revoked session forces a fresh login that picks up the
/// post-disable MFA state cleanly. A future
/// `SessionTarget::UserWithTrustLevel` variant could narrow this
/// without changing the function's caller contract.
///
/// Atomic: the column clear + backup-code DELETE land in one
/// transaction. Session revocation runs after commit.
// public:
pub async fn disable_mfa(db: &Db, target_user_id: i64) -> Result<DisableMfaOutcome> {
    if target_exists(db, target_user_id).await?.is_none() {
        return Ok(DisableMfaOutcome::UnknownTarget);
    }

    let was_enabled: bool =
        sqlx::query_scalar("SELECT COALESCE(mfa_enabled, FALSE) FROM rustio_users WHERE id = $1")
            .bind(target_user_id)
            .fetch_one(db.pool())
            .await
            .map_err(Error::from)?;

    let mut tx = db.pool().begin().await.map_err(Error::from)?;

    sqlx::query(
        "UPDATE rustio_users SET \
            mfa_enabled = FALSE, \
            mfa_secret_ciphertext = NULL, \
            mfa_secret_key_id = NULL, \
            mfa_last_used_step = NULL \
         WHERE id = $1",
    )
    .bind(target_user_id)
    .execute(&mut *tx)
    .await
    .map_err(Error::from)?;

    let deleted: u64 = sqlx::query("DELETE FROM rustio_mfa_backup_codes WHERE user_id = $1")
        .bind(target_user_id)
        .execute(&mut *tx)
        .await
        .map_err(Error::from)?
        .rows_affected();

    tx.commit().await.map_err(Error::from)?;

    let outcome = invalidate_sessions(
        db,
        SessionTarget::User {
            user_id: target_user_id,
        },
        SessionInvalidationReason::MfaDisabledByOther,
    )
    .await?;

    Ok(DisableMfaOutcome::Ok {
        was_enabled,
        deleted_backup_codes: deleted as usize,
        revoked_session_count: outcome.revoked_session_ids.len(),
    })
}

// ---- promote -------------------------------------------------------------

/// Change the target user's role to `new_role`.
///
/// Refuses to demote the sole active administrator: if the target
/// currently holds `Role::Administrator` AND `new_role !=
/// Administrator` AND no OTHER active administrators exist, returns
/// [`PromoteOutcome::SoleAdministratorDemoteRefused`]. This guard
/// is per `DESIGN_R4_EMERGENCY.md` §3.4 — the framework refuses to
/// leave the deployment with zero administrators, even via CLI.
///
/// Atomic: the role-write + session-revoke are in one transaction
/// to preserve doctrine 22 single-writer semantics while keeping
/// the promote operation isolated from concurrent session reads.
/// Session revocation runs after commit per the
/// `invalidate_sessions` contract.
// public:
pub async fn promote(db: &Db, target_user_id: i64, new_role: Role) -> Result<PromoteOutcome> {
    let row: Option<(String, bool)> =
        sqlx::query_as("SELECT role, is_active FROM rustio_users WHERE id = $1")
            .bind(target_user_id)
            .fetch_optional(db.pool())
            .await
            .map_err(Error::from)?;
    let (current_role_str, _is_active) = match row {
        Some(r) => r,
        None => return Ok(PromoteOutcome::UnknownTarget),
    };

    let current_role = parse_role(&current_role_str).unwrap_or(Role::User);
    if current_role == new_role {
        return Ok(PromoteOutcome::NoChange { current_role });
    }

    // Sole-administrator demote check. `is_active = TRUE` is the
    // pre-condition for an administrator to be usable; demoting to
    // a tier below Administrator must leave at least one active
    // administrator standing.
    if current_role == Role::Administrator && new_role != Role::Administrator {
        let other_admins: i64 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM rustio_users \
             WHERE role = 'administrator' AND is_active = TRUE AND id <> $1",
        )
        .bind(target_user_id)
        .fetch_one(db.pool())
        .await
        .map_err(Error::from)?;
        if other_admins == 0 {
            return Ok(PromoteOutcome::SoleAdministratorDemoteRefused);
        }
    }

    sqlx::query("UPDATE rustio_users SET role = $1 WHERE id = $2")
        .bind(role_as_str(new_role))
        .bind(target_user_id)
        .execute(db.pool())
        .await
        .map_err(Error::from)?;

    let outcome = invalidate_sessions(
        db,
        SessionTarget::User {
            user_id: target_user_id,
        },
        SessionInvalidationReason::RoleChangedByOther,
    )
    .await?;

    Ok(PromoteOutcome::Ok {
        previous_role: current_role,
        new_role,
        revoked_session_count: outcome.revoked_session_ids.len(),
    })
}

// ---- emergency_access ----------------------------------------------------

/// Issue a single-use password-reset URL bypassing the email
/// mailer. The URL plaintext is returned in
/// [`EmergencyAccessOutcome::Ok::url_path`] — the operator hands it
/// to the target via whatever out-of-band channel makes sense.
///
/// Reuses R1's `rustio_password_reset_tokens` table: inserts a row
/// keyed by SHA-256(token), returns the plaintext token in the URL
/// path. The plaintext never lands in the DB; the token is single-
/// use per the R1 partial unique index on
/// `(token_hash) WHERE consumed_at IS NULL`.
///
/// `ttl_minutes` is clamped to `[1, 60]` — beyond 60 the operator
/// should use `reset_password` instead (longer TTLs widen the URL
/// interception window for diminishing operational benefit).
///
/// `InactiveTarget` is the only emergency operation that refuses
/// inactive users: issuing a URL to a deactivated account has no
/// recovery semantic.
// public:
pub async fn emergency_access(
    db: &Db,
    target_user_id: i64,
    ttl_minutes: i64,
) -> Result<EmergencyAccessOutcome> {
    let is_active = match target_exists(db, target_user_id).await? {
        Some(active) => active,
        None => return Ok(EmergencyAccessOutcome::UnknownTarget),
    };
    if !is_active {
        return Ok(EmergencyAccessOutcome::InactiveTarget);
    }

    let ttl = ttl_minutes.clamp(1, 60);
    let expires_at = chrono::Utc::now() + chrono::Duration::minutes(ttl);

    // Reuse R1's exact token + hash format. Hand-rolling either
    // here would risk a format drift that bricks the URL on the
    // consume path — see commit #8 smoke where a hex-encoded hash
    // missed the base64-encoded R1 lookup and the framework
    // rendered "This link is no longer valid". Calling these
    // crate-internal helpers ensures the emergency-access URL
    // round-trips through the same machinery as a self-service
    // R1 reset URL.
    let token = crate::auth::sessions::random_token();
    let token_hash = crate::auth::sessions::hash_token_for_storage(&token);

    let token_id: i64 = sqlx::query_scalar(
        "INSERT INTO rustio_password_reset_tokens \
            (user_id, token_hash, expires_at) \
         VALUES ($1, $2, $3) \
         RETURNING id",
    )
    .bind(target_user_id)
    .bind(&token_hash)
    .bind(expires_at)
    .fetch_one(db.pool())
    .await
    .map_err(Error::from)?;

    Ok(EmergencyAccessOutcome::Ok {
        token_id,
        url_path: format!("/admin/reset-password/{token}"),
        expires_at,
    })
}

// ---- Role <-> string helpers --------------------------------------------
//
// `Role` already implements `FromStr` / `Display` somewhere in the
// framework, but the persisted shape (`'administrator'`, lowercase
// snake-case-ish) is what we need here and not all of those impls
// match. Keep the mapping explicit and local until R5 unifies the
// role-string surface.

fn parse_role(s: &str) -> Option<Role> {
    match s {
        "user" => Some(Role::User),
        "staff" => Some(Role::Staff),
        "supervisor" => Some(Role::Supervisor),
        "administrator" => Some(Role::Administrator),
        "developer" => Some(Role::Developer),
        _ => None,
    }
}

fn role_as_str(role: Role) -> &'static str {
    match role {
        Role::User => "user",
        Role::Staff => "staff",
        Role::Supervisor => "supervisor",
        Role::Administrator => "administrator",
        Role::Developer => "developer",
    }
}

// `InvalidationOutcome` is re-exported by `auth::mod` already; this
// `use` keeps the type name reachable in callers that match on it.
#[allow(unused_imports)]
use InvalidationOutcome as _;

// ---- CLI-side helpers (called from rustio-admin-cli) --------------------

/// Generate an alphanumeric temp password of `len` characters. The
/// alphabet excludes visually ambiguous glyphs (`0`/`O`, `1`/`l`/`I`)
/// so an operator reading the password aloud or writing it down by
/// hand has fewer transcription errors. Used by
/// `rustio user reset-password` when `--temp-password` is not
/// supplied.
///
/// The generated value is NOT stored anywhere by this function —
/// the caller passes it through [`reset_password`] which Argon2-
/// hashes it for `rustio_users.password_hash` and then prints the
/// plaintext exactly once.
// public:
pub fn generate_temp_password(len: usize) -> String {
    use rand::Rng;
    // 54 chars: A-Z minus I, O, L; a-z minus i, l, o; 2-9 (no 0 or 1).
    const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";
    let mut rng = rand::thread_rng();
    (0..len)
        .map(|_| ALPHABET[rng.gen_range(0..ALPHABET.len())] as char)
        .collect()
}

/// Produce a fresh hyphenated UUID v7 for use as the CLI-emitted
/// audit row's `correlation_id`. Matches the format the framework's
/// `correlation_id` middleware writes per request, so a future
/// cross-table audit pivot can join framework rows and CLI rows on
/// this column without per-source post-processing.
// public:
pub fn fresh_correlation_id() -> String {
    uuid::Uuid::now_v7().hyphenated().to_string()
}