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