Skip to main content

vcon_server/
audit.rs

1//! The audit log: one record per request, written in the same transaction
2//! as the change it describes. A record holds no vCon content, no token
3//! and no client address.
4
5use std::io::{self, Write};
6
7use rusqlite::{Connection, params};
8use serde_json::json;
9
10use crate::catalog::Cached;
11use time::OffsetDateTime;
12use time::format_description::well_known::Rfc3339;
13
14use crate::ids::{KeyId, UserId, VersionId};
15use crate::query::{self, BadQuery};
16use crate::reveal::Part;
17
18/// The audit table, part of every catalog that holds a log.
19pub const SCHEMA: &str = "
20CREATE TABLE audit (
21    seq INTEGER PRIMARY KEY AUTOINCREMENT,
22    at TEXT NOT NULL,
23    actor TEXT NOT NULL,
24    action TEXT NOT NULL,
25    target TEXT,
26    version TEXT,
27    status INTEGER,
28    count INTEGER NOT NULL
29);
30CREATE INDEX audit_counted ON audit (actor, action, status, at);
31";
32
33/// Who made a request.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum Actor {
36    /// A caller's key.
37    Key(KeyId),
38    /// The purge sweep.
39    Sweep,
40    /// A command run on the host.
41    Cli,
42    /// A user who signed in, by a session.
43    User(UserId),
44    /// A caller with no known key: its token did not parse, or names a key
45    /// id the key table does not hold; or a caller with no known session.
46    Unparsed,
47}
48
49/// What a request asked for. A refused request records what it asked for.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum Action {
52    Create,
53    Replace,
54    Read,
55    /// A read of the vCon's masked view (`?view=masked`): its summary,
56    /// with no content.
57    ReadMasked,
58    /// A read marked as a reveal of one part of the vCon.
59    Reveal(Part),
60    Delete,
61    Purge,
62    LegalRead,
63    /// A legal read of the version's masked view (`?view=masked`): its
64    /// summary, with no content.
65    LegalReadMasked,
66    /// A legal read marked as a reveal of one part of the version read.
67    LegalReveal(Part),
68    LegalVersions,
69    Restore,
70    Hold,
71    Release,
72    KeyCreate,
73    KeyRevoke,
74    KeyList,
75    KeyInfo,
76    Retention,
77    Health,
78    AuthFailed,
79    TenantCreate,
80    TenantList,
81    TenantRetention,
82    TenantRemove,
83    RekeyMaster,
84    RekeyTenant,
85    List,
86    AuditRead,
87    Openapi,
88    Backup,
89    /// An export of the tenant's versions, as Parquet files.
90    Export,
91    /// A tenant's metadata level set, in the admin log.
92    TenantMetadata,
93    /// The tenant's metadata level set, in its own log.
94    Metadata,
95    /// A request to the MCP server, counted (`count`), not recorded.
96    Mcp,
97    /// A valid key refused because the listener it came to serves the
98    /// other kind of key; counted (`count`), not recorded.
99    WrongListener,
100    /// A listener that found every one of its places held
101    /// (`limits.connections`); counted (`count`), not recorded.
102    ListenerFull,
103    /// A report of a content-security-policy violation that a browser
104    /// sent to the console (`POST /console/csp-report`), under the status
105    /// that answered it; counted (`count`), not recorded.
106    CspReport,
107    /// A user made, in the admin log.
108    UserAdd,
109    /// The users listed, in the admin log.
110    UserList,
111    /// A user deactivated and its memberships removed.
112    UserDeactivate,
113    /// Roles given to a user in a tenant, or as an operator.
114    MembershipGrant,
115    /// Roles taken from a user in a tenant, or as an operator.
116    MembershipRevoke,
117    /// A tenant's role cap set or removed.
118    RoleCapSet,
119    /// A tenant's role cap read, in the admin log.
120    RoleCapRead,
121    /// A tenant's settings read by its administrator.
122    SettingsRead,
123    /// A tenant's settings changed by its administrator.
124    SettingsSet,
125    /// A tenant's memberships listed by its administrator.
126    MembershipList,
127    /// A session started for a user who signed in.
128    SessionStart,
129    /// A session read by its own browser (`GET /session`), counted.
130    SessionRead,
131    /// A session ended by its user.
132    SessionEnd,
133}
134
135impl Action {
136    /// The name written in the log.
137    pub fn as_str(self) -> &'static str {
138        match self {
139            Action::Create => "create",
140            Action::Replace => "replace",
141            Action::Read => "read",
142            Action::ReadMasked => "read_masked",
143            Action::Reveal(Part::Parties) => "reveal_parties",
144            Action::Reveal(Part::Subject) => "reveal_subject",
145            Action::Reveal(Part::Dialog) => "reveal_dialog",
146            Action::Reveal(Part::Analysis) => "reveal_analysis",
147            Action::Reveal(Part::Links) => "reveal_links",
148            Action::Reveal(Part::All) => "reveal_all",
149            Action::Reveal(Part::Audio) => "reveal_audio",
150            Action::Delete => "delete",
151            Action::Purge => "purge",
152            Action::LegalRead => "legal_read",
153            Action::LegalReadMasked => "legal_read_masked",
154            Action::LegalReveal(Part::Parties) => "legal_reveal_parties",
155            Action::LegalReveal(Part::Subject) => "legal_reveal_subject",
156            Action::LegalReveal(Part::Dialog) => "legal_reveal_dialog",
157            Action::LegalReveal(Part::Analysis) => "legal_reveal_analysis",
158            Action::LegalReveal(Part::Links) => "legal_reveal_links",
159            Action::LegalReveal(Part::All) => "legal_reveal_all",
160            Action::LegalReveal(Part::Audio) => "legal_reveal_audio",
161            Action::LegalVersions => "legal_versions",
162            Action::Restore => "restore",
163            Action::Hold => "hold",
164            Action::Release => "release",
165            Action::KeyCreate => "key_create",
166            Action::KeyRevoke => "key_revoke",
167            Action::KeyList => "key_list",
168            Action::KeyInfo => "key_info",
169            Action::Retention => "retention",
170            Action::Health => "health",
171            Action::AuthFailed => "auth_failed",
172            Action::TenantCreate => "tenant_create",
173            Action::TenantList => "tenant_list",
174            Action::TenantRetention => "tenant_retention",
175            Action::TenantRemove => "tenant_remove",
176            Action::RekeyMaster => "rekey_master",
177            Action::RekeyTenant => "rekey_tenant",
178            Action::List => "list",
179            Action::AuditRead => "audit_read",
180            Action::Openapi => "openapi",
181            Action::Backup => "backup",
182            Action::Export => "export",
183            Action::TenantMetadata => "tenant_metadata",
184            Action::Metadata => "metadata",
185            Action::Mcp => "mcp",
186            Action::WrongListener => "wrong_listener",
187            Action::ListenerFull => "listener_full",
188            Action::CspReport => "csp_report",
189            Action::UserAdd => "user_add",
190            Action::UserList => "user_list",
191            Action::UserDeactivate => "user_deactivate",
192            Action::MembershipGrant => "membership_grant",
193            Action::MembershipRevoke => "membership_revoke",
194            Action::RoleCapSet => "role_cap_set",
195            Action::RoleCapRead => "role_cap_read",
196            Action::SettingsRead => "settings_read",
197            Action::SettingsSet => "settings_set",
198            Action::MembershipList => "membership_list",
199            Action::SessionStart => "session_start",
200            Action::SessionRead => "session_read",
201            Action::SessionEnd => "session_end",
202        }
203    }
204}
205
206/// One request, as recorded.
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct Entry {
209    pub actor: Actor,
210    pub action: Action,
211    /// The vCon's uuid, or the tenant or key id for an admin action.
212    pub target: Option<String>,
213    /// The version written, read or purged, if there is one.
214    pub version: Option<VersionId>,
215    /// The HTTP status answered, or the command's result; [`NO_ANSWER`]
216    /// for a record of something that answers no request.
217    pub status: u16,
218}
219
220/// The `status` of a record that answers no request, such as a listener
221/// that filled. No HTTP status is 0. The number is an entry's only: the
222/// log's column holds NULL for it (`stored`), and a record read back
223/// (`export`, `page`) has `null` there. Catalogs before schema version 5
224/// held the number, and the upgrade to 5 replaces it.
225pub const NO_ANSWER: u16 = 0;
226
227/// What the log's column holds for an entry's `status`: the status, or
228/// NULL for [`NO_ANSWER`]. The one place the number becomes no status.
229pub(crate) fn stored(status: u16) -> Option<u16> {
230    Some(status).filter(|status| *status != NO_ANSWER)
231}
232
233/// Why a record could not be written or exported.
234#[derive(Debug)]
235pub enum AuditError {
236    Sqlite(rusqlite::Error),
237    /// A log kept in a database server could not be written or read; the
238    /// text says why.
239    Database(String),
240    Write(io::Error),
241}
242
243impl From<rusqlite::Error> for AuditError {
244    fn from(e: rusqlite::Error) -> AuditError {
245        AuditError::Sqlite(e)
246    }
247}
248
249impl Actor {
250    /// The name written in the log: the key id, `sweep`, `cli`,
251    /// `user:<id>`, or empty.
252    pub(crate) fn name(self) -> String {
253        match self {
254            Actor::User(id) => format!("user:{id}"),
255            Actor::Key(id) => id.to_string(),
256            Actor::Sweep => "sweep".to_owned(),
257            Actor::Cli => "cli".to_owned(),
258            Actor::Unparsed => String::new(),
259        }
260    }
261}
262
263/// `now` in RFC 3339, in UTC.
264pub(crate) fn rfc3339(now: OffsetDateTime) -> String {
265    now.to_offset(time::UtcOffset::UTC)
266        .format(&Rfc3339)
267        .expect("every UTC time from the clock formats")
268}
269
270/// The start of the minute `now` is in, in UTC: the time of the record
271/// [`count`] adds to.
272pub(crate) fn minute_of(now: OffsetDateTime) -> OffsetDateTime {
273    now.to_offset(time::UtcOffset::UTC)
274        .replace_second(0)
275        .and_then(|t| t.replace_nanosecond(0))
276        .expect("0 is a valid second and nanosecond")
277}
278
279/// Appends one record, at `now`, in `tx`.
280pub fn record(tx: &Connection, entry: &Entry, now: OffsetDateTime) -> Result<(), AuditError> {
281    tx.cached_run(
282        "INSERT INTO audit (at, actor, action, target, version, status, count)
283         VALUES (?1, ?2, ?3, ?4, ?5, ?6, 1)",
284        params![
285            rfc3339(now),
286            entry.actor.name(),
287            entry.action.as_str(),
288            entry.target,
289            entry.version.map(|v| v.to_string()),
290            stored(entry.status),
291        ],
292    )?;
293    Ok(())
294}
295
296/// Adds one to the record for this actor, action and status in the minute
297/// of `now`, making it if needed. For requests that could otherwise grow a
298/// log one row each: failed authentications and health checks.
299pub fn count(tx: &Connection, entry: &Entry, now: OffsetDateTime) -> Result<(), AuditError> {
300    count_many(tx, entry, now, 1)
301}
302
303/// Adds `times` to the record for this actor, action and status in the
304/// minute of `now`, making it if needed: [`count`] for what was added up
305/// before it is written, so that many requests cost one write.
306pub fn count_many(
307    tx: &Connection,
308    entry: &Entry,
309    now: OffsetDateTime,
310    times: u64,
311) -> Result<(), AuditError> {
312    // A count of nothing makes no record.
313    if times == 0 {
314        return Ok(());
315    }
316    let times = i64::try_from(times).unwrap_or(i64::MAX);
317    let minute = minute_of(now);
318    let fields = params![
319        rfc3339(minute),
320        entry.actor.name(),
321        entry.action.as_str(),
322        entry.target,
323        entry.version.map(|v| v.to_string()),
324        stored(entry.status),
325        times,
326    ];
327    let added = tx.cached_run(
328        "UPDATE audit SET count = count + ?7
329         WHERE at = ?1 AND actor = ?2 AND action = ?3 AND target IS ?4 AND version IS ?5
330           AND status IS ?6",
331        fields,
332    )?;
333    if added == 0 {
334        tx.cached_run(
335            "INSERT INTO audit (at, actor, action, target, version, status, count)
336             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
337            fields,
338        )?;
339    }
340    Ok(())
341}
342
343/// Writes every record after `since` as JSON lines, oldest first.
344pub fn export(log: &Connection, since: Option<i64>, out: &mut dyn Write) -> Result<(), AuditError> {
345    // SQLite reads a negative limit as none.
346    lines(log, since.unwrap_or(0), -1, out)
347}
348
349/// Writes at most `limit` records after `after` as JSON lines, oldest
350/// first: the one rendering both `export` and `page` write.
351fn lines(log: &Connection, after: i64, limit: i64, out: &mut dyn Write) -> Result<(), AuditError> {
352    let mut rows = log.prepare_cached(
353        "SELECT seq, at, actor, action, target, version, status, count
354         FROM audit WHERE seq > ?1 ORDER BY seq LIMIT ?2",
355    )?;
356    let mut rows = rows.query(params![after, limit])?;
357    while let Some(row) = rows.next()? {
358        // A record that answers no request has no status to show.
359        let status = row.get::<_, Option<u16>>(6)?;
360        let record = json!({
361            "seq": row.get::<_, i64>(0)?,
362            "at": row.get::<_, String>(1)?,
363            "actor": row.get::<_, String>(2)?,
364            "action": row.get::<_, String>(3)?,
365            "target": row.get::<_, Option<String>>(4)?,
366            "version": row.get::<_, Option<String>>(5)?,
367            "status": status,
368            "count": row.get::<_, i64>(7)?,
369        });
370        writeln!(out, "{record}").map_err(AuditError::Write)?;
371    }
372    Ok(())
373}
374
375/// What an audit read asks for: at most `limit` records after the seq
376/// `after`, oldest first.
377#[derive(Debug, Clone, Copy, PartialEq, Eq)]
378pub struct AuditQuery {
379    pub after: i64,
380    pub limit: u32,
381}
382
383impl AuditQuery {
384    pub const DEFAULT_LIMIT: u32 = 1000;
385    pub const MAX_LIMIT: u32 = 10000;
386
387    /// An audit query from its parameters' values, the one rule for them
388    /// wherever they come from: `after` a seq (0, the default, is the
389    /// start of the log), `limit` 1 to `MAX_LIMIT`.
390    pub fn new(after: Option<u64>, limit: Option<u64>) -> Result<AuditQuery, BadQuery> {
391        let after = after
392            .map(|n| i64::try_from(n).map_err(|_| BadQuery))
393            .transpose()?
394            .unwrap_or(0);
395        let limit = match limit {
396            None => AuditQuery::DEFAULT_LIMIT,
397            Some(n) => u32::try_from(n)
398                .ok()
399                .filter(|n| (1..=AuditQuery::MAX_LIMIT).contains(n))
400                .ok_or(BadQuery)?,
401        };
402        Ok(AuditQuery { after, limit })
403    }
404
405    /// An audit query from an HTTP query string, which may name `after` and
406    /// `limit`, each at most once.
407    pub fn from_query(text: Option<&str>) -> Result<AuditQuery, BadQuery> {
408        let read = query::pairs(text, &["after", "limit"])?;
409        let number = |name| {
410            read.get(name)
411                .map(|n: &String| n.parse::<u64>().map_err(|_| BadQuery))
412                .transpose()
413        };
414        AuditQuery::new(number("after")?, number("limit")?)
415    }
416}
417
418/// Writes at most `query.limit` records after `query.after` as JSON lines,
419/// oldest first: the first lines `export` writes from the same place.
420pub fn page(log: &Connection, query: &AuditQuery, out: &mut dyn Write) -> Result<(), AuditError> {
421    lines(log, query.after, i64::from(query.limit), out)
422}
423
424/// Reading a log back, for tests.
425#[cfg(test)]
426pub(crate) mod testing {
427    use rusqlite::Connection;
428    use serde_json::Value;
429
430    /// The records `export` writes after `since`, parsed.
431    pub(crate) fn exported(log: &Connection, since: Option<i64>) -> Vec<Value> {
432        let mut out = Vec::new();
433        super::export(log, since, &mut out).expect("export");
434        String::from_utf8(out)
435            .expect("UTF-8")
436            .lines()
437            .map(|line| serde_json::from_str(line).expect("one JSON object per line"))
438            .collect()
439    }
440}
441
442#[cfg(test)]
443mod tests {
444    use serde_json::{Value, json};
445    use time::macros::datetime;
446
447    use super::testing::exported;
448    use super::*;
449    use crate::catalog;
450    use crate::envelope::Key;
451
452    struct Log {
453        _dir: tempfile::TempDir,
454        conn: Connection,
455    }
456
457    fn log() -> Log {
458        let dir = tempfile::tempdir().expect("temp dir");
459        let key = Key::generate().expect("key");
460        let conn = catalog::open(&dir.path().join("catalog.sqlite"), &key, SCHEMA).expect("opens");
461        Log { _dir: dir, conn }
462    }
463
464    fn read_by(key: KeyId, status: u16) -> Entry {
465        Entry {
466            actor: Actor::Key(key),
467            action: Action::Read,
468            target: Some("01a07da8-c2bb-83e5-b9a2-279e0d16bc46".into()),
469            version: Some(VersionId([0x22; 16])),
470            status,
471        }
472    }
473
474    #[test]
475    fn records_are_written_and_exported_back() {
476        let mut log = log();
477        let key = Key::generate().expect("key").id();
478        let tx = log.conn.transaction().expect("tx");
479        record(
480            &tx,
481            &read_by(key, 200),
482            datetime!(2026-10-23 12:34:56.789 UTC),
483        )
484        .expect("record");
485        let purge = Entry {
486            actor: Actor::Sweep,
487            action: Action::Purge,
488            target: Some("01a07da8-c2bb-83e5-b9a2-279e0d16bc46".into()),
489            version: None,
490            status: 200,
491        };
492        record(&tx, &purge, datetime!(2026-10-23 12:35:00 UTC)).expect("record");
493        tx.commit().expect("commit");
494        assert_eq!(
495            exported(&log.conn, None),
496            [
497                json!({"seq": 1, "at": "2026-10-23T12:34:56.789Z", "actor": key.to_string(),
498                       "action": "read", "target": "01a07da8-c2bb-83e5-b9a2-279e0d16bc46",
499                       "version": "22".repeat(16), "status": 200, "count": 1}),
500                json!({"seq": 2, "at": "2026-10-23T12:35:00Z", "actor": "sweep",
501                       "action": "purge", "target": "01a07da8-c2bb-83e5-b9a2-279e0d16bc46",
502                       "version": null, "status": 200, "count": 1}),
503            ]
504        );
505        assert_eq!(
506            exported(&log.conn, Some(1)).len(),
507            1,
508            "only records after seq 1"
509        );
510        assert_eq!(exported(&log.conn, Some(2)).len(), 0);
511    }
512
513    #[test]
514    fn times_are_written_in_utc() {
515        let mut log = log();
516        let key = Key::generate().expect("key").id();
517        let tx = log.conn.transaction().expect("tx");
518        record(
519            &tx,
520            &read_by(key, 200),
521            datetime!(2026-10-23 14:34:56 +02:00),
522        )
523        .expect("record");
524        tx.commit().expect("commit");
525        assert_eq!(exported(&log.conn, None)[0]["at"], "2026-10-23T12:34:56Z");
526    }
527
528    /// A listener that filled: a record that answers no request.
529    fn filled(target: &str) -> Entry {
530        Entry {
531            actor: Actor::Unparsed,
532            action: Action::ListenerFull,
533            target: Some(target.to_owned()),
534            version: None,
535            status: NO_ANSWER,
536        }
537    }
538
539    #[test]
540    fn a_record_that_answers_no_request_is_read_back_with_no_status() {
541        let mut log = log();
542        let tx = log.conn.transaction().expect("tx");
543        count(&tx, &filled("listen"), datetime!(2026-10-23 12:34:56 UTC)).expect("count");
544        tx.commit().expect("commit");
545        assert_eq!(
546            exported(&log.conn, None),
547            [json!({"seq": 1, "at": "2026-10-23T12:34:00Z", "actor": "",
548                       "action": "listener_full", "target": "listen",
549                       "version": null, "status": null, "count": 1}),],
550            "null, not a status no caller was sent"
551        );
552    }
553
554    #[test]
555    fn a_record_with_no_status_is_written_as_a_json_null_in_export_and_in_a_page() {
556        let mut log = log();
557        let tx = log.conn.transaction().expect("tx");
558        count(&tx, &filled("listen"), datetime!(2026-10-23 12:34:56 UTC)).expect("count");
559        tx.commit().expect("commit");
560        for text in [exported_text(&log.conn, None), paged(&log.conn, 0, 10)] {
561            assert!(
562                text.contains(r#""status":null"#),
563                "the member is there: {text}"
564            );
565            assert!(!text.contains(r#""status":0"#), "and is no number: {text}");
566        }
567    }
568
569    #[test]
570    fn records_with_no_status_are_counted_by_the_minute_like_any_other() {
571        let mut log = log();
572        let tx = log.conn.transaction().expect("tx");
573        for second in [0, 20, 40] {
574            let now = datetime!(2026-10-23 12:34:00 UTC) + time::Duration::seconds(second);
575            count(&tx, &filled("listen"), now).expect("count");
576        }
577        count(
578            &tx,
579            &filled("operator.listen"),
580            datetime!(2026-10-23 12:34:30 UTC),
581        )
582        .expect("count");
583        tx.commit().expect("commit");
584        let rows: Vec<_> = exported(&log.conn, None)
585            .iter()
586            .map(|r| (r["target"].clone(), r["status"].clone(), r["count"].clone()))
587            .collect();
588        assert_eq!(
589            rows,
590            [
591                ("listen".into(), Value::Null, 3.into()),
592                ("operator.listen".into(), Value::Null, 1.into()),
593            ],
594            "one row for each target, each with no status"
595        );
596    }
597
598    #[test]
599    fn a_record_with_a_status_keeps_it_beside_one_with_none() {
600        let mut log = log();
601        let tx = log.conn.transaction().expect("tx");
602        let health = Entry {
603            action: Action::Health,
604            target: None,
605            status: 200,
606            ..filled("listen")
607        };
608        count(&tx, &health, datetime!(2026-10-23 12:34:00 UTC)).expect("count");
609        count(&tx, &filled("listen"), datetime!(2026-10-23 12:34:00 UTC)).expect("count");
610        let failed = Entry {
611            status: 503,
612            ..health.clone()
613        };
614        count(&tx, &failed, datetime!(2026-10-23 12:34:00 UTC)).expect("count");
615        tx.commit().expect("commit");
616        let statuses: Vec<_> = exported(&log.conn, None)
617            .iter()
618            .map(|r| r["status"].clone())
619            .collect();
620        assert_eq!(
621            statuses,
622            [200.into(), Value::Null, 503.into()],
623            "only the record that answers no request has none"
624        );
625    }
626
627    #[test]
628    fn no_http_status_is_the_number_kept_for_no_answer() {
629        assert_eq!(NO_ANSWER, 0, "the number an entry holds in memory");
630        assert!(
631            axum::http::StatusCode::from_u16(NO_ANSWER).is_err(),
632            "it is not a status a server can answer"
633        );
634    }
635
636    #[test]
637    fn counted_records_hold_one_row_per_actor_action_status_and_minute() {
638        let mut log = log();
639        let health = |status| Entry {
640            actor: Actor::Unparsed,
641            action: Action::Health,
642            target: None,
643            version: None,
644            status,
645        };
646        let tx = log.conn.transaction().expect("tx");
647        for second in [0, 30, 59] {
648            let now = datetime!(2026-10-23 12:34:00 UTC) + time::Duration::seconds(second);
649            count(&tx, &health(200), now).expect("count");
650        }
651        count(&tx, &health(200), datetime!(2026-10-23 12:35:00 UTC)).expect("next minute");
652        count(&tx, &health(503), datetime!(2026-10-23 12:34:10 UTC)).expect("other status");
653        // Same actor, status and minute as the 503 health record above,
654        // so only the action keeps the two apart.
655        let failed = Entry {
656            action: Action::AuthFailed,
657            ..health(503)
658        };
659        count(&tx, &failed, datetime!(2026-10-23 12:34:20 UTC)).expect("other action");
660        let cli = Entry {
661            actor: Actor::Cli,
662            ..health(200)
663        };
664        count(&tx, &cli, datetime!(2026-10-23 12:34:40 UTC)).expect("other actor");
665        tx.commit().expect("commit");
666        let rows: Vec<(String, String, String, u64, u64)> = exported(&log.conn, None)
667            .iter()
668            .map(|r| {
669                (
670                    r["at"].as_str().expect("at").to_owned(),
671                    r["actor"].as_str().expect("actor").to_owned(),
672                    r["action"].as_str().expect("action").to_owned(),
673                    r["status"].as_u64().expect("status"),
674                    r["count"].as_u64().expect("count"),
675                )
676            })
677            .collect();
678        let row = |at: &str, actor: &str, action: &str, status, count| {
679            (
680                at.to_owned(),
681                actor.to_owned(),
682                action.to_owned(),
683                status,
684                count,
685            )
686        };
687        assert_eq!(
688            rows,
689            [
690                row("2026-10-23T12:34:00Z", "", "health", 200, 3),
691                row("2026-10-23T12:35:00Z", "", "health", 200, 1),
692                row("2026-10-23T12:34:00Z", "", "health", 503, 1),
693                row("2026-10-23T12:34:00Z", "", "auth_failed", 503, 1),
694                row("2026-10-23T12:34:00Z", "cli", "health", 200, 1),
695            ]
696        );
697    }
698
699    #[test]
700    fn a_record_in_a_transaction_that_does_not_commit_is_not_kept() {
701        let mut log = log();
702        let tx = log.conn.transaction().expect("tx");
703        let key = Key::generate().expect("key").id();
704        record(&tx, &read_by(key, 200), datetime!(2026-10-23 12:00:00 UTC)).expect("record");
705        drop(tx);
706        assert_eq!(exported(&log.conn, None), Vec::<Value>::new());
707    }
708
709    #[test]
710    fn every_action_has_its_name_in_the_log() {
711        // The name each action has in the logs, which exports and the audit
712        // routes give to operators. The match has no catch-all arm, so a
713        // new action fails to compile here until its name is written down.
714        let named = |action: Action| match action {
715            Action::Create => "create",
716            Action::Replace => "replace",
717            Action::Read => "read",
718            Action::ReadMasked => "read_masked",
719            Action::Reveal(Part::Parties) => "reveal_parties",
720            Action::Reveal(Part::Subject) => "reveal_subject",
721            Action::Reveal(Part::Dialog) => "reveal_dialog",
722            Action::Reveal(Part::Analysis) => "reveal_analysis",
723            Action::Reveal(Part::Links) => "reveal_links",
724            Action::Reveal(Part::All) => "reveal_all",
725            Action::Reveal(Part::Audio) => "reveal_audio",
726            Action::Delete => "delete",
727            Action::Purge => "purge",
728            Action::LegalRead => "legal_read",
729            Action::LegalReadMasked => "legal_read_masked",
730            Action::LegalReveal(Part::Parties) => "legal_reveal_parties",
731            Action::LegalReveal(Part::Subject) => "legal_reveal_subject",
732            Action::LegalReveal(Part::Dialog) => "legal_reveal_dialog",
733            Action::LegalReveal(Part::Analysis) => "legal_reveal_analysis",
734            Action::LegalReveal(Part::Links) => "legal_reveal_links",
735            Action::LegalReveal(Part::All) => "legal_reveal_all",
736            Action::LegalReveal(Part::Audio) => "legal_reveal_audio",
737            Action::LegalVersions => "legal_versions",
738            Action::Restore => "restore",
739            Action::Hold => "hold",
740            Action::Release => "release",
741            Action::KeyCreate => "key_create",
742            Action::KeyRevoke => "key_revoke",
743            Action::KeyList => "key_list",
744            Action::KeyInfo => "key_info",
745            Action::Retention => "retention",
746            Action::Health => "health",
747            Action::AuthFailed => "auth_failed",
748            Action::TenantCreate => "tenant_create",
749            Action::TenantList => "tenant_list",
750            Action::TenantRetention => "tenant_retention",
751            Action::TenantRemove => "tenant_remove",
752            Action::RekeyMaster => "rekey_master",
753            Action::RekeyTenant => "rekey_tenant",
754            Action::List => "list",
755            Action::AuditRead => "audit_read",
756            Action::Openapi => "openapi",
757            Action::Backup => "backup",
758            Action::Export => "export",
759            Action::TenantMetadata => "tenant_metadata",
760            Action::Metadata => "metadata",
761            Action::Mcp => "mcp",
762            Action::WrongListener => "wrong_listener",
763            Action::ListenerFull => "listener_full",
764            Action::CspReport => "csp_report",
765            Action::UserAdd => "user_add",
766            Action::UserList => "user_list",
767            Action::UserDeactivate => "user_deactivate",
768            Action::MembershipGrant => "membership_grant",
769            Action::MembershipRevoke => "membership_revoke",
770            Action::RoleCapSet => "role_cap_set",
771            Action::RoleCapRead => "role_cap_read",
772            Action::SettingsRead => "settings_read",
773            Action::SettingsSet => "settings_set",
774            Action::MembershipList => "membership_list",
775            Action::SessionStart => "session_start",
776            Action::SessionRead => "session_read",
777            Action::SessionEnd => "session_end",
778        };
779        let every = [
780            Action::Create,
781            Action::Replace,
782            Action::Read,
783            Action::ReadMasked,
784            Action::Reveal(Part::Parties),
785            Action::Reveal(Part::Subject),
786            Action::Reveal(Part::Dialog),
787            Action::Reveal(Part::Analysis),
788            Action::Reveal(Part::Links),
789            Action::Reveal(Part::All),
790            Action::Reveal(Part::Audio),
791            Action::Delete,
792            Action::Purge,
793            Action::LegalRead,
794            Action::LegalReadMasked,
795            Action::LegalReveal(Part::Parties),
796            Action::LegalReveal(Part::Subject),
797            Action::LegalReveal(Part::Dialog),
798            Action::LegalReveal(Part::Analysis),
799            Action::LegalReveal(Part::Links),
800            Action::LegalReveal(Part::All),
801            Action::LegalReveal(Part::Audio),
802            Action::LegalVersions,
803            Action::Restore,
804            Action::Hold,
805            Action::Release,
806            Action::KeyCreate,
807            Action::KeyRevoke,
808            Action::KeyList,
809            Action::KeyInfo,
810            Action::Retention,
811            Action::Health,
812            Action::AuthFailed,
813            Action::TenantCreate,
814            Action::TenantList,
815            Action::TenantRetention,
816            Action::TenantRemove,
817            Action::RekeyMaster,
818            Action::RekeyTenant,
819            Action::List,
820            Action::AuditRead,
821            Action::Openapi,
822            Action::Backup,
823            Action::Export,
824            Action::TenantMetadata,
825            Action::Metadata,
826            Action::Mcp,
827            Action::WrongListener,
828            Action::ListenerFull,
829            Action::CspReport,
830            Action::UserAdd,
831            Action::UserList,
832            Action::UserDeactivate,
833            Action::MembershipGrant,
834            Action::MembershipRevoke,
835            Action::RoleCapSet,
836            Action::RoleCapRead,
837            Action::SettingsRead,
838            Action::SettingsSet,
839            Action::MembershipList,
840            Action::SessionStart,
841            Action::SessionRead,
842            Action::SessionEnd,
843        ];
844        let mut seen = std::collections::BTreeSet::new();
845        for action in every {
846            assert_eq!(action.as_str(), named(action), "{action:?}");
847            assert!(
848                seen.insert(action.as_str()),
849                "{action:?}: a name of its own"
850            );
851        }
852    }
853
854    /// Five read records, at whole seconds.
855    fn five(log: &mut Log) {
856        let key = Key::generate().expect("key").id();
857        let tx = log.conn.transaction().expect("tx");
858        for second in 0..5 {
859            let now = datetime!(2026-10-23 12:00:00 UTC) + time::Duration::seconds(second);
860            record(&tx, &read_by(key, 200), now).expect("record");
861        }
862        tx.commit().expect("commit");
863    }
864
865    fn exported_text(log: &Connection, since: Option<i64>) -> String {
866        let mut out = Vec::new();
867        export(log, since, &mut out).expect("export");
868        String::from_utf8(out).expect("UTF-8")
869    }
870
871    fn paged(log: &Connection, after: i64, limit: u32) -> String {
872        let mut out = Vec::new();
873        page(log, &AuditQuery { after, limit }, &mut out).expect("page");
874        String::from_utf8(out).expect("UTF-8")
875    }
876
877    #[test]
878    fn a_page_is_the_first_lines_export_writes_from_the_same_place() {
879        let mut log = log();
880        five(&mut log);
881        for after in 0..=6 {
882            let lines: Vec<String> = exported_text(&log.conn, Some(after))
883                .lines()
884                .map(|l| format!("{l}\n"))
885                .collect();
886            for limit in 1..=6 {
887                let take = lines.len().min(usize::try_from(limit).expect("small"));
888                assert_eq!(
889                    paged(&log.conn, after, limit),
890                    lines[..take].concat(),
891                    "after {after}, limit {limit}"
892                );
893            }
894        }
895        assert_eq!(paged(&log.conn, 0, 10), exported_text(&log.conn, None));
896    }
897
898    #[test]
899    fn an_audit_query_takes_a_seq_and_a_limit_of_1_to_10000() {
900        let q = |after, limit| AuditQuery { after, limit };
901        assert_eq!(AuditQuery::new(None, None), Ok(q(0, 1000)));
902        assert_eq!(AuditQuery::new(Some(7), Some(1)), Ok(q(7, 1)));
903        assert_eq!(AuditQuery::new(None, Some(10000)), Ok(q(0, 10000)));
904        assert_eq!(
905            AuditQuery::new(Some(i64::MAX as u64), None),
906            Ok(q(i64::MAX, 1000))
907        );
908        for (after, limit) in [
909            (None, Some(0)),
910            (None, Some(10001)),
911            (None, Some(u64::MAX)),
912            (Some(i64::MAX as u64 + 1), None),
913        ] {
914            assert_eq!(
915                AuditQuery::new(after, limit),
916                Err(BadQuery),
917                "{after:?} {limit:?}"
918            );
919        }
920        assert_eq!(AuditQuery::from_query(None), Ok(q(0, 1000)));
921        assert_eq!(
922            AuditQuery::from_query(Some("after=12&limit=3")),
923            Ok(q(12, 3))
924        );
925        for bad in [
926            "after=-1",
927            "after=x",
928            "after=",
929            "limit=0",
930            "limit=1&limit=1",
931            "since=3",
932            "after=1.0",
933        ] {
934            assert_eq!(AuditQuery::from_query(Some(bad)), Err(BadQuery), "{bad}");
935        }
936    }
937}