Audit rows older than 365 days are swept in batches
Browse files at this commitb79de5eaba3b45eb1b46bbe64e35066b7366c61dParent: a049e43- fix
- audit rows older than 365 days are swept in batches
4 changed files +66 -5
- crates/iz-core/src/store/audit.rs +50 -0
- crates/iz-web/src/sweeper.rs +11 -2
- docs/architecture.md +4 -2
- docs/conventions.md +1 -1
crates/iz-core/src/store/audit.rsmodified+50 -0
| @@ -6,9 +6,11 @@ | |||
| 6 | //! column holds what an operator needs to read the action (names, roles, counts), never a password, a | 6 | //! column holds what an operator needs to read the action (names, roles, counts), never a password, a |
| 7 | //! token, a cookie or a secret: the caller is responsible for that. | 7 | //! token, a cookie or a secret: the caller is responsible for that. |
| 8 | 8 | ||
| 9 | +use jiff::Timestamp; | ||
| 9 | use serde_json::Value; | 10 | use serde_json::Value; |
| 10 | 11 | ||
| 11 | use super::{db_err, new_id}; | 12 | use super::{db_err, new_id}; |
| 13 | +use crate::clock::stamp_of; | ||
| 12 | use crate::error::Result; | 14 | use crate::error::Result; |
| 13 | use crate::store::Store; | 15 | use crate::store::Store; |
| 14 | use crate::time::now_stamp; | 16 | use crate::time::now_stamp; |
| @@ -16,6 +18,10 @@ use crate::time::now_stamp; | |||
| 16 | /// The kinds of actor an audit row can name. Matches the CHECK constraint of `audit_log.actor_kind`. | 18 | /// The kinds of actor an audit row can name. Matches the CHECK constraint of `audit_log.actor_kind`. |
| 17 | pub const ACTOR_KINDS: [&str; 4] = ["member", "admin", "system", "anonymous"]; | 19 | pub const ACTOR_KINDS: [&str; 4] = ["member", "admin", "system", "anonymous"]; |
| 18 | 20 | ||
| 21 | +/// Days an audit row is kept. Reason: a year covers a full review cycle; the sweeper deletes older rows and | ||
| 22 | +/// nothing else does. | ||
| 23 | +pub const AUDIT_RETENTION_DAYS: i64 = 365; | ||
| 24 | + | ||
| 19 | /// One row to append. `actor_id` is the member id (the OIDC `sub`) when there is one. | 25 | /// One row to append. `actor_id` is the member id (the OIDC `sub`) when there is one. |
| 20 | #[derive(Debug, Clone)] | 26 | #[derive(Debug, Clone)] |
| 21 | pub struct AuditEntry<'a> { | 27 | pub struct AuditEntry<'a> { |
| @@ -48,6 +54,19 @@ impl Store { | |||
| 48 | } | 54 | } |
| 49 | } | 55 | } |
| 50 | 56 | ||
| 57 | + /// Deletes up to `batch` audit rows recorded before `cutoff`. Returns how many were deleted. Each call is one | ||
| 58 | + /// statement, so the caller loops in batches and the writer is free between them. | ||
| 59 | + pub async fn prune_audit(&self, cutoff: Timestamp, batch: i64) -> Result<u64> { | ||
| 60 | + let cutoff = stamp_of(cutoff)?; | ||
| 61 | + let conn = self.inner.conn.lock().await; | ||
| 62 | + conn.execute( | ||
| 63 | + "DELETE FROM audit_log WHERE id IN (SELECT id FROM audit_log WHERE at < ?1 LIMIT ?2)", | ||
| 64 | + (cutoff, batch), | ||
| 65 | + ) | ||
| 66 | + .await | ||
| 67 | + .map_err(db_err) | ||
| 68 | + } | ||
| 69 | + | ||
| 51 | /// The write behind [`Store::audit`]. Returns the error instead of logging it, so tests can check it. | 70 | /// The write behind [`Store::audit`]. Returns the error instead of logging it, so tests can check it. |
| 52 | pub async fn append_audit(&self, entry: &AuditEntry<'_>) -> Result<()> { | 71 | pub async fn append_audit(&self, entry: &AuditEntry<'_>) -> Result<()> { |
| 53 | let data = serde_json::to_string(&entry.data).unwrap_or_else(|_| "{}".to_owned()); | 72 | let data = serde_json::to_string(&entry.data).unwrap_or_else(|_| "{}".to_owned()); |
| @@ -104,4 +123,35 @@ mod tests { | |||
| 104 | .expect("count"); | 123 | .expect("count"); |
| 105 | assert_eq!(count, Some(1)); | 124 | assert_eq!(count, Some(1)); |
| 106 | } | 125 | } |
| 126 | + | ||
| 127 | + #[tokio::test] | ||
| 128 | + async fn pruning_deletes_only_rows_before_the_cutoff() { | ||
| 129 | + let dir = tempfile::tempdir().expect("temp dir"); | ||
| 130 | + let store = Store::open(&dir.path().join("iz.db")).await.expect("store"); | ||
| 131 | + { | ||
| 132 | + let conn = store.inner.conn.lock().await; | ||
| 133 | + conn.execute_batch( | ||
| 134 | + "INSERT INTO audit_log (id, at, actor_kind, action, target_kind, data) \ | ||
| 135 | + VALUES ('old', '2020-01-01T00:00:00.000000000Z', 'system', 'x', 'y', '{}'); | ||
| 136 | + INSERT INTO audit_log (id, at, actor_kind, action, target_kind, data) \ | ||
| 137 | + VALUES ('new', '2030-01-01T00:00:00.000000000Z', 'system', 'x', 'y', '{}');", | ||
| 138 | + ) | ||
| 139 | + .await | ||
| 140 | + .expect("rows"); | ||
| 141 | + } | ||
| 142 | + assert_eq!( | ||
| 143 | + store | ||
| 144 | + .prune_audit(Timestamp::now(), 10) | ||
| 145 | + .await | ||
| 146 | + .expect("prune"), | ||
| 147 | + 1 | ||
| 148 | + ); | ||
| 149 | + let conn = store.read_conn().await; | ||
| 150 | + let left = super::super::fetch_opt(&conn, "SELECT COUNT(*) FROM audit_log", (), |row| { | ||
| 151 | + super::super::col_int(row, 0) | ||
| 152 | + }) | ||
| 153 | + .await | ||
| 154 | + .expect("count"); | ||
| 155 | + assert_eq!(left, Some(1)); | ||
| 156 | + } | ||
| 107 | } | 157 | } |
crates/iz-web/src/sweeper.rsmodified+11 -2
| @@ -1,8 +1,8 @@ | |||
| 1 | //! The sweeper worker: housekeeping that is not urgent. It runs once at start and then every hour until the | 1 | //! The sweeper worker: housekeeping that is not urgent. It runs once at start and then every hour until the |
| 2 | //! stop flag is set. Each run deletes expired sessions and expired logout-token records, retries the | 2 | //! stop flag is set. Each run deletes expired sessions and expired logout-token records, retries the |
| 3 | //! attachment copies still owed (the deleter in `attachments.rs` does this too, every few seconds; this pass | 3 | //! attachment copies still owed (the deleter in `attachments.rs` does this too, every few seconds; this pass |
| 4 | -//! is the backstop), deletes activity and mail-ledger rows older than `RETENTION_DAYS`, and removes staged | 4 | +//! is the backstop), deletes activity and mail-ledger rows older than `RETENTION_DAYS`, deletes audit rows |
| 5 | -//! uploads left in `data_dir/tmp` by a crash. | 5 | +//! older than `AUDIT_RETENTION_DAYS`, and removes staged uploads left in `data_dir/tmp` by a crash. |
| 6 | //! | 6 | //! |
| 7 | //! It never deletes live data: pending mail, pending deletions that are not yet due, and sessions that have | 7 | //! It never deletes live data: pending mail, pending deletions that are not yet due, and sessions that have |
| 8 | //! not expired are left alone. A failed step is logged and the next step still runs. | 8 | //! not expired are left alone. A failed step is logged and the next step still runs. |
| @@ -12,6 +12,7 @@ use std::path::Path; | |||
| 12 | use std::time::{Duration, SystemTime}; | 12 | use std::time::{Duration, SystemTime}; |
| 13 | 13 | ||
| 14 | use iz_core::staging::TMP_DIR; | 14 | use iz_core::staging::TMP_DIR; |
| 15 | +use iz_core::store::audit::AUDIT_RETENTION_DAYS; | ||
| 15 | use iz_core::store::sweep::RETENTION_DAYS; | 16 | use iz_core::store::sweep::RETENTION_DAYS; |
| 16 | use jiff::{SignedDuration, Timestamp}; | 17 | use jiff::{SignedDuration, Timestamp}; |
| 17 | use tokio::sync::watch; | 18 | use tokio::sync::watch; |
| @@ -64,6 +65,14 @@ async fn sweep(state: &AppState) { | |||
| 64 | tracing::warn!(error = %error, "retention cutoff is out of range; not pruned") | 65 | tracing::warn!(error = %error, "retention cutoff is out of range; not pruned") |
| 65 | } | 66 | } |
| 66 | } | 67 | } |
| 68 | + match Timestamp::now().checked_sub(SignedDuration::from_hours(24 * AUDIT_RETENTION_DAYS)) { | ||
| 69 | + Ok(cutoff) => { | ||
| 70 | + drain("audit rows", |batch| state.store.prune_audit(cutoff, batch)).await; | ||
| 71 | + } | ||
| 72 | + Err(error) => { | ||
| 73 | + tracing::warn!(error = %error, "retention cutoff is out of range; not pruned") | ||
| 74 | + } | ||
| 75 | + } | ||
| 67 | note( | 76 | note( |
| 68 | "stale staged uploads", | 77 | "stale staged uploads", |
| 69 | remove_stale_temp_files(&state.config.data_dir).await, | 78 | remove_stale_temp_files(&state.config.data_dir).await, |
docs/architecture.mdmodified+4 -2
| @@ -122,7 +122,9 @@ as old iz. Recipients are always active members with role ≠ viewer/none, never | |||
| 122 | **reminders**: `task_id`, `sub`, `due_at`, `sent_at` NULL; PK (task_id, sub). Rebuilt for a task in the same | 122 | **reminders**: `task_id`, `sub`, `due_at`, `sent_at` NULL; PK (task_id, sub). Rebuilt for a task in the same |
| 123 | transaction as any change to its meeting time, assignees, done state or deletion. | 123 | transaction as any change to its meeting time, assignees, done state or deletion. |
| 124 | 124 | ||
| 125 | -**audit_log**, **settings**: per conventions. Settings: SMTP sender (password sealed), limits, batching window, | 125 | +**audit_log**: append-only; rows older than 365 days (`AUDIT_RETENTION_DAYS`, `iz-core/src/store/audit.rs`) are deleted by |
| 126 | +the sweeper in batches of 500, one statement each, so the writer is never held for a long purge. **settings**: per | ||
| 127 | +conventions. Settings: SMTP sender (password sealed), limits, batching window, | ||
| 126 | reminder minutes (0–1440), allowed attachment types, attachment limit (1–500 MiB), attachment location | 128 | reminder minutes (0–1440), allowed attachment types, attachment limit (1–500 MiB), attachment location |
| 127 | (`local`|`in`), `default_role`, `key_prefix`, retention days for activity and mail ledger (default 365), | 129 | (`local`|`in`), `default_role`, `key_prefix`, retention days for activity and mail ledger (default 365), |
| 128 | base URL, trusted proxies. | 130 | base URL, trusted proxies. |
| @@ -199,7 +201,7 @@ Member, or Admin. Truth-table tested. | |||
| 199 | ## 8. Workers | 201 | ## 8. Workers |
| 200 | 202 | ||
| 201 | directory mirror, family list, mail outbox, reminders, attachment mover, sweeper (sessions, JTIs, retention of | 203 | directory mirror, family list, mail outbox, reminders, attachment mover, sweeper (sessions, JTIs, retention of |
| 202 | -activity and mail ledger, orphaned temp files), optional backup. All stop with the stop flag. | 204 | +activity and mail ledger, audit rows past `AUDIT_RETENTION_DAYS` = 365 in batches of 500, orphaned temp files), optional backup. All stop with the stop flag. |
| 203 | 205 | ||
| 204 | --- | 206 | --- |
| 205 | 207 | ||
docs/conventions.mdmodified+1 -1
| @@ -132,7 +132,7 @@ unit-tested as a truth table. | |||
| 132 | 132 | ||
| 133 | Append-only `audit_log` (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data JSON). Written | 133 | Append-only `audit_log` (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data JSON). Written |
| 134 | after the change commits; a failed audit write is logged and never fails the request. Never store secrets in | 134 | after the change commits; a failed audit write is logged and never fails the request. Never store secrets in |
| 135 | -`data`. Admin page with filters and keyset paging. Purge only through `admin audit-purge --older-than-days N`. | 135 | +`data`. Admin page with filters and keyset paging. Rows older than the retention window are removed by the sweeper; nothing else deletes them. |
| 136 | 136 | ||
| 137 | ## 11. i18n | 137 | ## 11. i18n |
| 138 | 138 | ||