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