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