vcon-server 0.4.5

Stores vCons encrypted at rest, on local disk or in an S3 bucket (as objects or Parquet files), and returns them to authorized readers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
//! The audit log: one record per request, written in the same transaction
//! as the change it describes. A record holds no vCon content, no token
//! and no client address.

use std::io::{self, Write};

use rusqlite::{Connection, params};
use serde_json::json;
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;

use crate::ids::{KeyId, UserId, VersionId};
use crate::query::{self, BadQuery};
use crate::reveal::Part;

/// The audit table, part of every catalog that holds a log.
pub const SCHEMA: &str = "
CREATE TABLE audit (
    seq INTEGER PRIMARY KEY AUTOINCREMENT,
    at TEXT NOT NULL,
    actor TEXT NOT NULL,
    action TEXT NOT NULL,
    target TEXT,
    version TEXT,
    status INTEGER,
    count INTEGER NOT NULL
);
CREATE INDEX audit_counted ON audit (actor, action, status, at);
";

/// Who made a request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Actor {
    /// A caller's key.
    Key(KeyId),
    /// The purge sweep.
    Sweep,
    /// A command run on the host.
    Cli,
    /// A user who signed in, by a session.
    User(UserId),
    /// A caller with no known key: its token did not parse, or names a key
    /// id the key table does not hold; or a caller with no known session.
    Unparsed,
}

/// What a request asked for. A refused request records what it asked for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    Create,
    Replace,
    Read,
    /// A read marked as a reveal of one part of the vCon.
    Reveal(Part),
    Delete,
    Purge,
    LegalRead,
    /// A legal read marked as a reveal of one part of the version read.
    LegalReveal(Part),
    LegalVersions,
    Restore,
    Hold,
    Release,
    KeyCreate,
    KeyRevoke,
    KeyList,
    KeyInfo,
    Retention,
    Health,
    AuthFailed,
    TenantCreate,
    TenantList,
    TenantRetention,
    TenantRemove,
    RekeyMaster,
    RekeyTenant,
    List,
    AuditRead,
    Openapi,
    Backup,
    /// An export of the tenant's versions, as Parquet files.
    Export,
    /// A tenant's metadata level set, in the admin log.
    TenantMetadata,
    /// The tenant's metadata level set, in its own log.
    Metadata,
    /// A request to the MCP server, counted (`count`), not recorded.
    Mcp,
    /// A valid key refused because the listener it came to serves the
    /// other kind of key; counted (`count`), not recorded.
    WrongListener,
    /// A listener that found every one of its places held
    /// (`limits.connections`); counted (`count`), not recorded.
    ListenerFull,
    /// A report of a content-security-policy violation that a browser
    /// sent to the console (`POST /console/csp-report`), under the status
    /// that answered it; counted (`count`), not recorded.
    CspReport,
    /// A user made, in the admin log.
    UserAdd,
    /// The users listed, in the admin log.
    UserList,
    /// A user deactivated and its memberships removed.
    UserDeactivate,
    /// Roles given to a user in a tenant, or as an operator.
    MembershipGrant,
    /// Roles taken from a user in a tenant, or as an operator.
    MembershipRevoke,
    /// A tenant's role cap set or removed.
    RoleCapSet,
    /// A tenant's role cap read, in the admin log.
    RoleCapRead,
    /// A tenant's settings read by its administrator.
    SettingsRead,
    /// A tenant's settings changed by its administrator.
    SettingsSet,
    /// A tenant's memberships listed by its administrator.
    MembershipList,
    /// A session started for a user who signed in.
    SessionStart,
    /// A session read by its own browser (`GET /session`), counted.
    SessionRead,
    /// A session ended by its user.
    SessionEnd,
}

