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