Skip to main content

renox_core/
audit.rs

1//! An audit trail: who did what, to which record, from where. Opt in with
2//! `App::module(Audit)`, which also records every auth event (logins,
3//! failed logins, lockouts, password and profile changes, deleted
4//! accounts). Record the app's own actions with [`record`]:
5//!
6//! ```
7//! use renox::prelude::*;
8//! use renox::audit::{self, Audit, Entry};
9//!
10//! # fn app() -> App {
11//! App::new().module(Auth::new()).module(Audit)
12//! # }
13//! async fn refund(State(db): State<Db>, user: AuthUser, ClientIp(ip): ClientIp) -> Result<&'static str> {
14//!     // … refund order 42 …
15//!     audit::record(
16//!         &db,
17//!         Entry::new("order.refunded")
18//!             .user(user.id)
19//!             .subject("orders", 42)
20//!             .data(json!({ "amount": 75_000 }))
21//!             .ip(ip),
22//!     )
23//!     .await?;
24//!     let recent = audit::for_subject(&db, "orders", 42, 20).await?; // newest first
25//!     # let _ = recent;
26//!     Ok("refunded")
27//! }
28//! # let _ = (app, refund);
29//! ```
30//!
31//! `rnx audit:prune --days 365` deletes older entries.
32
33use std::net::IpAddr;
34use std::time::Duration;
35
36use serde::Serialize;
37use serde_json::{Value, json};
38
39use crate::auth::events::{
40    AccountDeleted, EmailVerified, LockedOut, LoggedIn, LoggedOut, LoginFailed,
41    OtherDevicesLoggedOut, PasswordChanged, PasswordReset, ProfileUpdated, Registered,
42};
43use crate::db::{DateTime, Db, DbValue, Migration, Row, now, sql};
44use crate::settings::SettingsChanged;
45use crate::{AppState, Module, Registry, Result, Routes};
46
47const MIGRATIONS: &[Migration] = &[crate::db::framework_migration!(
48    "audit",
49    "00010101000600_create_audit_logs_table"
50)];
51
52/// Adds the `audit_logs` table, records auth events, and the
53/// `audit:prune` command.
54pub struct Audit;
55
56impl Module for Audit {
57    fn name(&self) -> &'static str {
58        "audit"
59    }
60
61    fn migrations(&self) -> &'static [Migration] {
62        MIGRATIONS
63    }
64
65    fn routes(&self) -> Routes {
66        Routes::new()
67    }
68
69    fn register(&self, app: &mut Registry) {
70        app.listen(|e: Registered, s| log(s, Entry::new("auth.registered").user(e.user_id)))
71            .listen(|e: LoggedIn, s| {
72                let data = json!({ "via": e.via });
73                log(
74                    s,
75                    Entry::new("auth.login")
76                        .user(e.user_id)
77                        .data(data)
78                        .ip_text(e.ip),
79                )
80            })
81            .listen(|e: LoginFailed, s| {
82                let data = json!({ "email": e.email });
83                log(s, Entry::new("auth.login_failed").data(data).ip_text(e.ip))
84            })
85            .listen(|e: LockedOut, s| {
86                let data = json!({ "email": e.email, "seconds": e.seconds });
87                log(s, Entry::new("auth.locked_out").data(data).ip_text(e.ip))
88            })
89            .listen(|e: LoggedOut, s| log(s, Entry::new("auth.logout").user(e.user_id)))
90            .listen(|e: PasswordReset, s| log(s, Entry::new("auth.password_reset").user(e.user_id)))
91            .listen(|e: PasswordChanged, s| {
92                log(s, Entry::new("auth.password_changed").user(e.user_id))
93            })
94            .listen(|e: EmailVerified, s| log(s, Entry::new("auth.email_verified").user(e.user_id)))
95            .listen(|e: ProfileUpdated, s| {
96                let data = json!({ "email_changed": e.email_changed });
97                log(
98                    s,
99                    Entry::new("auth.profile_updated")
100                        .user(e.user_id)
101                        .data(data),
102                )
103            })
104            .listen(|e: OtherDevicesLoggedOut, s| {
105                log(
106                    s,
107                    Entry::new("auth.other_devices_logged_out").user(e.user_id),
108                )
109            })
110            .listen(|e: AccountDeleted, s| {
111                let data = json!({ "email": e.email });
112                log(
113                    s,
114                    Entry::new("auth.account_deleted")
115                        .user(e.user_id)
116                        .data(data),
117                )
118            });
119        // Sealed groups arrive with `null` values: only the field names.
120        app.listen(|e: SettingsChanged, s| {
121            let data = json!({
122                "key": e.key,
123                "scope": e.scope,
124                "changed": e.changed,
125                "previous": e.previous,
126                "current": e.current,
127            });
128            let mut entry = Entry::new("settings.changed").data(data);
129            if let Some(user_id) = e.actor {
130                entry = entry.user(user_id);
131            }
132            log(s, entry)
133        });
134        app.command(
135            "audit:prune",
136            "Delete audit entries older than --days (default 365)",
137            |args, state| async move {
138                let days: u64 = args
139                    .value("--days")
140                    .unwrap_or("365")
141                    .parse()
142                    .map_err(|_| crate::Error::BadRequest("--days must be a number".into()))?;
143                let pruned = prune(&state.db, Duration::from_secs(days * 24 * 60 * 60)).await?;
144                println!("Deleted {pruned} audit entries older than {days} days.");
145                Ok(())
146            },
147        );
148    }
149}
150
151async fn log(state: AppState, entry: Entry) -> Result {
152    record(&state.db, entry).await
153}
154
155/// One thing that happened, to be recorded with [`record`].
156#[derive(Debug, Clone)]
157pub struct Entry {
158    action: String,
159    user_id: Option<i64>,
160    subject: Option<(String, i64)>,
161    data: Value,
162    ip: Option<String>,
163}
164
165impl Entry {
166    /// What happened, e.g. `order.refunded`.
167    pub fn new(action: &str) -> Self {
168        Self {
169            action: action.to_owned(),
170            user_id: None,
171            subject: None,
172            data: json!({}),
173            ip: None,
174        }
175    }
176
177    /// Who did it.
178    pub fn user(mut self, user_id: i64) -> Self {
179        self.user_id = Some(user_id);
180        self
181    }
182
183    /// The record it happened to, e.g. `("orders", 42)`.
184    pub fn subject(mut self, kind: &str, id: i64) -> Self {
185        self.subject = Some((kind.to_owned(), id));
186        self
187    }
188
189    /// Details, e.g. the old and new values.
190    pub fn data(mut self, data: Value) -> Self {
191        self.data = data;
192        self
193    }
194
195    /// Where the request came from (`ClientIp`).
196    pub fn ip(mut self, ip: Option<IpAddr>) -> Self {
197        self.ip = ip.map(|ip| ip.to_string());
198        self
199    }
200
201    fn ip_text(mut self, ip: Option<String>) -> Self {
202        self.ip = ip;
203        self
204    }
205}
206
207/// A recorded entry.
208#[derive(Debug, Clone, Serialize)]
209#[non_exhaustive]
210pub struct AuditLog {
211    /// The `audit_logs` row id.
212    pub id: i64,
213    /// Who did it; `None` when unknown (e.g. a failed login).
214    pub user_id: Option<i64>,
215    /// What happened, e.g. `auth.login` or `order.refunded`.
216    pub action: String,
217    /// The kind of record it happened to, e.g. `orders`.
218    pub subject_type: Option<String>,
219    /// That record's id.
220    pub subject_id: Option<i64>,
221    /// Details, e.g. the old and new values; `{}` when none were given.
222    pub data: Value,
223    /// Where the request came from, if recorded.
224    pub ip: Option<String>,
225    /// When it was recorded.
226    pub created_at: DateTime,
227}
228
229fn from_row(row: &Row) -> std::result::Result<AuditLog, crate::db::DbError> {
230    let data: String = row.try_get("data")?;
231    Ok(AuditLog {
232        id: row.try_get("id")?,
233        user_id: row.try_get("user_id")?,
234        action: row.try_get("action")?,
235        subject_type: row.try_get("subject_type")?,
236        subject_id: row.try_get("subject_id")?,
237        data: serde_json::from_str(&data).unwrap_or(Value::Null),
238        ip: row.try_get("ip")?,
239        created_at: row.try_get("created_at")?,
240    })
241}
242
243/// Records `entry` (needs the `Audit` module's table).
244pub async fn record(db: &Db, entry: Entry) -> Result {
245    let (subject_type, subject_id) = match entry.subject {
246        Some((kind, id)) => (Some(kind), Some(id)),
247        None => (None, None),
248    };
249    sql(
250        "INSERT INTO audit_logs (user_id, action, subject_type, subject_id, data, ip, created_at) \
251         VALUES (?, ?, ?, ?, ?, ?, ?)",
252    )
253    .bind(entry.user_id)
254    .bind(entry.action)
255    .bind(subject_type)
256    .bind(subject_id)
257    .bind(entry.data.to_string())
258    .bind(entry.ip)
259    .bind(now())
260    .execute(db)
261    .await?;
262    Ok(())
263}
264
265const COLUMNS: &str = "id, user_id, action, subject_type, subject_id, data, ip, created_at";
266
267async fn fetch(db: &Db, condition: &str, binds: Vec<DbValue>, limit: u32) -> Result<Vec<AuditLog>> {
268    let rows = sql(format!(
269        "SELECT {COLUMNS} FROM audit_logs {condition} ORDER BY id DESC LIMIT ?"
270    ))
271    .bind_all(binds)
272    .bind(i64::from(limit))
273    .fetch_all(db)
274    .await?;
275    Ok(rows
276        .iter()
277        .map(from_row)
278        .collect::<std::result::Result<_, _>>()?)
279}
280
281/// The newest `limit` entries.
282pub async fn latest(db: &Db, limit: u32) -> Result<Vec<AuditLog>> {
283    fetch(db, "", Vec::new(), limit).await
284}
285
286/// What `user_id` did, newest first.
287pub async fn for_user(db: &Db, user_id: i64, limit: u32) -> Result<Vec<AuditLog>> {
288    fetch(
289        db,
290        "WHERE user_id = ?",
291        vec![DbValue::Integer(user_id)],
292        limit,
293    )
294    .await
295}
296
297/// What happened to one record, newest first.
298pub async fn for_subject(db: &Db, kind: &str, id: i64, limit: u32) -> Result<Vec<AuditLog>> {
299    let binds = vec![DbValue::Text(kind.to_owned()), DbValue::Integer(id)];
300    fetch(
301        db,
302        "WHERE subject_type = ? AND subject_id = ?",
303        binds,
304        limit,
305    )
306    .await
307}
308
309/// Deletes entries older than `age`; returns how many.
310pub async fn prune(db: &Db, age: Duration) -> Result<u64> {
311    let before = now() - chrono::Duration::from_std(age).unwrap_or_default();
312    Ok(sql("DELETE FROM audit_logs WHERE created_at < ?")
313        .bind(before)
314        .execute(db)
315        .await?)
316}