impl Action {
    /// The name written in the log.
    pub fn as_str(self) -> &'static str {
        match self {
            Action::Create => "create",
            Action::Replace => "replace",
            Action::Read => "read",
            Action::Reveal(Part::Parties) => "reveal_parties",
            Action::Reveal(Part::Subject) => "reveal_subject",
            Action::Reveal(Part::Dialog) => "reveal_dialog",
            Action::Reveal(Part::Analysis) => "reveal_analysis",
            Action::Reveal(Part::Links) => "reveal_links",
            Action::Reveal(Part::All) => "reveal_all",
            Action::Reveal(Part::Audio) => "reveal_audio",
            Action::Delete => "delete",
            Action::Purge => "purge",
            Action::LegalRead => "legal_read",
            Action::LegalReveal(Part::Parties) => "legal_reveal_parties",
            Action::LegalReveal(Part::Subject) => "legal_reveal_subject",
            Action::LegalReveal(Part::Dialog) => "legal_reveal_dialog",
            Action::LegalReveal(Part::Analysis) => "legal_reveal_analysis",
            Action::LegalReveal(Part::Links) => "legal_reveal_links",
            Action::LegalReveal(Part::All) => "legal_reveal_all",
            Action::LegalReveal(Part::Audio) => "legal_reveal_audio",
            Action::LegalVersions => "legal_versions",
            Action::Restore => "restore",
            Action::Hold => "hold",
            Action::Release => "release",
            Action::KeyCreate => "key_create",
            Action::KeyRevoke => "key_revoke",
            Action::KeyList => "key_list",
            Action::KeyInfo => "key_info",
            Action::Retention => "retention",
            Action::Health => "health",
            Action::AuthFailed => "auth_failed",
            Action::TenantCreate => "tenant_create",
            Action::TenantList => "tenant_list",
            Action::TenantRetention => "tenant_retention",
            Action::TenantRemove => "tenant_remove",
            Action::RekeyMaster => "rekey_master",
            Action::RekeyTenant => "rekey_tenant",
            Action::List => "list",
            Action::AuditRead => "audit_read",
            Action::Openapi => "openapi",
            Action::Backup => "backup",
            Action::Export => "export",
            Action::TenantMetadata => "tenant_metadata",
            Action::Metadata => "metadata",
            Action::Mcp => "mcp",
            Action::WrongListener => "wrong_listener",
            Action::ListenerFull => "listener_full",
            Action::CspReport => "csp_report",
            Action::UserAdd => "user_add",
            Action::UserList => "user_list",
            Action::UserDeactivate => "user_deactivate",
            Action::MembershipGrant => "membership_grant",
            Action::MembershipRevoke => "membership_revoke",
            Action::RoleCapSet => "role_cap_set",
            Action::RoleCapRead => "role_cap_read",
            Action::SettingsRead => "settings_read",
            Action::SettingsSet => "settings_set",
            Action::MembershipList => "membership_list",
            Action::SessionStart => "session_start",
            Action::SessionRead => "session_read",
            Action::SessionEnd => "session_end",
        }
    }
}

/// One request, as recorded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
    pub actor: Actor,
    pub action: Action,
    /// The vCon's uuid, or the tenant or key id for an admin action.
    pub target: Option<String>,
    /// The version written, read or purged, if there is one.
    pub version: Option<VersionId>,
    /// The HTTP status answered, or the command's result; [`NO_ANSWER`]
    /// for a record of something that answers no request.
    pub status: u16,
}

/// The `status` of a record that answers no request, such as a listener
/// that filled. No HTTP status is 0. The number is an entry's only: the
/// log's column holds NULL for it (`stored`), and a record read back
/// (`export`, `page`) has `null` there. Catalogs before schema version 5
/// held the number, and the upgrade to 5 replaces it.
pub const NO_ANSWER: u16 = 0;

/// What the log's column holds for an entry's `status`: the status, or
/// NULL for [`NO_ANSWER`]. The one place the number becomes no status.
fn stored(status: u16) -> Option<u16> {
    Some(status).filter(|status| *status != NO_ANSWER)
}

/// Why a record could not be written or exported.
#[derive(Debug)]
pub enum AuditError {
    Sqlite(rusqlite::Error),
    Write(io::Error),
}

impl From<rusqlite::Error> for AuditError {
    fn from(e: rusqlite::Error) -> AuditError {
        AuditError::Sqlite(e)
    }
}

