tablo_audit/lib.rs
1//! The audit log for Tablo panels: an [`AuditEntry`] for each record every write of a panel
2//! names, stored inside the write's transaction, and the read-only [`AuditLog`] resource that
3//! lists them.
4//!
5//! It is built on Tablo's public API alone: a [`CommitHook`](tablo_core::CommitHook) stores the
6//! writes, an [`AuthHook`](tablo_core::AuthHook) stores what auth does, and [`AuditLog`] is an
7//! ordinary [`Resource`](tablo_core::Resource). [`PanelAuditExt`] registers them on a
8//! [`Panel`]:
9//!
10//! ```rust
11//! # use tablo_core::{Panel, when};
12//! # use topcoat::context::Cx;
13//! # fn is_admin(cx: &Cx) -> bool { false }
14//! use tablo_audit::PanelAuditExt;
15//!
16//! Panel::new("admin").audit_log(|log| log.policy(when(is_admin)));
17//! ```
18//!
19//! The `Db` registers [`AuditEntry`]: list it in the app's
20//! [`models!`](tablo_core::models!), as `tablo::models!(Post, tablo::audit::AuditEntry)`.
21
22mod entry;
23mod impersonation;
24mod log;
25mod trail;
26
27use std::time::Duration;
28
29use tablo_core::{Panel, PanelHandle, ResourceDef, TenantId};
30use topcoat::{context::Cx, l10n::locale};
31
32pub use self::{
33 entry::{AuditChange, AuditEntry, AuditEvent},
34 impersonation::{ImpersonationEvent, impersonations},
35 log::AuditLog,
36};
37
38/// The catalogs the log's words read from, under Tablo's and the app's.
39const CATALOGS: &[(topcoat::l10n::Locale, &str)] = &[
40 (locale!("en"), include_str!("../locales/en.ftl")),
41 (locale!("fr"), include_str!("../locales/fr.ftl")),
42];
43
44/// The audit log's registrations on a [`Panel`].
45pub trait PanelAuditExt {
46 /// Keeps an [`AuditEntry`] for each record every write of the panel names, inside the write's
47 /// transaction, as [`audit_trail`](Self::audit_trail) does, and lists them through the
48 /// [`AuditLog`] resource at `{prefix}/audit-log`, with `customize` adjusting its def.
49 ///
50 /// The log is denied to everyone until `customize` gives it a policy, and that policy allows
51 /// reads only. A reader sees the entries of the resources whose list they may open, whatever
52 /// row scope each resource's own query keeps, so the log's policy should be no wider than the
53 /// narrowest of them.
54 #[must_use]
55 fn audit_log(
56 self,
57 customize: impl FnOnce(ResourceDef<AuditLog>) -> ResourceDef<AuditLog> + Send + 'static,
58 ) -> Self;
59
60 /// Keeps an [`AuditEntry`] for each record every write of the panel names, inside the write's
61 /// transaction, and one for each [`AuthEvent`](tablo_core::AuthEvent) of the panel, a sign-in
62 /// or a change of credentials among them, without listing them: an [`Area`](tablo_core::Area)
63 /// group lists them with `group.resource_with::<AuditLog>(..)`. Calling it again changes
64 /// nothing.
65 ///
66 /// A CSV export stores an entry too, with the number of rows it hands over, before the first
67 /// byte leaves; an export whose entry fails to store is refused.
68 ///
69 /// Each entry names the [actor](tablo_core::auth::actor), the tenant they act for, the
70 /// resource and record, and the fields the write changed, as a
71 /// [`CommitHook`](tablo_core::CommitHook) reads them: a field marked `#[columns(skip)]`, such
72 /// as a password hash, is never stored. A write whose entry fails to store rolls back with
73 /// it, and so does a sign-in or a change of credentials; a refused sign-in, a sign-out and a
74 /// stop of impersonation go through unrecorded. A refused sign-in stores the login as it
75 /// was typed. Mounting refuses a `Db` that does not
76 /// register [`AuditEntry`], and an [`AuditLog`] on a panel without the trail.
77 #[must_use]
78 fn audit_trail(self) -> Self;
79}
80
81impl PanelAuditExt for Panel {
82 fn audit_log(
83 self,
84 customize: impl FnOnce(ResourceDef<AuditLog>) -> ResourceDef<AuditLog> + Send + 'static,
85 ) -> Self {
86 self.audit_trail().resource_with::<AuditLog>(customize)
87 }
88
89 fn audit_trail(self) -> Self {
90 CATALOGS.iter().fold(
91 self.before_commit::<trail::Trail>()
92 .auth_hook::<trail::Trail>()
93 .require_model::<AuditEntry>(),
94 |panel, (locale, catalog)| panel.default_translations(locale.clone(), *catalog),
95 )
96 }
97}
98
99/// Deletes the [`AuditEntry`] rows of `panel` older than `age`. Nothing else deletes them but
100/// [`forget_tenant`]; a job calls it on the schedule the app keeps its audit trail for.
101///
102/// # Errors
103///
104/// The driver's failure when the rows cannot be deleted.
105pub async fn prune(panel: &PanelHandle, age: Duration) -> topcoat::Result<()> {
106 let cutoff = jiff::Timestamp::now().checked_sub(jiff::SignedDuration::try_from(age)?)?;
107 let fields = AuditEntry::fields();
108 AuditEntry::filter(
109 fields
110 .panel()
111 .eq(panel.id().to_string())
112 .and(fields.created_at().lt(cutoff)),
113 )
114 .delete()
115 .exec(&mut tablo_core::db::db(&panel.context())?)
116 .await?;
117 Ok(())
118}
119
120/// Keeps what the user `user_id` did, but no longer who did it, for an account being erased: each
121/// entry they acted in names a deleted user, the `tablo-audit-deleted-user` message, in their
122/// place, and each auth entry done to their account, a sign-in or an impersonation of them, no
123/// longer holds their name. The entries' events, records and fields stay, as does the account's
124/// id, which names no one once the account is gone. A refused sign-in names no account and keeps
125/// the login it typed until [`prune`] deletes it. Run it through the transaction that deletes
126/// the account.
127///
128/// # Errors
129///
130/// The driver's failure when the rows cannot be read or written.
131pub async fn forget_actor(
132 cx: &Cx,
133 ex: &mut dyn toasty::Executor,
134 user_id: &str,
135) -> topcoat::Result<()> {
136 let deleted = tablo_core::t!(cx, "tablo-audit-deleted-user");
137 let fields = AuditEntry::fields();
138 AuditEntry::filter(fields.actor_id().eq(Some(user_id.to_owned())))
139 .update()
140 .actor_id(None::<String>)
141 .actor(deleted.clone())
142 .exec(&mut *ex)
143 .await?;
144 let done_to = AuditEntry::filter(
145 fields
146 .record()
147 .eq(Some(user_id.to_owned()))
148 .and(fields.resource().is_none()),
149 )
150 .exec(&mut *ex)
151 .await?;
152 for mut entry in done_to {
153 let mut changes = entry.changes.0.clone();
154 let mut scrubbed = false;
155 for change in &mut changes {
156 if change.field == impersonation::TARGET_FIELD {
157 change.after = Some(deleted.clone());
158 scrubbed = true;
159 }
160 }
161 if scrubbed {
162 entry
163 .update()
164 .changes(toasty::Json(changes))
165 .exec(&mut *ex)
166 .await?;
167 }
168 }
169 Ok(())
170}
171
172/// Deletes the entries filed under `tenant`, for a tenant being erased, but those recording an
173/// [impersonation](impersonations): a start is filed under the actor's tenant, and stays as the
174/// record of who reached which account until [`prune`] deletes it. Entries of panels that act for
175/// no tenant name none, and stay.
176///
177/// # Errors
178///
179/// The driver's failure when the rows cannot be deleted.
180pub async fn forget_tenant(ex: &mut dyn toasty::Executor, tenant: TenantId) -> topcoat::Result<()> {
181 AuditEntry::filter(
182 AuditEntry::fields()
183 .tenant()
184 .eq(Some(tenant))
185 .and(impersonations().not()),
186 )
187 .delete()
188 .exec(ex)
189 .await?;
190 Ok(())
191}