1use 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
52pub 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 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#[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 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 pub fn user(mut self, user_id: i64) -> Self {
179 self.user_id = Some(user_id);
180 self
181 }
182
183 pub fn subject(mut self, kind: &str, id: i64) -> Self {
185 self.subject = Some((kind.to_owned(), id));
186 self
187 }
188
189 pub fn data(mut self, data: Value) -> Self {
191 self.data = data;
192 self
193 }
194
195 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#[derive(Debug, Clone, Serialize)]
209#[non_exhaustive]
210pub struct AuditLog {
211 pub id: i64,
213 pub user_id: Option<i64>,
215 pub action: String,
217 pub subject_type: Option<String>,
219 pub subject_id: Option<i64>,
221 pub data: Value,
223 pub ip: Option<String>,
225 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
243pub 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
281pub async fn latest(db: &Db, limit: u32) -> Result<Vec<AuditLog>> {
283 fetch(db, "", Vec::new(), limit).await
284}
285
286pub 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
297pub 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
309pub 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}