impl Actor {
    /// The name written in the log: the key id, `sweep`, `cli`,
    /// `user:<id>`, or empty.
    fn name(self) -> String {
        match self {
            Actor::User(id) => format!("user:{id}"),
            Actor::Key(id) => id.to_string(),
            Actor::Sweep => "sweep".to_owned(),
            Actor::Cli => "cli".to_owned(),
            Actor::Unparsed => String::new(),
        }
    }
}

/// `now` in RFC 3339, in UTC.
fn rfc3339(now: OffsetDateTime) -> String {
    now.to_offset(time::UtcOffset::UTC)
        .format(&Rfc3339)
        .expect("every UTC time from the clock formats")
}

/// Appends one record, at `now`, in `tx`.
pub fn record(tx: &Connection, entry: &Entry, now: OffsetDateTime) -> Result<(), AuditError> {
    tx.execute(
        "INSERT INTO audit (at, actor, action, target, version, status, count)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, 1)",
        params![
            rfc3339(now),
            entry.actor.name(),
            entry.action.as_str(),
            entry.target,
            entry.version.map(|v| v.to_string()),
            stored(entry.status),
        ],
    )?;
    Ok(())
}

/// Adds one to the record for this actor, action and status in the minute
/// of `now`, making it if needed. For requests that could otherwise grow a
/// log one row each: failed authentications and health checks.
pub fn count(tx: &Connection, entry: &Entry, now: OffsetDateTime) -> Result<(), AuditError> {
    count_many(tx, entry, now, 1)
}

/// Adds `times` to the record for this actor, action and status in the
/// minute of `now`, making it if needed: [`count`] for what was added up
/// before it is written, so that many requests cost one write.
pub fn count_many(
    tx: &Connection,
    entry: &Entry,
    now: OffsetDateTime,
    times: u64,
) -> Result<(), AuditError> {
    // A count of nothing makes no record.
    if times == 0 {
        return Ok(());
    }
    let times = i64::try_from(times).unwrap_or(i64::MAX);
    let minute = now
        .to_offset(time::UtcOffset::UTC)
        .replace_second(0)
        .and_then(|t| t.replace_nanosecond(0))
        .expect("0 is a valid second and nanosecond");
    let fields = params![
        rfc3339(minute),
        entry.actor.name(),
        entry.action.as_str(),
        entry.target,
        entry.version.map(|v| v.to_string()),
        stored(entry.status),
        times,
    ];
    let added = tx.execute(
        "UPDATE audit SET count = count + ?7
         WHERE at = ?1 AND actor = ?2 AND action = ?3 AND target IS ?4 AND version IS ?5
           AND status IS ?6",
        fields,
    )?;
    if added == 0 {
        tx.execute(
            "INSERT INTO audit (at, actor, action, target, version, status, count)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
            fields,
        )?;
    }
    Ok(())
}

/// Writes every record after `since` as JSON lines, oldest first.
pub fn export(log: &Connection, since: Option<i64>, out: &mut dyn Write) -> Result<(), AuditError> {
    // SQLite reads a negative limit as none.
    lines(log, since.unwrap_or(0), -1, out)
}

/// Writes at most `limit` records after `after` as JSON lines, oldest
/// first: the one rendering both `export` and `page` write.
fn lines(log: &Connection, after: i64, limit: i64, out: &mut dyn Write) -> Result<(), AuditError> {
    let mut rows = log.prepare(
        "SELECT seq, at, actor, action, target, version, status, count
         FROM audit WHERE seq > ?1 ORDER BY seq LIMIT ?2",
    )?;
    let mut rows = rows.query(params![after, limit])?;
    while let Some(row) = rows.next()? {
        // A record that answers no request has no status to show.
        let status = row.get::<_, Option<u16>>(6)?;
        let record = json!({
            "seq": row.get::<_, i64>(0)?,
            "at": row.get::<_, String>(1)?,
            "actor": row.get::<_, String>(2)?,
            "action": row.get::<_, String>(3)?,
            "target": row.get::<_, Option<String>>(4)?,
            "version": row.get::<_, Option<String>>(5)?,
            "status": status,
            "count": row.get::<_, i64>(7)?,
        });
        writeln!(out, "{record}").map_err(AuditError::Write)?;
    }
    Ok(())
}

