From b79de5eaba3b45eb1b46bbe64e35066b7366c61d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 13:09:34 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=97=83=EF=B8=8F=20fix:=20audit=20rows=20o?= =?UTF-8?q?lder=20than=20365=20days=20are=20swept=20in=20batches?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/iz-core/src/store/audit.rs | 50 +++++++++++++++++++++++++++++++ crates/iz-web/src/sweeper.rs | 13 ++++++-- docs/architecture.md | 6 ++-- docs/conventions.md | 2 +- 4 files changed, 66 insertions(+), 5 deletions(-) diff --git a/crates/iz-core/src/store/audit.rs b/crates/iz-core/src/store/audit.rs index deeb0b0..79fab53 100644 --- a/crates/iz-core/src/store/audit.rs +++ b/crates/iz-core/src/store/audit.rs @@ -6,9 +6,11 @@ //! column holds what an operator needs to read the action (names, roles, counts), never a password, a //! token, a cookie or a secret: the caller is responsible for that. +use jiff::Timestamp; use serde_json::Value; use super::{db_err, new_id}; +use crate::clock::stamp_of; use crate::error::Result; use crate::store::Store; use crate::time::now_stamp; @@ -16,6 +18,10 @@ use crate::time::now_stamp; /// The kinds of actor an audit row can name. Matches the CHECK constraint of `audit_log.actor_kind`. pub const ACTOR_KINDS: [&str; 4] = ["member", "admin", "system", "anonymous"]; +/// Days an audit row is kept. Reason: a year covers a full review cycle; the sweeper deletes older rows and +/// nothing else does. +pub const AUDIT_RETENTION_DAYS: i64 = 365; + /// One row to append. `actor_id` is the member id (the OIDC `sub`) when there is one. #[derive(Debug, Clone)] pub struct AuditEntry<'a> { @@ -48,6 +54,19 @@ impl Store { } } + /// Deletes up to `batch` audit rows recorded before `cutoff`. Returns how many were deleted. Each call is one + /// statement, so the caller loops in batches and the writer is free between them. + pub async fn prune_audit(&self, cutoff: Timestamp, batch: i64) -> Result { + let cutoff = stamp_of(cutoff)?; + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM audit_log WHERE id IN (SELECT id FROM audit_log WHERE at < ?1 LIMIT ?2)", + (cutoff, batch), + ) + .await + .map_err(db_err) + } + /// The write behind [`Store::audit`]. Returns the error instead of logging it, so tests can check it. pub async fn append_audit(&self, entry: &AuditEntry<'_>) -> Result<()> { let data = serde_json::to_string(&entry.data).unwrap_or_else(|_| "{}".to_owned()); @@ -104,4 +123,35 @@ mod tests { .expect("count"); assert_eq!(count, Some(1)); } + + #[tokio::test] + async fn pruning_deletes_only_rows_before_the_cutoff() { + let dir = tempfile::tempdir().expect("temp dir"); + let store = Store::open(&dir.path().join("iz.db")).await.expect("store"); + { + let conn = store.inner.conn.lock().await; + conn.execute_batch( + "INSERT INTO audit_log (id, at, actor_kind, action, target_kind, data) \ + VALUES ('old', '2020-01-01T00:00:00.000000000Z', 'system', 'x', 'y', '{}'); + INSERT INTO audit_log (id, at, actor_kind, action, target_kind, data) \ + VALUES ('new', '2030-01-01T00:00:00.000000000Z', 'system', 'x', 'y', '{}');", + ) + .await + .expect("rows"); + } + assert_eq!( + store + .prune_audit(Timestamp::now(), 10) + .await + .expect("prune"), + 1 + ); + let conn = store.read_conn().await; + let left = super::super::fetch_opt(&conn, "SELECT COUNT(*) FROM audit_log", (), |row| { + super::super::col_int(row, 0) + }) + .await + .expect("count"); + assert_eq!(left, Some(1)); + } } diff --git a/crates/iz-web/src/sweeper.rs b/crates/iz-web/src/sweeper.rs index 2618991..9295eaf 100644 --- a/crates/iz-web/src/sweeper.rs +++ b/crates/iz-web/src/sweeper.rs @@ -1,8 +1,8 @@ //! The sweeper worker: housekeeping that is not urgent. It runs once at start and then every hour until the //! stop flag is set. Each run deletes expired sessions and expired logout-token records, retries the //! attachment copies still owed (the deleter in `attachments.rs` does this too, every few seconds; this pass -//! is the backstop), deletes activity and mail-ledger rows older than `RETENTION_DAYS`, and removes staged -//! uploads left in `data_dir/tmp` by a crash. +//! is the backstop), deletes activity and mail-ledger rows older than `RETENTION_DAYS`, deletes audit rows +//! older than `AUDIT_RETENTION_DAYS`, and removes staged uploads left in `data_dir/tmp` by a crash. //! //! It never deletes live data: pending mail, pending deletions that are not yet due, and sessions that have //! not expired are left alone. A failed step is logged and the next step still runs. @@ -12,6 +12,7 @@ use std::path::Path; use std::time::{Duration, SystemTime}; use iz_core::staging::TMP_DIR; +use iz_core::store::audit::AUDIT_RETENTION_DAYS; use iz_core::store::sweep::RETENTION_DAYS; use jiff::{SignedDuration, Timestamp}; use tokio::sync::watch; @@ -64,6 +65,14 @@ async fn sweep(state: &AppState) { tracing::warn!(error = %error, "retention cutoff is out of range; not pruned") } } + match Timestamp::now().checked_sub(SignedDuration::from_hours(24 * AUDIT_RETENTION_DAYS)) { + Ok(cutoff) => { + drain("audit rows", |batch| state.store.prune_audit(cutoff, batch)).await; + } + Err(error) => { + tracing::warn!(error = %error, "retention cutoff is out of range; not pruned") + } + } note( "stale staged uploads", remove_stale_temp_files(&state.config.data_dir).await, diff --git a/docs/architecture.md b/docs/architecture.md index 875b1f8..34b8795 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -122,7 +122,9 @@ as old iz. Recipients are always active members with role ≠ viewer/none, never **reminders**: `task_id`, `sub`, `due_at`, `sent_at` NULL; PK (task_id, sub). Rebuilt for a task in the same transaction as any change to its meeting time, assignees, done state or deletion. -**audit_log**, **settings**: per conventions. Settings: SMTP sender (password sealed), limits, batching window, +**audit_log**: append-only; rows older than 365 days (`AUDIT_RETENTION_DAYS`, `iz-core/src/store/audit.rs`) are deleted by +the sweeper in batches of 500, one statement each, so the writer is never held for a long purge. **settings**: per +conventions. Settings: SMTP sender (password sealed), limits, batching window, reminder minutes (0–1440), allowed attachment types, attachment limit (1–500 MiB), attachment location (`local`|`in`), `default_role`, `key_prefix`, retention days for activity and mail ledger (default 365), base URL, trusted proxies. @@ -199,7 +201,7 @@ Member, or Admin. Truth-table tested. ## 8. Workers directory mirror, family list, mail outbox, reminders, attachment mover, sweeper (sessions, JTIs, retention of -activity and mail ledger, orphaned temp files), optional backup. All stop with the stop flag. +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. --- diff --git a/docs/conventions.md b/docs/conventions.md index eed1b03..f5869f3 100644 --- a/docs/conventions.md +++ b/docs/conventions.md @@ -132,7 +132,7 @@ unit-tested as a truth table. Append-only `audit_log` (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data JSON). Written after the change commits; a failed audit write is logged and never fails the request. Never store secrets in -`data`. Admin page with filters and keyset paging. Purge only through `admin audit-purge --older-than-days N`. +`data`. Admin page with filters and keyset paging. Rows older than the retention window are removed by the sweeper; nothing else deletes them. ## 11. i18n