Skip to main content

brep_plm/
audit.rs

1//! The audit log: who changed what, and when, for every change to the store.
2//!
3//! # How every change is caught
4//!
5//! Nothing calls "log this" at each of the store's many write paths — one
6//! forgotten call would be a silent hole. Instead [`crate::db::Db::mutate`],
7//! which every change already goes through, compares the state before and
8//! after and turns the difference into events ([`diff`]). A write path added
9//! later is logged without anyone remembering to. The few events that are not
10//! a change to the store — a failed sign-in, a script file edited in the
11//! browser, a test run — are recorded explicitly ([`crate::db::Db::record`]).
12//!
13//! An event is written in the SAME SQLite transaction as its change
14//! ([`crate::sql::Sql::write`]): a change is never on disk without its events,
15//! and a change that is refused or rolled back leaves none.
16//!
17//! # Who
18//!
19//! The request guard knows who a request is; the store does not, and most of
20//! its methods are not told. So the guard runs each request inside a
21//! task-local [`Actor`] scope ([`scope`]), the blocking pool carries it across
22//! ([`crate::api::blocking`]), and `mutate` reads it ([`current_actor`]).
23//! Anything outside a request — start-up, a test driving the store directly —
24//! is the `system` actor unless it says otherwise ([`as_actor`]).
25//!
26//! # Where
27//!
28//! Behind [`AuditSink`], so the storage can change without the rest noticing.
29//! The store's sink is the `audit` table of `plm.sqlite` ([`crate::sql::Sql`]),
30//! with an index for each filter the API offers. Nothing is ever deleted from
31//! it.
32//!
33//! # Actions
34//!
35//! `create`, `update`, `delete` for anything; and more specific ones where a
36//! field says what happened:
37//! * revisions: `release`, `submit` (to in review), `supersede`, `obsolete`,
38//!   `return-to-draft`, `checkout`, `checkin`, `break-lock`, `document`,
39//!   `uses`, `bake`;
40//! * parts: `sourcing`;
41//! * users: `password`, `groups`, `enable`, `disable`;
42//! * tokens: `revoke` (a deleted token);
43//! * sign-ins: `sign-in`, `session-ended`, `sign-in-failed`;
44//! * scripts: `script-write`, `script-delete`, `script-run`.
45//! * preferences (kind `preference`, entity `<user id>/<key>`): `update`,
46//!   `delete` — written by [`crate::sql::Sql::set_preference`] in the write's
47//!   own transaction, since preferences do not go through `mutate`; the
48//!   `@recovery` mirror is not logged ([`crate::api::preferences`]).
49
50use std::collections::{BTreeMap, BTreeSet};
51use std::io;
52
53use serde::Deserialize;
54use serde_json::{Map, Value};
55
56use crate::model::{Actor, AuditEvent, EntityRef, FieldChange, Timestamp};
57
58// ===========================================================================
59// Who is acting
60// ===========================================================================
61
62tokio::task_local! {
63    static ACTOR: Actor;
64}
65
66/// Who the current request is, or the `system` actor outside one.
67pub fn current_actor() -> Actor {
68    ACTOR.try_with(Clone::clone).unwrap_or_else(|_| Actor::system())
69}
70
71/// Run `work` as `actor`, synchronously — the blocking pool, a test.
72pub fn as_actor<R>(actor: Actor, work: impl FnOnce() -> R) -> R {
73    ACTOR.sync_scope(actor, work)
74}
75
76/// Run a future as `actor` — the request guard.
77pub async fn scope<F: std::future::Future>(actor: Actor, future: F) -> F::Output {
78    ACTOR.scope(actor, future).await
79}
80
81// ===========================================================================
82// Where events go
83// ===========================================================================
84
85/// What an event store must do. Appends assign the ids; nothing edits or
86/// deletes an event.
87pub trait AuditSink: Send + Sync {
88    /// Append `events` in order, numbering each. Returns them numbered.
89    fn append(&self, events: Vec<AuditEvent>) -> io::Result<Vec<AuditEvent>>;
90    /// The events matching `filter`, newest first.
91    fn query(&self, filter: &AuditFilter) -> io::Result<Vec<AuditEvent>>;
92}
93
94/// Narrowing a query. Every field is optional; empty means no constraint.
95#[derive(Debug, Clone, Default, Deserialize)]
96pub struct AuditFilter {
97    /// The entity's kind (`part`, `revision`, `user`, …).
98    #[serde(default)]
99    pub kind: String,
100    /// The entity's id.
101    #[serde(default)]
102    pub entity: String,
103    /// A part's id: the part's own events AND its revisions'.
104    #[serde(default)]
105    pub part: String,
106    /// A user id or username (the username ignoring ASCII case).
107    #[serde(default)]
108    pub user: String,
109    #[serde(default)]
110    pub action: String,
111    /// Unix seconds, inclusive.
112    #[serde(default)]
113    pub since: Option<Timestamp>,
114    #[serde(default)]
115    pub until: Option<Timestamp>,
116    /// Only events older than this id — the next page.
117    #[serde(default)]
118    pub before: Option<u64>,
119    /// At most this many; the API caps it.
120    #[serde(default)]
121    pub limit: Option<usize>,
122    /// Only these kinds (the API narrows a non-administrator to parts and
123    /// revisions). Empty: any.
124    #[serde(skip)]
125    pub kinds: Vec<String>,
126}
127
128impl AuditFilter {
129    pub fn matches(&self, event: &AuditEvent) -> bool {
130        (self.kind.is_empty() || event.entity.kind == self.kind)
131            && (self.kinds.is_empty() || self.kinds.iter().any(|k| *k == event.entity.kind))
132            && (self.entity.is_empty() || event.entity.id == self.entity)
133            && (self.part.is_empty()
134                || event.entity.part_id == self.part
135                || (event.entity.kind == "part" && event.entity.id == self.part))
136            && (self.user.is_empty()
137                || event.actor.user_id == self.user
138                || event.actor.username.eq_ignore_ascii_case(&self.user))
139            && (self.action.is_empty() || event.action == self.action)
140            && self.since.is_none_or(|t| event.at >= t)
141            && self.until.is_none_or(|t| event.at <= t)
142            && self.before.is_none_or(|id| event.id < id)
143    }
144}
145
146// ===========================================================================
147// Turning a change into events
148// ===========================================================================
149
150/// Fields whose change alone is not worth an event: bookkeeping that moves
151/// with every real change, or on every request.
152const QUIET_FIELDS: [&str; 4] = ["modified_at", "last_seen", "last_used_at", "next"];
153
154/// Fields whose values are secrets: the event says they changed, never what to.
155const SECRET_FIELDS: [&str; 3] = ["password", "hash", "csrf"];
156
157/// Store keys that are the store's own bookkeeping, not anyone's record.
158const BOOKKEEPING: [&str; 3] = ["seq", "changes", "changes_from"];
159
160/// Collections of records keyed by `id`: the store key, the entity kind, and
161/// the field a person calls one by.
162const COLLECTIONS: [(&str, &str, &str); 7] = [
163    ("workspace", "workspace", "name"),
164    ("users", "user", "username"),
165    ("api_tokens", "token", "name"),
166    ("part_types", "part-type", "name"),
167    ("categories", "category", "name"),
168    ("manufacturers", "manufacturer", "name"),
169    ("suppliers", "supplier", "name"),
170];
171
172/// Every event that turns the store from `before` into `after`, by `actor`
173/// at `at`, stamped with the new `seq`. Ids are left 0 for the sink.
174pub fn diff(before: &Value, after: &Value, actor: &Actor, at: Timestamp, seq: u64) -> Vec<AuditEvent> {
175    let mut out = Vec::new();
176    let mut push = |action: &str, entity: EntityRef, changes: BTreeMap<String, FieldChange>| {
177        out.push(AuditEvent {
178            id: 0,
179            at,
180            actor: actor.clone(),
181            action: action.to_string(),
182            entity,
183            changes,
184            detail: String::new(),
185            seq,
186        });
187    };
188    let empty = Map::new();
189    let before_map = before.as_object().unwrap_or(&empty);
190    let after_map = after.as_object().unwrap_or(&empty);
191    let keys: BTreeSet<&String> = before_map.keys().chain(after_map.keys()).collect();
192
193    for key in keys {
194        let old = before_map.get(key).unwrap_or(&Value::Null);
195        let new = after_map.get(key).unwrap_or(&Value::Null);
196        if old == new || BOOKKEEPING.contains(&key.as_str()) {
197            continue;
198        }
199        match key.as_str() {
200            "parts" => diff_parts(old, new, &mut push),
201            "sessions" => diff_sessions(old, new, before_map, after_map, &mut push),
202            "settings" => {
203                let changes = field_changes(old, new, &[]);
204                if !changes.is_empty() {
205                    push("update", entity("settings", "settings", "Settings", ""), changes);
206                }
207            }
208            name => {
209                if let Some((_, kind, label)) = COLLECTIONS.iter().find(|(store, _, _)| *store == name) {
210                    diff_collection(old, new, kind, label, &mut push);
211                } else if keyed(old) && keyed(new) {
212                    // A collection a later slice adds: logged by its store
213                    // name, rather than silently not at all.
214                    diff_collection(old, new, name, "name", &mut push);
215                } else {
216                    let mut changes = BTreeMap::new();
217                    changes.insert(name.to_string(), FieldChange { before: old.clone(), after: new.clone() });
218                    push("update", entity(name, name, name, ""), changes);
219                }
220            }
221        }
222    }
223    out
224}
225
226fn entity(kind: &str, id: &str, label: &str, part_id: &str) -> EntityRef {
227    EntityRef { kind: kind.into(), id: id.into(), label: label.into(), part_id: part_id.into() }
228}
229
230/// Whether `value` is a list of records with ids (or empty).
231fn keyed(value: &Value) -> bool {
232    match value {
233        Value::Array(items) => items.iter().all(|item| item.get("id").and_then(Value::as_str).is_some()),
234        Value::Null => true,
235        _ => false,
236    }
237}
238
239fn by_id(value: &Value) -> BTreeMap<String, &Value> {
240    value
241        .as_array()
242        .map(|items| {
243            items
244                .iter()
245                .filter_map(|item| Some((item.get("id")?.as_str()?.to_string(), item)))
246                .collect()
247        })
248        .unwrap_or_default()
249}
250
251fn text<'a>(value: &'a Value, field: &str) -> &'a str {
252    value.get(field).and_then(Value::as_str).unwrap_or("")
253}
254
255/// The fields that differ between two records, minus `skip` and the quiet
256/// ones, with secrets redacted. A missing record is `null`: every field of
257/// the other side appears.
258fn field_changes(before: &Value, after: &Value, skip: &[&str]) -> BTreeMap<String, FieldChange> {
259    let empty = Map::new();
260    let old = before.as_object().unwrap_or(&empty);
261    let new = after.as_object().unwrap_or(&empty);
262    let mut changes = BTreeMap::new();
263    for key in old.keys().chain(new.keys()).collect::<BTreeSet<_>>() {
264        if skip.contains(&key.as_str()) || QUIET_FIELDS.contains(&key.as_str()) {
265            continue;
266        }
267        let a = old.get(key).cloned().unwrap_or(Value::Null);
268        let b = new.get(key).cloned().unwrap_or(Value::Null);
269        if a == b {
270            continue;
271        }
272        let change = if SECRET_FIELDS.contains(&key.as_str()) {
273            let mark = |v: &Value| if v.is_null() { Value::Null } else { Value::from("(secret)") };
274            FieldChange { before: mark(&a), after: mark(&b) }
275        } else {
276            FieldChange { before: a, after: b }
277        };
278        changes.insert(key.clone(), change);
279    }
280    changes
281}
282
283fn diff_collection(
284    old: &Value,
285    new: &Value,
286    kind: &str,
287    label_field: &str,
288    push: &mut impl FnMut(&str, EntityRef, BTreeMap<String, FieldChange>),
289) {
290    let before = by_id(old);
291    let after = by_id(new);
292    for id in before.keys().chain(after.keys()).collect::<BTreeSet<_>>() {
293        let (a, b) = (before.get(id).copied(), after.get(id).copied());
294        let record = b.or(a).unwrap_or(&Value::Null);
295        let who = entity(kind, id, text(record, label_field), "");
296        let changes = field_changes(a.unwrap_or(&Value::Null), b.unwrap_or(&Value::Null), &[]);
297        match (a, b) {
298            (None, Some(_)) => push("create", who, changes),
299            (Some(_), None) => push(if kind == "token" { "revoke" } else { "delete" }, who, changes),
300            _ if changes.is_empty() => {}
301            _ => {
302                let action = match kind {
303                    "user" => user_action(&changes),
304                    "workspace" => workspace_action(&changes),
305                    _ => "update",
306                };
307                push(action, who, changes);
308            }
309        }
310    }
311}
312
313/// A workspace entry's change, named by what moved: a new file version
314/// (a replace or a restore), a move to another folder, a rename, or a link
315/// pinned or set to follow, or a new owner.
316fn workspace_action(changes: &BTreeMap<String, FieldChange>) -> &'static str {
317    let moved: Vec<&str> = changes.keys().map(String::as_str).filter(|k| !QUIET_FIELDS.contains(k)).collect();
318    match moved.as_slice() {
319        ["versions"] => "version",
320        ["parent"] | ["name", "parent"] | ["owner", "parent"] | ["name", "owner", "parent"] => "move",
321        ["name"] => "rename",
322        ["link"] => "pin",
323        ["owner"] => "owner",
324        _ => "update",
325    }
326}
327
328fn user_action(changes: &BTreeMap<String, FieldChange>) -> &'static str {
329    let only = |field: &str| changes.len() == 1 && changes.contains_key(field);
330    if only("password") {
331        "password"
332    } else if only("groups") {
333        "groups"
334    } else if only("active") {
335        if changes["active"].after == Value::Bool(true) { "enable" } else { "disable" }
336    } else {
337        "update"
338    }
339}
340
341fn diff_parts(old: &Value, new: &Value, push: &mut impl FnMut(&str, EntityRef, BTreeMap<String, FieldChange>)) {
342    let before = by_id(old);
343    let after = by_id(new);
344    for id in before.keys().chain(after.keys()).collect::<BTreeSet<_>>() {
345        let (a, b) = (before.get(id).copied(), after.get(id).copied());
346        let part = b.or(a).unwrap_or(&Value::Null);
347        let number = text(part, "number").to_string();
348        let changes = field_changes(a.unwrap_or(&Value::Null), b.unwrap_or(&Value::Null), &["revisions"]);
349        let who = entity("part", id, &number, "");
350        match (a, b) {
351            (None, Some(_)) => push("create", who, changes),
352            (Some(_), None) => push("delete", who, changes),
353            _ if changes.is_empty() => {}
354            _ => {
355                let action = if changes.len() == 1 && changes.contains_key("sourcing") { "sourcing" } else { "update" };
356                push(action, who, changes);
357            }
358        }
359        let revs_before = by_id(a.and_then(|p| p.get("revisions")).unwrap_or(&Value::Null));
360        let revs_after = by_id(b.and_then(|p| p.get("revisions")).unwrap_or(&Value::Null));
361        for rev in revs_before.keys().chain(revs_after.keys()).collect::<BTreeSet<_>>() {
362            let (x, y) = (revs_before.get(rev).copied(), revs_after.get(rev).copied());
363            let record = y.or(x).unwrap_or(&Value::Null);
364            let label = format!("{number} rev {}", text(record, "label"));
365            let who = entity("revision", rev, &label, id);
366            let changes = field_changes(x.unwrap_or(&Value::Null), y.unwrap_or(&Value::Null), &[]);
367            match (x, y) {
368                (None, Some(_)) => push("create", who, changes),
369                (Some(_), None) => push("delete", who, changes),
370                _ if changes.is_empty() => {}
371                _ => {
372                    let action = revision_action(&changes);
373                    push(action, who, changes);
374                }
375            }
376        }
377    }
378}
379
380/// The one word that best says what happened to a revision. Several fields
381/// can change at once (a release also stamps who and when); the most
382/// significant one names the event, and every field is still in `changes`.
383fn revision_action(changes: &BTreeMap<String, FieldChange>) -> &'static str {
384    // A reviewer's decision names the event even when it also moved the
385    // lifecycle (a rejection sends the revision back to Draft).
386    if let Some(change) = changes.get("reviews") {
387        if let Some(verdict) = new_decision(&change.before, &change.after) {
388            return verdict;
389        }
390        if let Some(status) = last_review_status(&change.after) {
391            if status == "withdrawn" && last_review_status(&change.before) != Some("withdrawn") {
392                return "withdraw";
393            }
394        }
395    }
396    if let Some(change) = changes.get("lifecycle") {
397        return match change.after.as_str().unwrap_or("") {
398            "released" => "release",
399            "inreview" => "submit",
400            "superseded" => "supersede",
401            "obsolete" => "obsolete",
402            "draft" => "return-to-draft",
403            _ => "update",
404        };
405    }
406    if let Some(change) = changes.get("lock") {
407        return match (change.before.is_null(), change.after.is_null()) {
408            (true, false) => "checkout",
409            (false, true) => {
410                // The holder checking in, or someone else breaking the lock:
411                // the diff cannot tell who acted, so the caller's name is in
412                // the actor and the holder's in `before`.
413                "checkin"
414            }
415            _ => "checkout",
416        };
417    }
418    if changes.contains_key("content_hash") {
419        return "document";
420    }
421    if changes.contains_key("uses") {
422        return "uses";
423    }
424    if changes.contains_key("bake") {
425        return "bake";
426    }
427    if changes.contains_key("reviews") {
428        return "review-update";
429    }
430    if changes.contains_key("comments") {
431        return "comment";
432    }
433    "update"
434}
435
436/// The verdict of a decision `after` has that `before` did not, in the last
437/// review round of a `reviews` list.
438pub(crate) fn new_decision(before: &Value, after: &Value) -> Option<&'static str> {
439    let decisions = |v: &Value| -> usize {
440        v.as_array()
441            .and_then(|rounds| rounds.last())
442            .and_then(|r| r.get("decisions"))
443            .and_then(Value::as_array)
444            .map(Vec::len)
445            .unwrap_or(0)
446    };
447    let same_round = |v: &Value| v.as_array().and_then(|r| r.last()).and_then(|r| r.get("id")).cloned();
448    let grew = decisions(after) > decisions(before) || (same_round(before) != same_round(after) && decisions(after) > 0);
449    if !grew {
450        return None;
451    }
452    let verdict = after
453        .as_array()?
454        .last()?
455        .get("decisions")?
456        .as_array()?
457        .last()?
458        .get("verdict")?
459        .as_str()?;
460    Some(if verdict == "reject" { "reject" } else { "approve" })
461}
462
463/// The status of the last round in a `reviews` list.
464pub(crate) fn last_review_status(value: &Value) -> Option<&str> {
465    value.as_array()?.last()?.get("status")?.as_str()
466}
467
468fn diff_sessions(
469    old: &Value,
470    new: &Value,
471    before: &Map<String, Value>,
472    after: &Map<String, Value>,
473    push: &mut impl FnMut(&str, EntityRef, BTreeMap<String, FieldChange>),
474) {
475    // Keyed by token, which never leaves this function: the event names the
476    // user, not the session.
477    let tokens = |value: &Value| -> BTreeMap<String, String> {
478        value
479            .as_array()
480            .map(|items| {
481                items
482                    .iter()
483                    .filter_map(|s| Some((s.get("token")?.as_str()?.to_string(), s.get("user_id")?.as_str()?.to_string())))
484                    .collect()
485            })
486            .unwrap_or_default()
487    };
488    let username = |user_id: &str| -> String {
489        for map in [after, before] {
490            if let Some(users) = map.get("users").and_then(Value::as_array) {
491                if let Some(user) = users.iter().find(|u| text(u, "id") == user_id) {
492                    return text(user, "username").to_string();
493                }
494            }
495        }
496        String::new()
497    };
498    let (a, b) = (tokens(old), tokens(new));
499    for (token, user_id) in &b {
500        if !a.contains_key(token) {
501            push("sign-in", entity("user", user_id, &username(user_id), ""), BTreeMap::new());
502        }
503    }
504    // Several sessions of one user ending at once (sign out everywhere) are
505    // one event, with the count.
506    let mut ended: BTreeMap<&str, u64> = BTreeMap::new();
507    for (token, user_id) in &a {
508        if !b.contains_key(token) {
509            *ended.entry(user_id).or_default() += 1;
510        }
511    }
512    for (user_id, count) in ended {
513        let mut changes = BTreeMap::new();
514        changes.insert("sessions".to_string(), FieldChange { before: Value::from(count), after: Value::from(0) });
515        push("session-ended", entity("user", user_id, &username(user_id), ""), changes);
516    }
517}
518
519/// The lock change of a `checkin` event names whose lock it was; when that
520/// is not the actor, the event is really a broken lock.
521pub fn refine(mut events: Vec<AuditEvent>) -> Vec<AuditEvent> {
522    for event in &mut events {
523        if event.action == "checkin" {
524            let holder = event
525                .changes
526                .get("lock")
527                .and_then(|c| c.before.get("user_id"))
528                .and_then(Value::as_str)
529                .unwrap_or("");
530            if !holder.is_empty() && holder != event.actor.user_id {
531                event.action = "break-lock".into();
532            }
533        }
534    }
535    events
536}
537
538/// CSV of events, for the admin's export.
539pub fn to_csv(events: &[AuditEvent]) -> String {
540    let mut out = String::from("id,at,user,via,ip,action,kind,entity,label,part,changes,detail,seq\n");
541    for e in events {
542        let changes = if e.changes.is_empty() {
543            String::new()
544        } else {
545            serde_json::to_string(&e.changes).unwrap_or_default()
546        };
547        let row = [
548            e.id.to_string(),
549            e.at.to_string(),
550            e.actor.username.clone(),
551            e.actor.via.clone(),
552            e.actor.ip.clone(),
553            e.action.clone(),
554            e.entity.kind.clone(),
555            e.entity.id.clone(),
556            e.entity.label.clone(),
557            e.entity.part_id.clone(),
558            changes,
559            e.detail.clone(),
560            e.seq.to_string(),
561        ];
562        out.push_str(&row.iter().map(|f| crate::bom::csv_cell(f)).collect::<Vec<_>>().join(","));
563        out.push('\n');
564    }
565    out
566}
567