/// What an audit read asks for: at most `limit` records after the seq
/// `after`, oldest first.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuditQuery {
    pub after: i64,
    pub limit: u32,
}

impl AuditQuery {
    pub const DEFAULT_LIMIT: u32 = 1000;
    pub const MAX_LIMIT: u32 = 10000;

    /// An audit query from its parameters' values, the one rule for them
    /// wherever they come from: `after` a seq (0, the default, is the
    /// start of the log), `limit` 1 to `MAX_LIMIT`.
    pub fn new(after: Option<u64>, limit: Option<u64>) -> Result<AuditQuery, BadQuery> {
        let after = after
            .map(|n| i64::try_from(n).map_err(|_| BadQuery))
            .transpose()?
            .unwrap_or(0);
        let limit = match limit {
            None => AuditQuery::DEFAULT_LIMIT,
            Some(n) => u32::try_from(n)
                .ok()
                .filter(|n| (1..=AuditQuery::MAX_LIMIT).contains(n))
                .ok_or(BadQuery)?,
        };
        Ok(AuditQuery { after, limit })
    }

    /// An audit query from an HTTP query string, which may name `after` and
    /// `limit`, each at most once.
    pub fn from_query(text: Option<&str>) -> Result<AuditQuery, BadQuery> {
        let read = query::pairs(text, &["after", "limit"])?;
        let number = |name| {
            read.get(name)
                .map(|n: &String| n.parse::<u64>().map_err(|_| BadQuery))
                .transpose()
        };
        AuditQuery::new(number("after")?, number("limit")?)
    }
}

/// Writes at most `query.limit` records after `query.after` as JSON lines,
/// oldest first: the first lines `export` writes from the same place.
pub fn page(log: &Connection, query: &AuditQuery, out: &mut dyn Write) -> Result<(), AuditError> {
    lines(log, query.after, i64::from(query.limit), out)
}

/// Reading a log back, for tests.
#[cfg(test)]
pub(crate) mod testing {
    use rusqlite::Connection;
    use serde_json::Value;

