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