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