rustio_admin/admin/audit.rs
1//! Admin action log — every create / update / delete driven through
2//! the admin writes a row to `rustio_admin_actions`. The audit trail
3//! powers two user-visible surfaces:
4//!
5//! - `GET /admin/history` — project-wide timeline.
6//! - `GET /admin/<model>/<id>/history` — per-object history.
7//!
8//! ## Integrity
9//!
10//! [`record`] rejects entries that are missing any of `user_id`,
11//! `model_name`, or `object_id`. The caller gets an
12//! [`Error::Internal`] so the admin handler can fail loudly rather
13//! than silently losing the audit trail.
14
15use chrono::{DateTime, Utc};
16use sqlx::Row as _;
17
18use crate::error::{Error, Result};
19use crate::orm::Db;
20
21pub(crate) const CREATE_TABLE_SQL: &str = "CREATE TABLE IF NOT EXISTS rustio_admin_actions (
22 id BIGSERIAL PRIMARY KEY,
23 user_id BIGINT NOT NULL REFERENCES rustio_users(id) ON DELETE CASCADE,
24 action_type TEXT NOT NULL,
25 model_name TEXT NOT NULL,
26 object_id BIGINT NOT NULL,
27 timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
28 ip_address TEXT,
29 summary TEXT NOT NULL DEFAULT ''
30)";
31
32pub(crate) const CREATE_MODEL_INDEX_SQL: &str =
33 "CREATE INDEX IF NOT EXISTS rustio_admin_actions_model_idx \
34 ON rustio_admin_actions(model_name, object_id)";
35
36pub(crate) const CREATE_TIMESTAMP_INDEX_SQL: &str =
37 "CREATE INDEX IF NOT EXISTS rustio_admin_actions_timestamp_idx \
38 ON rustio_admin_actions(timestamp DESC)";
39
40// public:
41/// Ensure the `rustio_admin_actions` table and its indexes exist.
42/// Idempotent. Depends on `rustio_users` existing first.
43///
44/// 0.4.0 lifecycle additions: `metadata` JSONB, `correlation_id`, and
45/// `session_id`. The framework will populate these as recovery flows
46/// land in R1+; existing audit rows from 0.3.x stay valid with NULLs.
47pub async fn ensure_table(db: &Db) -> Result<()> {
48 sqlx::query(CREATE_TABLE_SQL).execute(db.pool()).await?;
49 sqlx::query(CREATE_MODEL_INDEX_SQL)
50 .execute(db.pool())
51 .await?;
52 sqlx::query(CREATE_TIMESTAMP_INDEX_SQL)
53 .execute(db.pool())
54 .await?;
55
56 // R0 (0.4.0) lifecycle additions — additive, idempotent.
57 sqlx::query("ALTER TABLE rustio_admin_actions ADD COLUMN IF NOT EXISTS metadata JSONB")
58 .execute(db.pool())
59 .await?;
60 sqlx::query("ALTER TABLE rustio_admin_actions ADD COLUMN IF NOT EXISTS correlation_id TEXT")
61 .execute(db.pool())
62 .await?;
63 sqlx::query("ALTER TABLE rustio_admin_actions ADD COLUMN IF NOT EXISTS session_id BIGINT")
64 .execute(db.pool())
65 .await?;
66 sqlx::query(
67 "CREATE INDEX IF NOT EXISTS rustio_admin_actions_correlation_idx \
68 ON rustio_admin_actions (correlation_id) WHERE correlation_id IS NOT NULL",
69 )
70 .execute(db.pool())
71 .await?;
72 sqlx::query(
73 "CREATE INDEX IF NOT EXISTS rustio_admin_actions_session_idx \
74 ON rustio_admin_actions (session_id) WHERE session_id IS NOT NULL",
75 )
76 .execute(db.pool())
77 .await?;
78
79 // 0.8.1 — model_name slug canonicalisation backfill.
80 //
81 // Audit rows from 0.7.x and earlier wrote `model_name` in several
82 // inconsistent conventions: `"User"` (struct name), `"user"`
83 // (lowercase struct), or, on 0.8.0 from the CLI's R4 emergency
84 // commands, `"rustio_users"` (SQL table name). The History page
85 // renders this column as a URL slug, so any non-slug value
86 // produced a `/admin/User/:id` style link that 404'd against the
87 // dispatcher's `admin.find("User")` lookup (the canonical slug
88 // is `"users"`).
89 //
90 // 0.8.1 makes every framework + CLI emission write the admin slug
91 // (`"users"` / `"groups"`) directly. This backfill rewrites the
92 // legacy rows in place so the History page links work
93 // retroactively. Idempotent — once rows are migrated, subsequent
94 // boot calls find no rows to update.
95 //
96 // See `VISIBILITY_AUDIT.md` finding F1.
97 sqlx::query(
98 "UPDATE rustio_admin_actions \
99 SET model_name = 'users' \
100 WHERE model_name IN ('User', 'user', 'rustio_users')",
101 )
102 .execute(db.pool())
103 .await?;
104 sqlx::query(
105 "UPDATE rustio_admin_actions \
106 SET model_name = 'groups' \
107 WHERE model_name IN ('Group', 'group', 'rustio_groups')",
108 )
109 .execute(db.pool())
110 .await?;
111
112 Ok(())
113}
114
115// public:
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum ActionType {
118 Create,
119 Update,
120 Delete,
121}
122
123impl ActionType {
124 // public:
125 pub fn as_str(self) -> &'static str {
126 match self {
127 Self::Create => "create",
128 Self::Update => "update",
129 Self::Delete => "delete",
130 }
131 }
132
133 // public:
134 pub fn parse(s: &str) -> Option<Self> {
135 match s {
136 "create" => Some(Self::Create),
137 "update" => Some(Self::Update),
138 "delete" => Some(Self::Delete),
139 _ => None,
140 }
141 }
142
143 // public:
144 pub fn label(self) -> &'static str {
145 match self {
146 Self::Create => "Created",
147 Self::Update => "Updated",
148 Self::Delete => "Deleted",
149 }
150 }
151
152 // public:
153 pub fn pill_class(self) -> &'static str {
154 match self {
155 Self::Create => "badge-success",
156 Self::Update => "badge-neutral",
157 Self::Delete => "badge-danger",
158 }
159 }
160}
161
162// public:
163#[derive(Debug, Clone)]
164pub struct AdminAction {
165 pub id: i64,
166 pub user_id: i64,
167 pub user_email: Option<String>,
168 pub action_type: String,
169 pub model_name: String,
170 pub object_id: i64,
171 pub timestamp: DateTime<Utc>,
172 pub ip_address: Option<String>,
173 pub summary: String,
174}
175
176// public:
177pub struct LogEntry<'a> {
178 pub user_id: i64,
179 pub action_type: ActionType,
180 pub model_name: &'a str,
181 pub object_id: i64,
182 pub ip_address: Option<&'a str>,
183 pub summary: String,
184 /// Per-request UUID (R0). All audit rows written under one HTTP
185 /// request share this id so a future `/admin/history/<id>` page
186 /// can reconstruct the chain of events ("admin reset password →
187 /// all sessions revoked → security email dispatched").
188 pub correlation_id: Option<&'a str>,
189 /// The session that performed the action, when applicable. CLI
190 /// emergency actions write `None`.
191 pub session_id: Option<i64>,
192 /// Structured before/after / extra metadata. JSONB column.
193 /// R2 emissions populate this with an *object* (not a scalar
194 /// or array) — the merge layer in [`record`] inserts
195 /// `actor_user_id` and similar typed sidecars into the object
196 /// before persistence, and a non-object value disables that
197 /// merge (the row still writes; a warning is logged).
198 pub metadata: Option<serde_json::Value>,
199 /// The acting principal when this row records one user
200 /// performing an action on another (admin password reset,
201 /// admin lock/unlock, admin revoke-sessions, etc.). Persisted
202 /// under `metadata.actor_user_id` — the column itself doesn't
203 /// change.
204 ///
205 /// R2 emissions set this via [`LogEntry::with_actor`]; R0/R1
206 /// emissions leave it `None`. The legacy [`Self::user_id`]
207 /// field continues to carry the actor for backwards-compat
208 /// with `/admin/history`'s "who did what" view; `actor_user_id`
209 /// is the typed mirror that lets metadata consumers (SIEM,
210 /// future per-user audit pivots) read the actor without
211 /// relying on heuristics about which row-shape sets
212 /// `user_id` to actor vs. target.
213 ///
214 /// When `Some(id)` is set and `metadata` is also `Some(obj)`,
215 /// [`record`] inserts the key into the object. If the existing
216 /// metadata already contains `actor_user_id`, the typed-field
217 /// value wins — the struct field is the source of truth.
218 pub actor_user_id: Option<i64>,
219 /// When `Some`, supersedes `action_type.as_str()` as the
220 /// persisted `rustio_admin_actions.action_type` string. Set via
221 /// [`LogEntry::with_event`]; the `action_type` field becomes a
222 /// placeholder in that case (the convention is to pass
223 /// `ActionType::Update`). Used by R1+ recovery / authority /
224 /// identity emissions that need the richer typed vocabulary —
225 /// see `DESIGN_AUDIT.md` §3 + `DESIGN_RECOVERY.md` §6.
226 pub event: Option<AuditEvent>,
227}
228
229impl<'a> LogEntry<'a> {
230 // public:
231 /// Builder helper for the common case (every field that R0
232 /// added defaults to `None`). Existing call sites can migrate
233 /// incrementally.
234 pub fn new(user_id: i64, action_type: ActionType, model_name: &'a str, object_id: i64) -> Self {
235 Self {
236 user_id,
237 action_type,
238 model_name,
239 object_id,
240 ip_address: None,
241 summary: String::new(),
242 correlation_id: None,
243 session_id: None,
244 metadata: None,
245 actor_user_id: None,
246 event: None,
247 }
248 }
249
250 // public:
251 /// Mark this entry as an admin acting on another user. The id
252 /// is persisted under `metadata.actor_user_id` by [`record`],
253 /// not as a separate column. Pair with `.with_event(...)` for
254 /// the canonical R2 admin-action shape, e.g.
255 ///
256 /// ```ignore
257 /// LogEntry::new(target_id, ActionType::Update, "users", target_id)
258 /// .with_event(AuditEvent::PasswordResetByOther)
259 /// .with_actor(admin_identity.user_id)
260 /// ```
261 ///
262 /// Auto-throttle (no actor) leaves this `None`; the row's
263 /// `user_id` column carries the affected user as the
264 /// closest-reasonable subject. See `DESIGN_R2_ORGANISATIONAL.md`
265 /// §5.2.
266 pub fn with_actor(mut self, actor_user_id: i64) -> Self {
267 self.actor_user_id = Some(actor_user_id);
268 self
269 }
270
271 // public:
272 /// Promote this entry's persisted `action_type` string from the
273 /// legacy [`ActionType`] (create/update/delete) trio to the
274 /// richer typed [`AuditEvent`]. The `action_type` field becomes
275 /// a placeholder; the convention is to pass `ActionType::Update`
276 /// to [`Self::new`] and chain `.with_event(...)`.
277 ///
278 /// ```ignore
279 /// let entry = LogEntry::new(user_id, ActionType::Update, "users", user_id)
280 /// .with_event(AuditEvent::PasswordChangedSelf);
281 /// ```
282 ///
283 /// Use this for framework-internal authority + identity +
284 /// recovery audit rows per `DESIGN_AUDIT.md` §3 +
285 /// `DESIGN_RECOVERY.md` §6. Project code that records generic
286 /// CRUD on its own models continues to use [`Self::new`] alone
287 /// with the legacy `ActionType` trio.
288 pub fn with_event(mut self, event: AuditEvent) -> Self {
289 self.event = Some(event);
290 self
291 }
292
293 /// Resolve the persisted `action_type` string. The `event`
294 /// override wins when set; otherwise the legacy `action_type`
295 /// trio's lowercase string is used. Pulled out as a small helper
296 /// so the `record()` insert and any future read-side rendering
297 /// share one resolution rule.
298 pub(crate) fn resolved_action_type(&self) -> &'static str {
299 match self.event {
300 Some(e) => e.as_str(),
301 None => self.action_type.as_str(),
302 }
303 }
304}
305
306/// Merge `actor_user_id` into the persisted `metadata` JSONB column.
307///
308/// - When `actor_user_id` is `None`: returns `metadata` unchanged.
309/// - When `actor_user_id` is `Some(id)` and `metadata` is `None`:
310/// synthesizes `{"actor_user_id": id}`.
311/// - When `actor_user_id` is `Some(id)` and `metadata` is
312/// `Some(object)`: inserts the key, replacing any existing
313/// `actor_user_id` (the typed field wins — it is the source of
314/// truth for the actor association).
315/// - When `actor_user_id` is `Some(id)` and `metadata` is
316/// `Some(scalar | array)`: returns the original metadata
317/// unchanged and emits a `log::warn!`. The merge requires an
318/// object; non-object metadata is a programming error and the
319/// audit row is preferable to silent loss.
320///
321/// Pulled out as a free function so the merge contract is
322/// unit-testable without a database.
323fn build_persisted_metadata(
324 metadata: Option<serde_json::Value>,
325 actor_user_id: Option<i64>,
326) -> Option<serde_json::Value> {
327 let actor = match actor_user_id {
328 None => return metadata,
329 Some(id) => id,
330 };
331
332 match metadata {
333 None => Some(serde_json::json!({ "actor_user_id": actor })),
334 Some(mut value) => {
335 if let Some(obj) = value.as_object_mut() {
336 obj.insert("actor_user_id".to_string(), serde_json::json!(actor));
337 Some(value)
338 } else {
339 log::warn!(
340 "audit::record: actor_user_id={} set but metadata is not a JSON object \
341 ({:?}); writing row without merging actor — fix the call site",
342 actor,
343 value
344 );
345 Some(value)
346 }
347 }
348 }
349}
350
351// public:
352/// Write one row to the action log. Validates required fields before
353/// touching the DB so a broken audit pipeline becomes visible.
354///
355/// `object_id == 0` is reserved for bulk-dispatch rows
356/// (`POST /admin/:model/bulk/:name`): the affected ids live in
357/// `metadata.ids`, and the row's `metadata.kind` is `"bulk_action"`.
358/// The history page can render bulk rows distinctly from per-object
359/// rows by checking that pair. Negative `object_id` values remain
360/// invalid.
361pub async fn record(db: &Db, entry: LogEntry<'_>) -> Result<()> {
362 if entry.user_id <= 0 {
363 return Err(Error::Internal("admin audit: missing user_id".to_string()));
364 }
365 if entry.model_name.trim().is_empty() {
366 return Err(Error::Internal(
367 "admin audit: missing model_name".to_string(),
368 ));
369 }
370 if entry.object_id < 0 {
371 return Err(Error::Internal(
372 "admin audit: object_id must be >= 0 (bulk rows use 0)".to_string(),
373 ));
374 }
375
376 let now = Utc::now();
377 let action_type_str = entry.resolved_action_type();
378 let metadata = build_persisted_metadata(entry.metadata, entry.actor_user_id);
379 sqlx::query(
380 "INSERT INTO rustio_admin_actions
381 (user_id, action_type, model_name, object_id, timestamp, ip_address, summary,
382 correlation_id, session_id, metadata)
383 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
384 )
385 .bind(entry.user_id)
386 .bind(action_type_str)
387 .bind(entry.model_name)
388 .bind(entry.object_id)
389 .bind(now)
390 .bind(entry.ip_address)
391 .bind(&entry.summary)
392 .bind(entry.correlation_id)
393 .bind(entry.session_id)
394 .bind(metadata.as_ref())
395 .execute(db.pool())
396 .await?;
397 Ok(())
398}
399
400// public:
401/// Typed representation of every audit `action_type` the framework
402/// emits for authority + identity + recovery actions.
403///
404/// **Public-API stability (0.5.0):** the enum is `pub` from R1
405/// onwards (doctrine 18). External consumers — SIEM tooling, custom
406/// dashboards, integration tests — can match on these variants
407/// instead of (or in addition to) the persisted strings. The
408/// `as_str()` mapping is the single canonical boundary between the
409/// typed surface and the `rustio_admin_actions.action_type` TEXT
410/// column. Every existing variant's string is locked-in by the
411/// `audit_event_existing_variants_have_stable_strings` test below;
412/// renaming a string is a breaking change requiring a major version
413/// bump.
414///
415/// **Coexistence with `ActionType`:** the legacy
416/// `ActionType::{Create, Update, Delete}` trio writes the strings
417/// `"create" / "update" / "delete"`, used for generic CRUD on
418/// project-registered models. `AuditEvent` strings are richer
419/// (`"user_created"`, `"password_reset_self_consume"`, …) and used
420/// for the framework's own authority + identity + recovery surfaces.
421/// The two vocabularies are disjoint by design;
422/// `action_type_and_audit_event_vocabularies_dont_collide` asserts
423/// the disjointness.
424///
425/// **Future-extensibility:** `#[non_exhaustive]` lets future
426/// R-phases (R2 / R3 / R4) add variants without breaking external
427/// matchers. Variants whose call-sites haven't shipped yet are
428/// listed here in anticipation — `as_str()` returns the canonical
429/// string regardless of whether anything emits it. The roadmap
430/// in `DESIGN_RECOVERY.md` §16 + `ROADMAP.md` covers when each
431/// variant lights up.
432#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
433#[non_exhaustive]
434pub enum AuditEvent {
435 // ---- User / Group authority CRUD (R0+) ----
436 UserCreated,
437 UserUpdated,
438 UserDeleted,
439 GroupCreated,
440 GroupUpdated,
441 GroupDeleted,
442 // ---- Password lifecycle (R1+) ----
443 /// Authenticated user changed their own password via
444 /// `/admin/password_change`. R1 commit #11 wires emission.
445 PasswordChangedSelf,
446 /// Anonymous user requested a password-reset email via
447 /// `/admin/forgot-password`. R1 commit #7 wires emission.
448 PasswordResetSelfRequest,
449 /// Anonymous user consumed a reset token + set a new password
450 /// via `/admin/reset-password/<token>`. R1 commit #7 wires
451 /// emission.
452 PasswordResetSelfConsume,
453 /// An administrator reset another user's password. R2 wires
454 /// emission via the dedicated `/admin/users/<id>/reset-password`
455 /// route.
456 PasswordResetByOther,
457 /// A user with `must_change_password = TRUE` completed the
458 /// forced rotation via `POST /admin/must-change-password`,
459 /// clearing the flag and (per `DESIGN_R2_ORGANISATIONAL.md`
460 /// §3.4) revoking every other session for the same user.
461 /// `metadata.triggered_by_audit_id` links back to the
462 /// originating `PasswordResetByOther` row;
463 /// `metadata.invalidated_session_count` records how many
464 /// sessions were revoked. R2 commit #12 wires emission.
465 ForcedPasswordChangeCompleted,
466 // ---- Account state (R2+) ----
467 AccountLocked,
468 AccountUnlocked,
469 // ---- MFA (R3+) ----
470 MfaEnabled,
471 MfaDisabled,
472 MfaResetByOther,
473 /// A user consumed a backup code as the second factor on
474 /// the login or re-auth flow. Emitted by
475 /// `auth::mfa::consume_backup_code` (R3 commit #8).
476 /// `metadata.code_id` identifies which code was used;
477 /// `metadata.remaining_codes` tracks the unused-code count
478 /// post-consume so the user can be nudged toward
479 /// regeneration before exhaustion;
480 /// `metadata.via = "login" | "reauth"` distinguishes the
481 /// caller context.
482 MfaCodeConsumed,
483 /// A user regenerated their backup-code batch. Emitted by
484 /// `auth::mfa::regenerate_backup_codes` (R3 commit #10).
485 /// The DELETE + INSERT runs in one transaction per D3 of
486 /// the design (atomic regeneration; the old batch is
487 /// unrecoverable from the moment the transaction commits).
488 /// `metadata.previous_codes_invalidated` records the
489 /// count of rows the DELETE removed (used + unused
490 /// combined); `metadata.new_codes_count` is locked at 8
491 /// per Appendix B.
492 BackupCodesRegenerated,
493 // ---- Session lifecycle (R0/R1+) ----
494 SessionsRevokedSelf,
495 SessionsRevokedByOther,
496 SessionLogout,
497 // ---- Layer-3 CLI (R4+) ----
498 /// Emergency-recovery operation initiated from the `rustio`
499 /// CLI binary. Subsumes every `rustio user <op>` emergency
500 /// subcommand — the specific operation lives in
501 /// `metadata.cli_operation` (`"reset_password" | "unlock" |
502 /// "disable_mfa" | "promote" | "emergency_access"`). The
503 /// OS-level actor identity lives in `metadata.os_actor`
504 /// (`<whoami>@<hostname>`).
505 ///
506 /// **CLI-only invariant (D12).** This variant must NOT be
507 /// emitted from any framework HTTP handler. The web surface
508 /// has its own audit variants (`PasswordResetByOther`,
509 /// `MfaResetByOther`, etc.); collapsing those into
510 /// `EmergencyRecovery` would lose the distinction between
511 /// "admin acted via the web" and "operator went around every
512 /// other tier via shell." A grep-based unit test (see
513 /// `audit::tests::emergency_recovery_is_cli_only`) enforces
514 /// this by walking `crates/rustio-admin/src/` and asserting
515 /// zero callsites; the variant is exercised only from
516 /// `crates/rustio-admin-cli/src/`.
517 ///
518 /// See `DESIGN_R4_EMERGENCY.md` §5 for the full metadata
519 /// schema and §10 doctrine D12.
520 EmergencyRecovery,
521}
522
523impl AuditEvent {
524 // public:
525 /// Stable lowercase identifier persisted as
526 /// `rustio_admin_actions.action_type`.
527 ///
528 /// **Stability contract:** every string returned here is
529 /// part of the public API from 0.5.0 onwards. Existing values
530 /// are locked-in by
531 /// `audit_event_existing_variants_have_stable_strings` and
532 /// changing one is a breaking change requiring a major bump.
533 /// New `AuditEvent` variants may be added in minor versions
534 /// (the enum is `#[non_exhaustive]`); each new variant ships
535 /// with its locked string from day one.
536 pub const fn as_str(self) -> &'static str {
537 match self {
538 Self::UserCreated => "user_created",
539 Self::UserUpdated => "user_updated",
540 Self::UserDeleted => "user_deleted",
541 Self::GroupCreated => "group_created",
542 Self::GroupUpdated => "group_updated",
543 Self::GroupDeleted => "group_deleted",
544 Self::PasswordChangedSelf => "password_changed_self",
545 Self::PasswordResetSelfRequest => "password_reset_self_request",
546 Self::PasswordResetSelfConsume => "password_reset_self_consume",
547 Self::PasswordResetByOther => "password_reset_by_other",
548 Self::ForcedPasswordChangeCompleted => "forced_password_change_completed",
549 Self::AccountLocked => "account_locked",
550 Self::AccountUnlocked => "account_unlocked",
551 Self::MfaEnabled => "mfa_enabled",
552 Self::MfaDisabled => "mfa_disabled",
553 Self::MfaResetByOther => "mfa_reset_by_other",
554 Self::MfaCodeConsumed => "mfa_code_consumed",
555 Self::BackupCodesRegenerated => "backup_codes_regenerated",
556 Self::SessionsRevokedSelf => "sessions_revoked_self",
557 Self::SessionsRevokedByOther => "sessions_revoked_by_other",
558 Self::SessionLogout => "session_logout",
559 Self::EmergencyRecovery => "emergency_recovery",
560 }
561 }
562}
563
564// public:
565/// Fetch the most recent `limit` admin actions, newest first.
566pub async fn recent(
567 db: &Db,
568 limit: i64,
569 model_filter: Option<&str>,
570 action_filter: Option<&str>,
571) -> Result<Vec<AdminAction>> {
572 let mut sql = String::from(
573 "SELECT a.id, a.user_id, u.email AS user_email, a.action_type,
574 a.model_name, a.object_id, a.timestamp, a.ip_address, a.summary
575 FROM rustio_admin_actions a
576 LEFT JOIN rustio_users u ON u.id = a.user_id",
577 );
578 let mut clauses: Vec<String> = Vec::new();
579 let mut param_idx: usize = 1;
580 if model_filter.is_some() {
581 clauses.push(format!("a.model_name = ${param_idx}"));
582 param_idx += 1;
583 }
584 if action_filter.is_some() {
585 clauses.push(format!("a.action_type = ${param_idx}"));
586 param_idx += 1;
587 }
588 if !clauses.is_empty() {
589 sql.push_str(" WHERE ");
590 sql.push_str(&clauses.join(" AND "));
591 }
592 sql.push_str(&format!(
593 " ORDER BY a.timestamp DESC, a.id DESC LIMIT ${param_idx}"
594 ));
595
596 let mut q = sqlx::query(&sql);
597 if let Some(m) = model_filter {
598 q = q.bind(m);
599 }
600 if let Some(a) = action_filter {
601 q = q.bind(a);
602 }
603 q = q.bind(limit);
604
605 let rows = q.fetch_all(db.pool()).await?;
606 rows.iter().map(row_to_action).collect()
607}
608
609// public:
610/// All actions for one `(model, object_id)`, newest first.
611pub async fn for_object(db: &Db, model_name: &str, object_id: i64) -> Result<Vec<AdminAction>> {
612 let rows = sqlx::query(
613 "SELECT a.id, a.user_id, u.email AS user_email, a.action_type,
614 a.model_name, a.object_id, a.timestamp, a.ip_address, a.summary
615 FROM rustio_admin_actions a
616 LEFT JOIN rustio_users u ON u.id = a.user_id
617 WHERE a.model_name = $1 AND a.object_id = $2
618 ORDER BY a.timestamp DESC, a.id DESC",
619 )
620 .bind(model_name)
621 .bind(object_id)
622 .fetch_all(db.pool())
623 .await?;
624 rows.iter().map(row_to_action).collect()
625}
626
627fn row_to_action(r: &sqlx::postgres::PgRow) -> Result<AdminAction> {
628 Ok(AdminAction {
629 id: r.try_get("id")?,
630 user_id: r.try_get("user_id")?,
631 user_email: r.try_get("user_email")?,
632 action_type: r.try_get("action_type")?,
633 model_name: r.try_get("model_name")?,
634 object_id: r.try_get("object_id")?,
635 timestamp: r.try_get("timestamp")?,
636 ip_address: r.try_get("ip_address")?,
637 summary: r.try_get("summary")?,
638 })
639}
640
641#[cfg(test)]
642mod tests {
643 use super::*;
644
645 /// Single source of truth for every `AuditEvent` variant the
646 /// framework currently exposes. Drift tests below iterate over
647 /// this constant; adding a new variant means adding it here.
648 /// CHANGELOG / DESIGN_AUDIT.md call out variant additions.
649 const ALL_AUDIT_EVENTS: &[AuditEvent] = &[
650 AuditEvent::UserCreated,
651 AuditEvent::UserUpdated,
652 AuditEvent::UserDeleted,
653 AuditEvent::GroupCreated,
654 AuditEvent::GroupUpdated,
655 AuditEvent::GroupDeleted,
656 AuditEvent::PasswordChangedSelf,
657 AuditEvent::PasswordResetSelfRequest,
658 AuditEvent::PasswordResetSelfConsume,
659 AuditEvent::PasswordResetByOther,
660 AuditEvent::ForcedPasswordChangeCompleted,
661 AuditEvent::AccountLocked,
662 AuditEvent::AccountUnlocked,
663 AuditEvent::MfaEnabled,
664 AuditEvent::MfaDisabled,
665 AuditEvent::MfaResetByOther,
666 AuditEvent::MfaCodeConsumed,
667 AuditEvent::BackupCodesRegenerated,
668 AuditEvent::SessionsRevokedSelf,
669 AuditEvent::SessionsRevokedByOther,
670 AuditEvent::SessionLogout,
671 AuditEvent::EmergencyRecovery,
672 ];
673
674 /// Drift test (doctrine 18): every variant's `as_str()` is
675 /// unique. Catches copy-paste collisions when adding variants
676 /// — `password_reset_self_request` vs
677 /// `password_reset_self_consume` are easy to mis-paste.
678 #[test]
679 fn audit_event_strings_are_unique() {
680 let mut set = std::collections::HashSet::new();
681 for &e in ALL_AUDIT_EVENTS {
682 assert!(set.insert(e.as_str()), "duplicate as_str() for {e:?}");
683 }
684 assert_eq!(set.len(), ALL_AUDIT_EVENTS.len());
685 }
686
687 /// Every `AuditEvent` string is snake_case ASCII. Future SIEM
688 /// integrations tokenise on these — keep them pre-normalised.
689 #[test]
690 fn audit_event_strings_are_snake_case() {
691 for &e in ALL_AUDIT_EVENTS {
692 let s = e.as_str();
693 assert!(!s.is_empty(), "{e:?} as_str is empty");
694 assert!(
695 s.chars()
696 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'),
697 "{e:?}.as_str() = {s:?} is not snake_case"
698 );
699 }
700 }
701
702 /// R1 commit #6: `PasswordChangedSelf` maps to the locked string
703 /// `"password_changed_self"`. The string is part of the public
704 /// API contract from 0.5.0; renaming requires a major bump.
705 #[test]
706 fn audit_event_password_changed_self_maps_correctly() {
707 assert_eq!(
708 AuditEvent::PasswordChangedSelf.as_str(),
709 "password_changed_self"
710 );
711 }
712
713 /// Stability contract for the public API: every existing
714 /// variant's string value is locked-in here. A change to any of
715 /// these strings is a breaking change requiring a major bump
716 /// (the persisted `rustio_admin_actions.action_type` column
717 /// would have rows referencing the old string from prior
718 /// installations). New variants may extend this list; existing
719 /// rows must keep their strings.
720 #[test]
721 fn audit_event_existing_variants_have_stable_strings() {
722 assert_eq!(AuditEvent::UserCreated.as_str(), "user_created");
723 assert_eq!(AuditEvent::UserUpdated.as_str(), "user_updated");
724 assert_eq!(AuditEvent::UserDeleted.as_str(), "user_deleted");
725 assert_eq!(AuditEvent::GroupCreated.as_str(), "group_created");
726 assert_eq!(AuditEvent::GroupUpdated.as_str(), "group_updated");
727 assert_eq!(AuditEvent::GroupDeleted.as_str(), "group_deleted");
728 assert_eq!(
729 AuditEvent::PasswordChangedSelf.as_str(),
730 "password_changed_self"
731 );
732 assert_eq!(
733 AuditEvent::PasswordResetSelfRequest.as_str(),
734 "password_reset_self_request"
735 );
736 assert_eq!(
737 AuditEvent::PasswordResetSelfConsume.as_str(),
738 "password_reset_self_consume"
739 );
740 assert_eq!(
741 AuditEvent::PasswordResetByOther.as_str(),
742 "password_reset_by_other"
743 );
744 assert_eq!(
745 AuditEvent::ForcedPasswordChangeCompleted.as_str(),
746 "forced_password_change_completed"
747 );
748 assert_eq!(AuditEvent::AccountLocked.as_str(), "account_locked");
749 assert_eq!(AuditEvent::AccountUnlocked.as_str(), "account_unlocked");
750 assert_eq!(AuditEvent::MfaEnabled.as_str(), "mfa_enabled");
751 assert_eq!(AuditEvent::MfaDisabled.as_str(), "mfa_disabled");
752 assert_eq!(AuditEvent::MfaResetByOther.as_str(), "mfa_reset_by_other");
753 assert_eq!(AuditEvent::MfaCodeConsumed.as_str(), "mfa_code_consumed");
754 assert_eq!(
755 AuditEvent::BackupCodesRegenerated.as_str(),
756 "backup_codes_regenerated"
757 );
758 assert_eq!(
759 AuditEvent::SessionsRevokedSelf.as_str(),
760 "sessions_revoked_self"
761 );
762 assert_eq!(
763 AuditEvent::SessionsRevokedByOther.as_str(),
764 "sessions_revoked_by_other"
765 );
766 assert_eq!(AuditEvent::SessionLogout.as_str(), "session_logout");
767 assert_eq!(AuditEvent::EmergencyRecovery.as_str(), "emergency_recovery");
768 }
769
770 /// `ActionType` and `AuditEvent` are intentionally separate
771 /// vocabularies — `ActionType` writes generic CRUD strings
772 /// (`"create" / "update" / "delete"`) for project-registered
773 /// models; `AuditEvent` writes the framework's richer authority,
774 /// identity, and recovery vocabulary. The two namespaces must
775 /// stay disjoint so a SIEM consumer can route on the string
776 /// alone without disambiguation.
777 #[test]
778 fn action_type_and_audit_event_vocabularies_dont_collide() {
779 let action_type_strs = [
780 ActionType::Create.as_str(),
781 ActionType::Update.as_str(),
782 ActionType::Delete.as_str(),
783 ];
784 let mut set = std::collections::HashSet::new();
785 for s in action_type_strs {
786 assert!(set.insert(s), "duplicate ActionType string {s:?}");
787 }
788 for &e in ALL_AUDIT_EVENTS {
789 assert!(
790 set.insert(e.as_str()),
791 "AuditEvent::{:?} ({:?}) collides with ActionType",
792 e,
793 e.as_str()
794 );
795 }
796 assert_eq!(set.len(), action_type_strs.len() + ALL_AUDIT_EVENTS.len());
797 }
798
799 /// Doctrine D12 enforcement (`DESIGN_R4_EMERGENCY.md` §10).
800 ///
801 /// `AuditEvent::EmergencyRecovery` is the CLI-only audit
802 /// signal: any emission from a framework HTTP handler would
803 /// collapse the "operator went around every other tier via
804 /// shell" distinction into the regular web-driven audit
805 /// vocabulary. This test walks `crates/rustio-admin/src/`
806 /// (the framework crate) and asserts that no source file —
807 /// other than this file, where the variant is declared,
808 /// documented, mapped, and stability-tested — names
809 /// `AuditEvent::EmergencyRecovery` in CODE.
810 ///
811 /// The narrower `AuditEvent::EmergencyRecovery` qualified
812 /// form (not bare `EmergencyRecovery`) is checked
813 /// deliberately: `SessionInvalidationReason::EmergencyRecovery`
814 /// is a separate enum the framework legitimately uses when
815 /// CLI-driven session invalidations land via
816 /// `auth::sessions::invalidate_sessions`. Doctrine D12
817 /// scopes to the audit variant alone.
818 ///
819 /// Implementation: line-comment-stripped grep. A real
820 /// emission cannot hide inside a `//` comment.
821 #[test]
822 fn emergency_recovery_is_cli_only() {
823 let framework_src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
824 let self_file = framework_src.join("admin/audit.rs");
825
826 let mut offenders: Vec<String> = Vec::new();
827 walk_rs_files_admin_audit(&framework_src, &mut |path: &std::path::Path| {
828 if path == self_file {
829 return;
830 }
831 let content = std::fs::read_to_string(path)
832 .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
833 for (line_no, raw_line) in content.lines().enumerate() {
834 // Strip `//` line comments. Don't try to parse `/*
835 // ... */`; framework code uses `//` and `///`
836 // exclusively (verified by inspection).
837 let code = match raw_line.find("//") {
838 Some(idx) => &raw_line[..idx],
839 None => raw_line,
840 };
841 if code.contains("AuditEvent::EmergencyRecovery") {
842 offenders.push(format!(
843 "{}:{}: {}",
844 path.display(),
845 line_no + 1,
846 raw_line.trim()
847 ));
848 }
849 }
850 });
851 assert!(
852 offenders.is_empty(),
853 "framework crate must not reference `AuditEvent::EmergencyRecovery` \
854 in CODE (it is a CLI-only audit variant per \
855 `DESIGN_R4_EMERGENCY.md` §10 D12). Move the emission to \
856 crates/rustio-admin-cli/, or introduce a new AuditEvent variant \
857 for the web-side action:\n {}",
858 offenders.join("\n ")
859 );
860 }
861
862 /// `VISIBILITY_AUDIT.md` finding F1 enforcement.
863 ///
864 /// `rustio_admin_actions.model_name` MUST be the admin slug
865 /// (the value the dispatcher's `admin.find(model_name)` looks
866 /// up), so the History page's link `<a href="/admin/{model_name}/{id}">`
867 /// resolves to a real admin entry. Pre-0.8.1, callsites
868 /// drifted into four conventions: `"User"` (struct name),
869 /// `"user"` (lowercase struct), `"rustio_users"` (SQL table
870 /// name from the R4 CLI), and the correct `"users"` (admin
871 /// slug). Three of the four 404'd.
872 ///
873 /// This test walks every `.rs` file in `crates/rustio-admin/src/`
874 /// looking for `model_name: "<legacy>"` and `LogEntry::new(_, _, "<legacy>", _)`
875 /// patterns. Doc comments and tests in this file (`admin/audit.rs`)
876 /// are skipped because the file is the contract surface where
877 /// the legacy strings are documented as failure cases.
878 ///
879 /// If this test fails with a new offender, the fix is one of:
880 /// - change the literal to the admin slug (`"users"` /
881 /// `"groups"` / your project's `M::ADMIN_NAME`);
882 /// - if the model is a project-registered model not built into
883 /// the framework, use the value of `M::ADMIN_NAME` from the
884 /// `RustioAdmin` derive directly.
885 #[test]
886 fn model_name_uses_admin_slug_not_struct_name() {
887 let framework_src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
888 let self_file = framework_src.join("admin/audit.rs");
889
890 // Patterns that previously appeared in code and resolve to
891 // 404 against the dispatcher. The negative list intentionally
892 // excludes `"users"` and `"groups"` — those ARE the
893 // canonical admin slugs.
894 let legacy_patterns: &[&str] = &[
895 r#""User""#,
896 r#""user""#,
897 r#""Group""#,
898 r#""group""#,
899 r#""rustio_users""#,
900 r#""rustio_groups""#,
901 ];
902
903 let mut offenders: Vec<String> = Vec::new();
904 walk_rs_files_admin_audit(&framework_src, &mut |path: &std::path::Path| {
905 if path == self_file {
906 return;
907 }
908 let content = std::fs::read_to_string(path)
909 .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
910 for (line_no, raw_line) in content.lines().enumerate() {
911 // Strip `//` line comments.
912 let code = match raw_line.find("//") {
913 Some(idx) => &raw_line[..idx],
914 None => raw_line,
915 };
916 // Only flag lines that ALSO look like audit-emission
917 // contexts. Bare `"user"` strings in role.rs etc. are
918 // legitimate (Role::User stringification, not audit
919 // model_name) — those callsites do NOT contain
920 // either `LogEntry` or `model_name:`.
921 let looks_like_audit_emission = code.contains("LogEntry")
922 || code.contains("model_name:")
923 || code.contains("model_name ==")
924 || code.contains("model_name =");
925 if !looks_like_audit_emission {
926 continue;
927 }
928 for pat in legacy_patterns {
929 if code.contains(pat) {
930 offenders.push(format!(
931 "{}:{}: {}",
932 path.display(),
933 line_no + 1,
934 raw_line.trim()
935 ));
936 break;
937 }
938 }
939 }
940 });
941 assert!(
942 offenders.is_empty(),
943 "audit row emissions must write the admin slug (not struct \
944 name / SQL table name) as `model_name`. The History page \
945 renders this column as a URL slug; non-slug values 404. \
946 See `VISIBILITY_AUDIT.md` F1.\n {}",
947 offenders.join("\n ")
948 );
949 }
950
951 /// std-only recursive walker dedicated to this test. Mirrors
952 /// the `walk_rs_files` helper used by
953 /// `templates::tests::every_handler_rendered_template_resolves`;
954 /// duplicated here so the audit test stays self-contained.
955 fn walk_rs_files_admin_audit(root: &std::path::Path, visit: &mut dyn FnMut(&std::path::Path)) {
956 let entries = match std::fs::read_dir(root) {
957 Ok(e) => e,
958 Err(_) => return,
959 };
960 for entry in entries.flatten() {
961 let path = entry.path();
962 let file_type = match entry.file_type() {
963 Ok(ft) => ft,
964 Err(_) => continue,
965 };
966 if file_type.is_dir() {
967 walk_rs_files_admin_audit(&path, visit);
968 } else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
969 visit(&path);
970 }
971 }
972 }
973
974 // ---- LogEntry::with_event ----
975
976 #[test]
977 fn log_entry_with_event_overrides_action_type_persistence() {
978 // Without with_event(), the legacy ActionType wins.
979 let entry = LogEntry::new(1, ActionType::Update, "users", 1);
980 assert_eq!(entry.resolved_action_type(), "update");
981
982 // with_event() promotes to the richer AuditEvent string.
983 let entry = LogEntry::new(1, ActionType::Update, "users", 1)
984 .with_event(AuditEvent::PasswordChangedSelf);
985 assert_eq!(entry.resolved_action_type(), "password_changed_self");
986
987 // Different events resolve to their canonical string.
988 let entry = LogEntry::new(1, ActionType::Update, "users", 1)
989 .with_event(AuditEvent::PasswordResetSelfRequest);
990 assert_eq!(entry.resolved_action_type(), "password_reset_self_request");
991
992 let entry = LogEntry::new(1, ActionType::Update, "users", 1)
993 .with_event(AuditEvent::PasswordResetSelfConsume);
994 assert_eq!(entry.resolved_action_type(), "password_reset_self_consume");
995 }
996
997 #[test]
998 fn log_entry_default_event_is_none() {
999 // Backwards-compat: legacy callers continue to work.
1000 let entry = LogEntry::new(1, ActionType::Create, "post", 99);
1001 assert!(entry.event.is_none());
1002 assert_eq!(entry.resolved_action_type(), "create");
1003 }
1004
1005 // ---- LogEntry::with_actor + build_persisted_metadata (R2 #7) -----------
1006
1007 #[test]
1008 fn log_entry_with_actor_sets_field() {
1009 let entry = LogEntry::new(1, ActionType::Update, "users", 1).with_actor(7);
1010 assert_eq!(entry.actor_user_id, Some(7));
1011 }
1012
1013 #[test]
1014 fn log_entry_default_actor_user_id_is_none() {
1015 // R0/R1 emissions leave actor_user_id None — only R2 admin
1016 // actions opt in via .with_actor(...).
1017 let entry = LogEntry::new(1, ActionType::Update, "users", 1);
1018 assert!(entry.actor_user_id.is_none());
1019 }
1020
1021 #[test]
1022 fn merge_returns_metadata_unchanged_when_no_actor() {
1023 // None actor means no merge — even an existing
1024 // actor_user_id key in the input is preserved verbatim.
1025 let original = serde_json::json!({"reason": "x", "actor_user_id": 99});
1026 let out = build_persisted_metadata(Some(original.clone()), None);
1027 assert_eq!(out.unwrap(), original);
1028
1029 // None metadata + None actor → None.
1030 assert!(build_persisted_metadata(None, None).is_none());
1031 }
1032
1033 #[test]
1034 fn merge_synthesizes_object_when_metadata_is_none() {
1035 let out = build_persisted_metadata(None, Some(7)).unwrap();
1036 assert_eq!(out, serde_json::json!({"actor_user_id": 7}));
1037 }
1038
1039 #[test]
1040 fn merge_inserts_into_existing_object() {
1041 let input = serde_json::json!({"reason": "support ticket", "mode": "email"});
1042 let out = build_persisted_metadata(Some(input), Some(7)).unwrap();
1043 assert_eq!(
1044 out,
1045 serde_json::json!({
1046 "reason": "support ticket",
1047 "mode": "email",
1048 "actor_user_id": 7
1049 })
1050 );
1051 }
1052
1053 #[test]
1054 fn merge_typed_actor_wins_over_existing_metadata_key() {
1055 // Doctrine: the LogEntry struct field is the source of
1056 // truth for the actor association. A handler that puts
1057 // actor_user_id directly into metadata gets overridden
1058 // when it also sets the typed field — preventing
1059 // accidental inconsistency between the JSON key and the
1060 // struct.
1061 let input = serde_json::json!({"actor_user_id": 999, "extra": "x"});
1062 let out = build_persisted_metadata(Some(input), Some(7)).unwrap();
1063 assert_eq!(out, serde_json::json!({"actor_user_id": 7, "extra": "x"}));
1064 }
1065
1066 #[test]
1067 fn merge_passes_through_non_object_metadata_with_warning() {
1068 // Non-object metadata is a programming bug. The merge
1069 // returns the original value unchanged so the row still
1070 // writes (audit-row-loss is worse than missing actor
1071 // metadata); a log::warn in the runtime path surfaces
1072 // the bug. Here we just assert the row preserves shape.
1073 let input = serde_json::json!(42);
1074 let out = build_persisted_metadata(Some(input.clone()), Some(7)).unwrap();
1075 assert_eq!(out, input);
1076
1077 let input = serde_json::json!(["a", "b"]);
1078 let out = build_persisted_metadata(Some(input.clone()), Some(7)).unwrap();
1079 assert_eq!(out, input);
1080
1081 let input = serde_json::json!("scalar");
1082 let out = build_persisted_metadata(Some(input.clone()), Some(7)).unwrap();
1083 assert_eq!(out, input);
1084 }
1085
1086 /// The legacy `ActionType::parse` is a partial parser — it only
1087 /// recognises the original create/update/delete trio. Strings
1088 /// emitted by `AuditEvent` (and any free-form legacy strings
1089 /// already in older `rustio_admin_actions` rows) return `None`,
1090 /// which the render layer maps to a neutral pill class without
1091 /// panicking. This pins the property so a future change to
1092 /// `ActionType::parse` doesn't accidentally start matching
1093 /// AuditEvent strings.
1094 #[test]
1095 fn legacy_action_type_parser_returns_none_on_unknown_strings() {
1096 // Legacy trio still parses.
1097 assert_eq!(ActionType::parse("create"), Some(ActionType::Create));
1098 assert_eq!(ActionType::parse("update"), Some(ActionType::Update));
1099 assert_eq!(ActionType::parse("delete"), Some(ActionType::Delete));
1100
1101 // Every AuditEvent string is unrecognised by the legacy
1102 // parser — the render layer falls through to "badge-neutral"
1103 // for these, which is the documented behaviour.
1104 for &e in ALL_AUDIT_EVENTS {
1105 assert!(
1106 ActionType::parse(e.as_str()).is_none(),
1107 "ActionType::parse should not recognise AuditEvent string {:?}",
1108 e.as_str()
1109 );
1110 }
1111
1112 // Pure garbage and free-form legacy strings.
1113 assert!(ActionType::parse("garbage").is_none());
1114 assert!(ActionType::parse("").is_none());
1115 assert!(ActionType::parse("CREATE").is_none()); // case-sensitive
1116 }
1117}