Skip to main content

vcon_server/
audit.rs

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