    /// The records `export` writes after `since`, parsed.
    pub(crate) fn exported(log: &Connection, since: Option<i64>) -> Vec<Value> {
        let mut out = Vec::new();
        super::export(log, since, &mut out).expect("export");
        String::from_utf8(out)
            .expect("UTF-8")
            .lines()
            .map(|line| serde_json::from_str(line).expect("one JSON object per line"))
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use serde_json::{Value, json};
    use time::macros::datetime;

    use super::testing::exported;
    use super::*;
    use crate::catalog;
    use crate::envelope::Key;

    struct Log {
        _dir: tempfile::TempDir,
        conn: Connection,
    }

    fn log() -> Log {
        let dir = tempfile::tempdir().expect("temp dir");
        let key = Key::generate().expect("key");
        let conn = catalog::open(&dir.path().join("catalog.sqlite"), &key, SCHEMA).expect("opens");
        Log { _dir: dir, conn }
    }

    fn read_by(key: KeyId, status: u16) -> Entry {
        Entry {
            actor: Actor::Key(key),
            action: Action::Read,
            target: Some("01a07da8-c2bb-83e5-b9a2-279e0d16bc46".into()),
            version: Some(VersionId([0x22; 16])),
            status,
        }
    }

    #[test]
    fn records_are_written_and_exported_back() {
        let mut log = log();
        let key = Key::generate().expect("key").id();
        let tx = log.conn.transaction().expect("tx");
        record(
            &tx,
            &read_by(key, 200),
            datetime!(2026-10-23 12:34:56.789 UTC),
        )
        .expect("record");
        let purge = Entry {
            actor: Actor::Sweep,
            action: Action::Purge,
            target: Some("01a07da8-c2bb-83e5-b9a2-279e0d16bc46".into()),
            version: None,
            status: 200,
        };
        record(&tx, &purge, datetime!(2026-10-23 12:35:00 UTC)).expect("record");
        tx.commit().expect("commit");
        assert_eq!(
            exported(&log.conn, None),
            [
                json!({"seq": 1, "at": "2026-10-23T12:34:56.789Z", "actor": key.to_string(),
                       "action": "read", "target": "01a07da8-c2bb-83e5-b9a2-279e0d16bc46",
                       "version": "22".repeat(16), "status": 200, "count": 1}),
                json!({"seq": 2, "at": "2026-10-23T12:35:00Z", "actor": "sweep",
                       "action": "purge", "target": "01a07da8-c2bb-83e5-b9a2-279e0d16bc46",
                       "version": null, "status": 200, "count": 1}),
            ]
        );
        assert_eq!(
            exported(&log.conn, Some(1)).len(),
            1,
            "only records after seq 1"
        );
        assert_eq!(exported(&log.conn, Some(2)).len(), 0);
    }

    #[test]
    fn times_are_written_in_utc() {
        let mut log = log();
        let key = Key::generate().expect("key").id();
        let tx = log.conn.transaction().expect("tx");
        record(
            &tx,
            &read_by(key, 200),
            datetime!(2026-10-23 14:34:56 +02:00),
        )
        .expect("record");
        tx.commit().expect("commit");
        assert_eq!(exported(&log.conn, None)[0]["at"], "2026-10-23T12:34:56Z");
    }

    /// A listener that filled: a record that answers no request.
    fn filled(target: &str) -> Entry {
        Entry {
            actor: Actor::Unparsed,
            action: Action::ListenerFull,
            target: Some(target.to_owned()),
            version: None,
            status: NO_ANSWER,
        }
    }

    #[test]
    fn a_record_that_answers_no_request_is_read_back_with_no_status() {
        let mut log = log();
        let tx = log.conn.transaction().expect("tx");
        count(&tx, &filled("listen"), datetime!(2026-10-23 12:34:56 UTC)).expect("count");
        tx.commit().expect("commit");
        assert_eq!(
            exported(&log.conn, None),
            [json!({"seq": 1, "at": "2026-10-23T12:34:00Z", "actor": "",
                       "action": "listener_full", "target": "listen",
                       "version": null, "status": null, "count": 1}),],
            "null, not a status no caller was sent"
        );
    }

    #[test]
    fn a_record_with_no_status_is_written_as_a_json_null_in_export_and_in_a_page() {
        let mut log = log();
        let tx = log.conn.transaction().expect("tx");
        count(&tx, &filled("listen"), datetime!(2026-10-23 12:34:56 UTC)).expect("count");
        tx.commit().expect("commit");
        for text in [exported_text(&log.conn, None), paged(&log.conn, 0, 10)] {
            assert!(
                text.contains(r#""status":null"#),
                "the member is there: {text}"
            );
            assert!(!text.contains(r#""status":0"#), "and is no number: {text}");
        }
    }

    #[test]
    fn records_with_no_status_are_counted_by_the_minute_like_any_other() {
        let mut log = log();
        let tx = log.conn.transaction().expect("tx");
        for second in [0, 20, 40] {
            let now = datetime!(2026-10-23 12:34:00 UTC) + time::Duration::seconds(second);
            count(&tx, &filled("listen"), now).expect("count");
        }
        count(
            &tx,
            &filled("operator.listen"),
            datetime!(2026-10-23 12:34:30 UTC),
        )
        .expect("count");
        tx.commit().expect("commit");
        let rows: Vec<_> = exported(&log.conn, None)
            .iter()
            .map(|r| (r["target"].clone(), r["status"].clone(), r["count"].clone()))
            .collect();
        assert_eq!(
            rows,
            [
                ("listen".into(), Value::Null, 3.into()),
                ("operator.listen".into(), Value::Null, 1.into()),
            ],
            "one row for each target, each with no status"
        );
    }

    #[test]
    fn a_record_with_a_status_keeps_it_beside_one_with_none() {
        let mut log = log();
        let tx = log.conn.transaction().expect("tx");
        let health = Entry {
            action: Action::Health,
            target: None,
            status: 200,
            ..filled("listen")
        };
        count(&tx, &health, datetime!(2026-10-23 12:34:00 UTC)).expect("count");
        count(&tx, &filled("listen"), datetime!(2026-10-23 12:34:00 UTC)).expect("count");
        let failed = Entry {
            status: 503,
            ..health.clone()
        };
        count(&tx, &failed, datetime!(2026-10-23 12:34:00 UTC)).expect("count");
        tx.commit().expect("commit");
        let statuses: Vec<_> = exported(&log.conn, None)
            .iter()
            .map(|r| r["status"].clone())
            .collect();
        assert_eq!(
            statuses,
            [200.into(), Value::Null, 503.into()],
            "only the record that answers no request has none"
        );
    }

    #[test]
    fn no_http_status_is_the_number_kept_for_no_answer() {
        assert_eq!(NO_ANSWER, 0, "the number an entry holds in memory");
        assert!(
            axum::http::StatusCode::from_u16(NO_ANSWER).is_err(),
            "it is not a status a server can answer"
        );
    }

    #[test]
    fn counted_records_hold_one_row_per_actor_action_status_and_minute() {
        let mut log = log();
        let health = |status| Entry {
            actor: Actor::Unparsed,
            action: Action::Health,
            target: None,
            version: None,
            status,
        };
        let tx = log.conn.transaction().expect("tx");
        for second in [0, 30, 59] {
            let now = datetime!(2026-10-23 12:34:00 UTC) + time::Duration::seconds(second);
            count(&tx, &health(200), now).expect("count");
        }
        count(&tx, &health(200), datetime!(2026-10-23 12:35:00 UTC)).expect("next minute");
        count(&tx, &health(503), datetime!(2026-10-23 12:34:10 UTC)).expect("other status");
        // Same actor, status and minute as the 503 health record above,
        // so only the action keeps the two apart.
        let failed = Entry {
            action: Action::AuthFailed,
            ..health(503)
        };
        count(&tx, &failed, datetime!(2026-10-23 12:34:20 UTC)).expect("other action");
        let cli = Entry {
            actor: Actor::Cli,
            ..health(200)
        };
        count(&tx, &cli, datetime!(2026-10-23 12:34:40 UTC)).expect("other actor");
        tx.commit().expect("commit");
        let rows: Vec<(String, String, String, u64, u64)> = exported(&log.conn, None)
            .iter()
            .map(|r| {
                (
                    r["at"].as_str().expect("at").to_owned(),
                    r["actor"].as_str().expect("actor").to_owned(),
                    r["action"].as_str().expect("action").to_owned(),
                    r["status"].as_u64().expect("status"),
                    r["count"].as_u64().expect("count"),
                )
            })
            .collect();
        let row = |at: &str, actor: &str, action: &str, status, count| {
            (
                at.to_owned(),
                actor.to_owned(),
                action.to_owned(),
                status,
                count,
            )
        };
        assert_eq!(
            rows,
            [
                row("2026-10-23T12:34:00Z", "", "health", 200, 3),
                row("2026-10-23T12:35:00Z", "", "health", 200, 1),
                row("2026-10-23T12:34:00Z", "", "health", 503, 1),
                row("2026-10-23T12:34:00Z", "", "auth_failed", 503, 1),
                row("2026-10-23T12:34:00Z", "cli", "health", 200, 1),
            ]
        );
    }

    #[test]
    fn a_record_in_a_transaction_that_does_not_commit_is_not_kept() {
        let mut log = log();
        let tx = log.conn.transaction().expect("tx");
        let key = Key::generate().expect("key").id();
        record(&tx, &read_by(key, 200), datetime!(2026-10-23 12:00:00 UTC)).expect("record");
        drop(tx);
        assert_eq!(exported(&log.conn, None), Vec::<Value>::new());
    }

    #[test]
    fn every_action_has_its_name_in_the_log() {
        // The name each action has in the logs, which exports and the audit
        // routes give to operators. The match has no catch-all arm, so a
        // new action fails to compile here until its name is written down.
        let named = |action: Action| match action {
            Action::Create => "create",
            Action::Replace => "replace",
            Action::Read => "read",
            Action::Reveal(Part::Parties) => "reveal_parties",
            Action::Reveal(Part::Subject) => "reveal_subject",
            Action::Reveal(Part::Dialog) => "reveal_dialog",
            Action::Reveal(Part::Analysis) => "reveal_analysis",
            Action::Reveal(Part::Links) => "reveal_links",
            Action::Reveal(Part::All) => "reveal_all",
            Action::Reveal(Part::Audio) => "reveal_audio",
            Action::Delete => "delete",
            Action::Purge => "purge",
            Action::LegalRead => "legal_read",
            Action::LegalReveal(Part::Parties) => "legal_reveal_parties",
            Action::LegalReveal(Part::Subject) => "legal_reveal_subject",
            Action::LegalReveal(Part::Dialog) => "legal_reveal_dialog",
            Action::LegalReveal(Part::Analysis) => "legal_reveal_analysis",
            Action::LegalReveal(Part::Links) => "legal_reveal_links",
            Action::LegalReveal(Part::All) => "legal_reveal_all",
            Action::LegalReveal(Part::Audio) => "legal_reveal_audio",
            Action::LegalVersions => "legal_versions",
            Action::Restore => "restore",
            Action::Hold => "hold",
            Action::Release => "release",
            Action::KeyCreate => "key_create",
            Action::KeyRevoke => "key_revoke",
            Action::KeyList => "key_list",
            Action::KeyInfo => "key_info",
            Action::Retention => "retention",
            Action::Health => "health",
            Action::AuthFailed => "auth_failed",
            Action::TenantCreate => "tenant_create",
            Action::TenantList => "tenant_list",
            Action::TenantRetention => "tenant_retention",
            Action::TenantRemove => "tenant_remove",
            Action::RekeyMaster => "rekey_master",
            Action::RekeyTenant => "rekey_tenant",
            Action::List => "list",
            Action::AuditRead => "audit_read",
            Action::Openapi => "openapi",
            Action::Backup => "backup",
            Action::Export => "export",
            Action::TenantMetadata => "tenant_metadata",
            Action::Metadata => "metadata",
            Action::Mcp => "mcp",
            Action::WrongListener => "wrong_listener",
            Action::ListenerFull => "listener_full",
            Action::CspReport => "csp_report",
            Action::UserAdd => "user_add",
            Action::UserList => "user_list",
            Action::UserDeactivate => "user_deactivate",
            Action::MembershipGrant => "membership_grant",
            Action::MembershipRevoke => "membership_revoke",
            Action::RoleCapSet => "role_cap_set",
            Action::RoleCapRead => "role_cap_read",
            Action::SettingsRead => "settings_read",
            Action::SettingsSet => "settings_set",
            Action::MembershipList => "membership_list",
            Action::SessionStart => "session_start",
            Action::SessionRead => "session_read",
            Action::SessionEnd => "session_end",
        };
        let every = [
            Action::Create,
            Action::Replace,
            Action::Read,
            Action::Reveal(Part::Parties),
            Action::Reveal(Part::Subject),
            Action::Reveal(Part::Dialog),
            Action::Reveal(Part::Analysis),
            Action::Reveal(Part::Links),
            Action::Reveal(Part::All),
            Action::Reveal(Part::Audio),
            Action::Delete,
            Action::Purge,
            Action::LegalRead,
            Action::LegalReveal(Part::Parties),
            Action::LegalReveal(Part::Subject),
            Action::LegalReveal(Part::Dialog),
            Action::LegalReveal(Part::Analysis),
            Action::LegalReveal(Part::Links),
            Action::LegalReveal(Part::All),
            Action::LegalReveal(Part::Audio),
            Action::LegalVersions,
            Action::Restore,
            Action::Hold,
            Action::Release,
            Action::KeyCreate,
            Action::KeyRevoke,
            Action::KeyList,
            Action::KeyInfo,
            Action::Retention,
            Action::Health,
            Action::AuthFailed,
            Action::TenantCreate,
            Action::TenantList,
            Action::TenantRetention,
            Action::TenantRemove,
            Action::RekeyMaster,
            Action::RekeyTenant,
            Action::List,
            Action::AuditRead,
            Action::Openapi,
            Action::Backup,
            Action::Export,
            Action::TenantMetadata,
            Action::Metadata,
            Action::Mcp,
            Action::WrongListener,
            Action::ListenerFull,
            Action::CspReport,
            Action::UserAdd,
            Action::UserList,
            Action::UserDeactivate,
            Action::MembershipGrant,
            Action::MembershipRevoke,
            Action::RoleCapSet,
            Action::RoleCapRead,
            Action::SettingsRead,
            Action::SettingsSet,
            Action::MembershipList,
            Action::SessionStart,
            Action::SessionRead,
            Action::SessionEnd,
        ];
        let mut seen = std::collections::BTreeSet::new();
        for action in every {
            assert_eq!(action.as_str(), named(action), "{action:?}");
            assert!(
                seen.insert(action.as_str()),
                "{action:?}: a name of its own"
            );
        }
    }

    /// Five read records, at whole seconds.
    fn five(log: &mut Log) {
        let key = Key::generate().expect("key").id();
        let tx = log.conn.transaction().expect("tx");
        for second in 0..5 {
            let now = datetime!(2026-10-23 12:00:00 UTC) + time::Duration::seconds(second);
            record(&tx, &read_by(key, 200), now).expect("record");
        }
        tx.commit().expect("commit");
    }

    fn exported_text(log: &Connection, since: Option<i64>) -> String {
        let mut out = Vec::new();
        export(log, since, &mut out).expect("export");
        String::from_utf8(out).expect("UTF-8")
    }

    fn paged(log: &Connection, after: i64, limit: u32) -> String {
        let mut out = Vec::new();
        page(log, &AuditQuery { after, limit }, &mut out).expect("page");
        String::from_utf8(out).expect("UTF-8")
    }

    #[test]
    fn a_page_is_the_first_lines_export_writes_from_the_same_place() {
        let mut log = log();
        five(&mut log);
        for after in 0..=6 {
            let lines: Vec<String> = exported_text(&log.conn, Some(after))
                .lines()
                .map(|l| format!("{l}\n"))
                .collect();
            for limit in 1..=6 {
                let take = lines.len().min(usize::try_from(limit).expect("small"));
                assert_eq!(
                    paged(&log.conn, after, limit),
                    lines[..take].concat(),
                    "after {after}, limit {limit}"
                );
            }
        }
        assert_eq!(paged(&log.conn, 0, 10), exported_text(&log.conn, None));
    }

    #[test]
    fn an_audit_query_takes_a_seq_and_a_limit_of_1_to_10000() {
        let q = |after, limit| AuditQuery { after, limit };
        assert_eq!(AuditQuery::new(None, None), Ok(q(0, 1000)));
        assert_eq!(AuditQuery::new(Some(7), Some(1)), Ok(q(7, 1)));
        assert_eq!(AuditQuery::new(None, Some(10000)), Ok(q(0, 10000)));
        assert_eq!(
            AuditQuery::new(Some(i64::MAX as u64), None),
            Ok(q(i64::MAX, 1000))
        );
        for (after, limit) in [
            (None, Some(0)),
            (None, Some(10001)),
            (None, Some(u64::MAX)),
            (Some(i64::MAX as u64 + 1), None),
        ] {
            assert_eq!(
                AuditQuery::new(after, limit),
                Err(BadQuery),
                "{after:?} {limit:?}"
            );
        }
        assert_eq!(AuditQuery::from_query(None), Ok(q(0, 1000)));
        assert_eq!(
            AuditQuery::from_query(Some("after=12&limit=3")),
            Ok(q(12, 3))
        );
        for bad in [
            "after=-1",
            "after=x",
            "after=",
            "limit=0",
            "limit=1&limit=1",
            "since=3",
            "after=1.0",
        ] {
            assert_eq!(AuditQuery::from_query(Some(bad)), Err(BadQuery), "{bad}");
        }
    }
}