Skip to main content

themis/
audit.rs

1//! Audit trail of permission changes (feature `audit`).
2//!
3//! Every grant change, ReBAC tuple change or role assignment becomes an [`AuditRecord`], accepted
4//! or refused. The [`AuditLevel`] decides how much of each record is kept, and therefore the
5//! storage cost ([`AuditLevel::estimate_bytes`]). The destination is an [`AuditSink`]:
6//! memory, a JSON Lines file or your own implementation (table, queue, SIEM).
7//!
8//! At the [`AuditLevel::Forensic`] level the records form a SHA-256 hash chain: each one carries
9//! the hash of the previous one, so deleting or editing a record breaks verification
10//! ([`verify_chain`]).
11
12use std::fmt;
13use std::io::Write;
14use std::sync::{Arc, Mutex, MutexGuard};
15
16use serde::{Deserialize, Serialize};
17use sha2::{Digest, Sha256};
18
19use crate::attr::Attributes;
20use crate::decision::{Decision, Reason, Request};
21use crate::engine::{Context, Engine};
22use crate::explain::Explanation;
23use crate::governance::{Mutation, Violation};
24use crate::grant::{Effect, Grant, SubjectMatcher, TargetSelector};
25use crate::rebac::Tuple;
26use crate::resource::{Anchor, Resource};
27use crate::subject::{RoleAssignment, Subject};
28
29/// How much of each change is recorded. Each level includes everything from the previous one.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
31#[serde(rename_all = "snake_case")]
32pub enum AuditLevel {
33    /// Who, when, what (object id) and whether it was applied.
34    Minimal,
35    /// Plus a summary of the change (permission, subject, target, effect, scope) and the names of the
36    /// invariants that refused it.
37    Standard,
38    /// Plus the whole object (grant with condition, tuple), the full actor, the violation messages
39    /// and the application metadata (ip, request id, reason).
40    Detailed,
41    /// Plus the digest of the grant set before and after, and the hash chain.
42    Forensic,
43}
44
45impl AuditLevel {
46    pub const ALL: [AuditLevel; 4] = [
47        AuditLevel::Minimal,
48        AuditLevel::Standard,
49        AuditLevel::Detailed,
50        AuditLevel::Forensic,
51    ];
52
53    /// Typical size of a record in compact JSON, in bytes, measured on the reference record of
54    /// [`reference_record`] (grant with a scope and a two-clause condition, actor with two roles and
55    /// three metadata entries). The test `estimates_match_reference_records` keeps these numbers
56    /// honest.
57    pub const fn typical_record_bytes(self) -> u64 {
58        match self {
59            AuditLevel::Minimal => 174,
60            AuditLevel::Standard => 387,
61            AuditLevel::Detailed => 1_096,
62            AuditLevel::Forensic => 1_414,
63        }
64    }
65
66    /// Like [`AuditLevel::typical_record_bytes`], for decision records, measured on
67    /// [`reference_decision_record`] (three grants in the source, one with a condition).
68    pub const fn typical_decision_bytes(self) -> u64 {
69        match self {
70            AuditLevel::Minimal => 284,
71            AuditLevel::Standard => 668,
72            AuditLevel::Detailed => 1_238,
73            AuditLevel::Forensic => 3_581,
74        }
75    }
76
77    pub const fn estimate_decision_bytes(self, records: u64) -> u64 {
78        (self.typical_decision_bytes() + 1) * records
79    }
80
81    /// Storage estimate for `records` records in JSON Lines, with no compression and no index. In a
82    /// database, add the per-row overhead (in Postgres, about 28 bytes between the tuple header and the
83    /// item pointer, plus whatever indexes you create).
84    pub const fn estimate_bytes(self, records: u64) -> u64 {
85        (self.typical_record_bytes() + 1) * records
86    }
87}
88
89impl fmt::Display for AuditLevel {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        f.write_str(match self {
92            AuditLevel::Minimal => "minimal",
93            AuditLevel::Standard => "standard",
94            AuditLevel::Detailed => "detailed",
95            AuditLevel::Forensic => "forensic",
96        })
97    }
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(rename_all = "snake_case")]
102pub enum AuditAction {
103    GrantAdd,
104    GrantRemove,
105    TupleAdd,
106    TupleRemove,
107    RoleAssign,
108    RoleRevoke,
109    /// An access decision (`Engine::decide`), not a change.
110    Decision,
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(rename_all = "snake_case")]
115pub enum AuditOutcome {
116    Applied,
117    Rejected,
118    Allowed,
119    Denied,
120}
121
122/// Summary of a decision, kept from [`AuditLevel::Standard`] upward.
123#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
124pub struct DecisionSummary {
125    pub permission: String,
126    /// Resource path as text (`document:d1/project:p1`).
127    pub resource: String,
128    pub reason: Reason,
129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
130    pub matched: Vec<String>,
131    /// From `detailed` upward.
132    #[serde(default, skip_serializing_if = "Vec::is_empty")]
133    pub warnings: Vec<String>,
134}
135
136fn path_text(resource: &Resource) -> String {
137    resource
138        .path
139        .iter()
140        .map(ToString::to_string)
141        .collect::<Vec<_>>()
142        .join("/")
143}
144
145/// Summary of a grant, kept from [`AuditLevel::Standard`] upward.
146#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
147pub struct GrantSummary {
148    pub permission: String,
149    pub subject: SubjectMatcher,
150    pub target: TargetSelector,
151    pub effect: Effect,
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub scope: Option<Anchor>,
154    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
155    pub conditional: bool,
156}
157
158impl From<&Grant> for GrantSummary {
159    fn from(grant: &Grant) -> Self {
160        Self {
161            permission: grant.permission.clone(),
162            subject: grant.subject.clone(),
163            target: grant.target.clone(),
164            effect: grant.effect,
165            scope: grant.scope.clone(),
166            conditional: grant.condition.is_some(),
167        }
168    }
169}
170
171/// Recorded role assignment.
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173pub struct RoleChange {
174    /// Subject id, or `<kind>:<anonymous>` when it has no id.
175    pub subject: String,
176    pub role: String,
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub scope: Option<Anchor>,
179}
180
181impl RoleChange {
182    fn of(subject: &Subject, role: &RoleAssignment) -> Self {
183        Self {
184            subject: subject
185                .id
186                .clone()
187                .unwrap_or_else(|| format!("{}:<anonymous>", subject.kind)),
188            role: role.role.clone(),
189            scope: role.scope.clone(),
190        }
191    }
192}
193
194/// One record of the trail. The optional fields appear depending on the level.
195#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
196pub struct AuditRecord {
197    /// Milliseconds since the Unix epoch.
198    pub at: u64,
199    pub level: AuditLevel,
200    /// Actor id, or its kind when anonymous.
201    pub actor: String,
202    pub action: AuditAction,
203    /// Grant id, the tuple's `object#relation@subject`, or `role@subject` for a role change,
204    /// with the scope after the role when there is one (`role#scope@subject`).
205    pub object: String,
206    pub outcome: AuditOutcome,
207
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    pub grant: Option<GrantSummary>,
210    #[serde(default, skip_serializing_if = "Option::is_none")]
211    pub role: Option<RoleChange>,
212    /// Names of the invariants (standard) or `name: message` (detailed and above).
213    #[serde(default, skip_serializing_if = "Vec::is_empty")]
214    pub violations: Vec<String>,
215
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub decision: Option<DecisionSummary>,
218
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub full_grant: Option<Grant>,
221    /// Full resource of a decision, from `detailed` upward. With `actor_detail`, it is enough to
222    /// re-evaluate the decision against another policy.
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub resource: Option<Resource>,
225    /// Full trace of the decision, at `forensic`.
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub explanation: Option<Box<Explanation>>,
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub tuple: Option<Tuple>,
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub actor_detail: Option<Subject>,
232    #[serde(default, skip_serializing_if = "Attributes::is_empty")]
233    pub meta: Attributes,
234
235    /// Digest of the grant set before the change. For a role change, the digest of the subject's
236    /// roles.
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub before_digest: Option<String>,
239    /// Digest of the grant set after the change (equal to the previous one on a refusal). For a role
240    /// change, the digest of the subject's roles.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub after_digest: Option<String>,
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    pub prev_hash: Option<String>,
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub hash: Option<String>,
247}
248
249#[derive(Debug, thiserror::Error)]
250pub enum AuditError {
251    #[error("falha ao gravar auditoria: {0}")]
252    Sink(String),
253    #[error(transparent)]
254    Io(#[from] std::io::Error),
255    #[error(transparent)]
256    Json(#[from] serde_json::Error),
257}
258
259/// Destination of the records. An implementation that cannot write returns an error, and
260/// governance refuses the change: no record, no change.
261pub trait AuditSink: Send + Sync {
262    fn write(&self, record: &AuditRecord) -> Result<(), AuditError>;
263}
264
265impl<F: Fn(&AuditRecord) -> Result<(), AuditError> + Send + Sync> AuditSink for F {
266    fn write(&self, record: &AuditRecord) -> Result<(), AuditError> {
267        self(record)
268    }
269}
270
271fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
272    mutex.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
273}
274
275/// In-memory records, for tests and for callers who drain the trail themselves.
276#[derive(Debug, Default)]
277pub struct MemoryAuditLog {
278    records: Mutex<Vec<AuditRecord>>,
279}
280
281impl MemoryAuditLog {
282    pub fn new() -> Self {
283        Self::default()
284    }
285
286    pub fn records(&self) -> Vec<AuditRecord> {
287        lock(&self.records).clone()
288    }
289
290    pub fn drain(&self) -> Vec<AuditRecord> {
291        std::mem::take(&mut *lock(&self.records))
292    }
293}
294
295impl AuditSink for MemoryAuditLog {
296    fn write(&self, record: &AuditRecord) -> Result<(), AuditError> {
297        lock(&self.records).push(record.clone());
298        Ok(())
299    }
300}
301
302/// One JSON record per line on a `Write` (file, socket, stdout).
303pub struct JsonLinesAudit<W> {
304    out: Mutex<W>,
305}
306
307impl<W: Write + Send> JsonLinesAudit<W> {
308    pub fn new(out: W) -> Self {
309        Self { out: Mutex::new(out) }
310    }
311
312    pub fn into_inner(self) -> W {
313        self.out.into_inner().unwrap_or_else(|poisoned| poisoned.into_inner())
314    }
315}
316
317impl<W: Write + Send> AuditSink for JsonLinesAudit<W> {
318    fn write(&self, record: &AuditRecord) -> Result<(), AuditError> {
319        let mut line = serde_json::to_vec(record)?;
320        line.push(b'\n');
321        let mut out = lock(&self.out);
322        out.write_all(&line)?;
323        out.flush()?;
324        Ok(())
325    }
326}
327
328pub type Clock = Arc<dyn Fn() -> u64 + Send + Sync>;
329
330#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
331fn system_clock() -> u64 {
332    std::time::SystemTime::now()
333        .duration_since(std::time::UNIX_EPOCH)
334        .map(|d| d.as_millis() as u64)
335        .unwrap_or(0)
336}
337
338/// `wasm32-unknown-unknown` has no system clock; use [`Auditor::with_clock`].
339#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
340fn system_clock() -> u64 {
341    0
342}
343
344/// Builds the records at the configured level and hands them to the sink.
345pub struct Auditor {
346    level: AuditLevel,
347    sink: Arc<dyn AuditSink>,
348    clock: Clock,
349    last_hash: Mutex<Option<String>>,
350}
351
352impl fmt::Debug for Auditor {
353    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354        f.debug_struct("Auditor")
355            .field("level", &self.level)
356            .finish_non_exhaustive()
357    }
358}
359
360impl Auditor {
361    pub fn new(level: AuditLevel, sink: Arc<dyn AuditSink>) -> Self {
362        Self {
363            level,
364            sink,
365            clock: Arc::new(system_clock),
366            last_hash: Mutex::new(None),
367        }
368    }
369
370    pub fn with_clock(mut self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
371        self.clock = Arc::new(clock);
372        self
373    }
374
375    /// Resumes a forensic chain from the hash of the last record already written.
376    pub fn resume_chain(self, last_hash: impl Into<String>) -> Self {
377        *lock(&self.last_hash) = Some(last_hash.into());
378        self
379    }
380
381    pub fn level(&self) -> AuditLevel {
382        self.level
383    }
384
385    fn base(&self, actor: &Subject, action: AuditAction, object: String, outcome: AuditOutcome) -> AuditRecord {
386        AuditRecord {
387            at: (self.clock)(),
388            level: self.level,
389            actor: actor.id.clone().unwrap_or_else(|| actor.kind.clone()),
390            action,
391            object,
392            outcome,
393            grant: None,
394            role: None,
395            violations: Vec::new(),
396            decision: None,
397            full_grant: None,
398            resource: None,
399            explanation: None,
400            tuple: None,
401            actor_detail: None,
402            meta: Attributes::new(),
403            before_digest: None,
404            after_digest: None,
405            prev_hash: None,
406            hash: None,
407        }
408    }
409
410    /// Decides and records. At the `forensic` level it uses [`Engine::explain`] and keeps the trace; at
411    /// the other levels, [`Engine::decide`]. The decision is returned even if the record fails: the
412    /// caller chooses whether to deny access in that case.
413    pub fn decide(
414        &self,
415        engine: &Engine,
416        ctx: &Context<'_>,
417        request: &Request<'_>,
418        meta: &Attributes,
419    ) -> (Decision, Result<AuditRecord, AuditError>) {
420        if self.level >= AuditLevel::Forensic {
421            let explanation = engine.explain(ctx, request);
422            let record = self.explained(&explanation, meta);
423            (explanation.decision, record)
424        } else {
425            let decision = engine.decide(ctx, request);
426            let record = self.decision(request, &decision, meta);
427            (decision, record)
428        }
429    }
430
431    /// Records a decision that was already made. At `forensic`, prefer [`Auditor::explained`].
432    pub fn decision(
433        &self,
434        request: &Request<'_>,
435        decision: &Decision,
436        meta: &Attributes,
437    ) -> Result<AuditRecord, AuditError> {
438        self.emit(self.decision_record(request.subject, request.permission, request.resource, decision, meta))
439    }
440
441    /// Records a decision with the full trace.
442    pub fn explained(&self, explanation: &Explanation, meta: &Attributes) -> Result<AuditRecord, AuditError> {
443        let mut record = self.decision_record(
444            &explanation.subject,
445            &explanation.permission,
446            &explanation.resource,
447            &explanation.decision,
448            meta,
449        );
450        if self.level >= AuditLevel::Forensic {
451            record.explanation = Some(Box::new(explanation.clone()));
452        }
453        self.emit(record)
454    }
455
456    fn decision_record(
457        &self,
458        subject: &Subject,
459        permission: &str,
460        resource: &Resource,
461        decision: &Decision,
462        meta: &Attributes,
463    ) -> AuditRecord {
464        let outcome = if decision.is_allowed() {
465            AuditOutcome::Allowed
466        } else {
467            AuditOutcome::Denied
468        };
469        let path = path_text(resource);
470        let object = format!("{permission}@{path}");
471        let mut record = self.base(subject, AuditAction::Decision, object, outcome);
472        if self.level >= AuditLevel::Standard {
473            record.decision = Some(DecisionSummary {
474                permission: permission.to_string(),
475                resource: path,
476                reason: decision.reason.clone(),
477                matched: decision.matched.clone(),
478                warnings: if self.level >= AuditLevel::Detailed {
479                    decision.warnings.clone()
480                } else {
481                    Vec::new()
482                },
483            });
484        }
485        if self.level >= AuditLevel::Detailed {
486            record.resource = Some(resource.clone());
487        }
488        self.detail(&mut record, subject, meta);
489        record
490    }
491
492    fn detail(&self, record: &mut AuditRecord, actor: &Subject, meta: &Attributes) {
493        if self.level >= AuditLevel::Detailed {
494            record.actor_detail = Some(actor.clone());
495            record.meta = meta.clone();
496        }
497    }
498
499    /// Records a change decided by governance. A role change is emitted as
500    /// `role_assign`/`role_revoke`, like [`Auditor::role_change`], with the violations.
501    pub fn grant_mutation(
502        &self,
503        actor: &Subject,
504        mutation: &Mutation,
505        before: &[Grant],
506        result: &Result<Vec<Grant>, Vec<Violation>>,
507        meta: &Attributes,
508    ) -> Result<AuditRecord, AuditError> {
509        let (outcome, violations) = match result {
510            Ok(_) => (AuditOutcome::Applied, &[][..]),
511            Err(violations) => (AuditOutcome::Rejected, violations.as_slice()),
512        };
513        let (action, object, grant) = match mutation {
514            Mutation::Add(grant) => (AuditAction::GrantAdd, grant.id.clone(), Some(grant)),
515            Mutation::Remove { id } => (
516                AuditAction::GrantRemove,
517                id.clone(),
518                before.iter().find(|g| &g.id == id),
519            ),
520            Mutation::AssignRole { subject, role } | Mutation::RevokeRole { subject, role } => {
521                let assigned = matches!(mutation, Mutation::AssignRole { .. });
522                let change = RoleChange::of(subject, role);
523                let before = role_set_digest(&subject.roles);
524                let after = match result {
525                    Ok(_) => {
526                        let roles = mutation.subject_after().map(|s| s.roles);
527                        role_set_digest(&roles.unwrap_or_default())
528                    }
529                    Err(_) => before.clone(),
530                };
531                let digests = Some((before, after));
532                return self.role_record(actor, assigned, &change, outcome, violations, digests, meta);
533            }
534        };
535        let mut record = self.base(actor, action, object, outcome);
536        if self.level >= AuditLevel::Standard {
537            record.grant = grant.map(GrantSummary::from);
538            record.violations = self.violation_texts(violations);
539        }
540        if self.level >= AuditLevel::Detailed {
541            record.full_grant = grant.cloned();
542        }
543        self.detail(&mut record, actor, meta);
544        if self.level >= AuditLevel::Forensic {
545            record.before_digest = Some(grant_set_digest(before));
546            record.after_digest = Some(match result {
547                Ok(after) => grant_set_digest(after),
548                Err(_) => grant_set_digest(before),
549            });
550        }
551        self.emit(record)
552    }
553
554    /// Records the writing or removal of a ReBAC tuple.
555    pub fn tuple_change(
556        &self,
557        actor: &Subject,
558        added: bool,
559        tuple: &Tuple,
560        outcome: AuditOutcome,
561        meta: &Attributes,
562    ) -> Result<AuditRecord, AuditError> {
563        let action = if added {
564            AuditAction::TupleAdd
565        } else {
566            AuditAction::TupleRemove
567        };
568        let mut record = self.base(actor, action, tuple.to_string(), outcome);
569        if self.level >= AuditLevel::Detailed {
570            record.tuple = Some(tuple.clone());
571        }
572        self.detail(&mut record, actor, meta);
573        self.emit(record)
574    }
575
576    /// Records the assignment or revocation of a role.
577    pub fn role_change(
578        &self,
579        actor: &Subject,
580        assigned: bool,
581        change: &RoleChange,
582        outcome: AuditOutcome,
583        meta: &Attributes,
584    ) -> Result<AuditRecord, AuditError> {
585        self.role_record(actor, assigned, change, outcome, &[], None, meta)
586    }
587
588    #[allow(clippy::too_many_arguments)]
589    fn role_record(
590        &self,
591        actor: &Subject,
592        assigned: bool,
593        change: &RoleChange,
594        outcome: AuditOutcome,
595        violations: &[Violation],
596        digests: Option<(String, String)>,
597        meta: &Attributes,
598    ) -> Result<AuditRecord, AuditError> {
599        let action = if assigned {
600            AuditAction::RoleAssign
601        } else {
602            AuditAction::RoleRevoke
603        };
604        let object = match &change.scope {
605            Some(scope) => format!("{}#{scope}@{}", change.role, change.subject),
606            None => format!("{}@{}", change.role, change.subject),
607        };
608        let mut record = self.base(actor, action, object, outcome);
609        if self.level >= AuditLevel::Standard {
610            record.role = Some(change.clone());
611            record.violations = self.violation_texts(violations);
612        }
613        self.detail(&mut record, actor, meta);
614        if self.level >= AuditLevel::Forensic
615            && let Some((before, after)) = digests
616        {
617            record.before_digest = Some(before);
618            record.after_digest = Some(after);
619        }
620        self.emit(record)
621    }
622
623    /// Names of the invariants at `standard`; name and message from `detailed` upward.
624    fn violation_texts(&self, violations: &[Violation]) -> Vec<String> {
625        violations
626            .iter()
627            .map(|v| {
628                if self.level >= AuditLevel::Detailed {
629                    v.to_string()
630                } else {
631                    v.invariant.clone()
632                }
633            })
634            .collect()
635    }
636
637    fn emit(&self, mut record: AuditRecord) -> Result<AuditRecord, AuditError> {
638        if self.level < AuditLevel::Forensic {
639            self.sink.write(&record)?;
640            return Ok(record);
641        }
642        let mut last = lock(&self.last_hash);
643        record.prev_hash = last.clone();
644        record.hash = Some(record_hash(&record)?);
645        self.sink.write(&record)?;
646        *last = record.hash.clone();
647        Ok(record)
648    }
649}
650
651fn hex(bytes: &[u8]) -> String {
652    bytes.iter().map(|b| format!("{b:02x}")).collect()
653}
654
655/// SHA-256 digest of a grant set, independent of order.
656pub fn grant_set_digest(grants: &[Grant]) -> String {
657    let mut lines: Vec<String> = grants
658        .iter()
659        .map(|g| serde_json::to_string(g).unwrap_or_default())
660        .collect();
661    lines.sort();
662    let mut hasher = Sha256::new();
663    for line in lines {
664        hasher.update(line.as_bytes());
665        hasher.update(b"\n");
666    }
667    hex(&hasher.finalize())
668}
669
670/// SHA-256 digest of a subject's roles, independent of order.
671fn role_set_digest(roles: &[RoleAssignment]) -> String {
672    let mut lines: Vec<String> = roles
673        .iter()
674        .map(|r| serde_json::to_string(r).unwrap_or_default())
675        .collect();
676    lines.sort();
677    let mut hasher = Sha256::new();
678    for line in lines {
679        hasher.update(line.as_bytes());
680        hasher.update(b"\n");
681    }
682    hex(&hasher.finalize())
683}
684
685/// Hash of a record: SHA-256 of the JSON with `hash` empty and `prev_hash` filled in.
686pub fn record_hash(record: &AuditRecord) -> Result<String, AuditError> {
687    let mut unsigned = record.clone();
688    unsigned.hash = None;
689    Ok(hex(&Sha256::digest(serde_json::to_vec(&unsigned)?)))
690}
691
692#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
693pub enum ChainError {
694    #[error("registro {index}: hash não confere")]
695    Tampered { index: usize },
696    #[error("registro {index}: elo quebrado com o anterior")]
697    Broken { index: usize },
698    #[error("registro {index}: sem hash, não é nível forensic")]
699    Unchained { index: usize },
700}
701
702/// Checks a sequence of forensic records, in the order they were written.
703pub fn verify_chain(records: &[AuditRecord]) -> Result<(), ChainError> {
704    let mut previous: Option<&str> = None;
705    for (index, record) in records.iter().enumerate() {
706        let Some(hash) = record.hash.as_deref() else {
707            return Err(ChainError::Unchained { index });
708        };
709        if index > 0 && record.prev_hash.as_deref() != previous {
710            return Err(ChainError::Broken { index });
711        }
712        if record_hash(record).ok().as_deref() != Some(hash) {
713            return Err(ChainError::Tampered { index });
714        }
715        previous = Some(hash);
716    }
717    Ok(())
718}
719
720/// The reference record used in the storage estimates: the most common grant change (role with a
721/// scope and a short condition), made by an actor with two roles and three request metadata
722/// entries.
723pub fn reference_record(level: AuditLevel) -> AuditRecord {
724    use crate::condition::{Condition, Operand};
725
726    let actor = Subject::user("8f14e45f-ceea-467a-9575-0cbd1e4e7c21")
727        .with_role_in("admin", Anchor::new("org", "c9f0f895-fb98-4b91-8f1c-3b0b1e6f2a10"))
728        .with_role("auditor");
729    let grant = Grant::allow(
730        "0b8a1e2c-5f6d-4a3b-9c8d-7e6f5a4b3c2d",
731        SubjectMatcher::role("editor"),
732        "document.export",
733        TargetSelector::kind("project"),
734    )
735    .scoped(Anchor::new("org", "c9f0f895-fb98-4b91-8f1c-3b0b1e6f2a10"))
736    .when(Condition::all([
737        Condition::eq(Operand::attr("subject.plan"), Operand::lit("enterprise")),
738        Condition::lt(Operand::attr("env.hour"), Operand::lit(18)),
739    ]));
740    let before: Vec<Grant> = Vec::new();
741    let mut meta = Attributes::new();
742    meta.insert("ip".into(), "203.0.113.42".into());
743    meta.insert("request_id".into(), "req-01HZX3K9QW8E7R6T5Y4U3I2O1P".into());
744    meta.insert("reason".into(), "ticket SUP-1234".into());
745
746    let auditor = Auditor::new(level, Arc::new(MemoryAuditLog::new()))
747        .with_clock(|| 1_763_700_000_000)
748        .resume_chain("a".repeat(64));
749    let result = Ok(vec![grant.clone()]);
750    auditor
751        .grant_mutation(&actor, &Mutation::Add(grant), &before, &result, &meta)
752        .expect("registro de referência")
753}
754
755/// The reference decision record: a subject with two roles, a resource with three steps, three
756/// grants in the source (one with a two-clause condition, one for another permission, one out of
757/// scope) and three metadata entries.
758pub fn reference_decision_record(level: AuditLevel) -> AuditRecord {
759    use crate::catalog::{Catalog, PermissionDef};
760    use crate::condition::{Condition, Operand};
761
762    let org = "c9f0f895-fb98-4b91-8f1c-3b0b1e6f2a10";
763    let catalog = Catalog::builder()
764        .target_kinds(["project", "document"])
765        .broad_target("org")
766        .permission(PermissionDef::new("document.export").targets(["project", "document"]))
767        .permission(PermissionDef::new("document.edit").targets(["project", "document"]))
768        .build()
769        .expect("catálogo de referência");
770    let engine = Engine::builder(catalog).build().expect("motor de referência");
771    let grants = vec![
772        Grant::allow(
773            "0b8a1e2c-5f6d-4a3b-9c8d-7e6f5a4b3c2d",
774            SubjectMatcher::role("editor"),
775            "document.export",
776            TargetSelector::kind("project"),
777        )
778        .scoped(Anchor::new("org", org))
779        .when(Condition::all([
780            Condition::eq(Operand::attr("subject.plan"), Operand::lit("enterprise")),
781            Condition::lt(Operand::attr("env.hour"), Operand::lit(18)),
782        ])),
783        Grant::allow(
784            "1c9b2f3d-6a7e-4b4c-8d9e-8f7a6b5c4d3e",
785            SubjectMatcher::role("editor"),
786            "document.edit",
787            TargetSelector::kind("project"),
788        ),
789        Grant::deny(
790            "2d0c3a4e-7b8f-4c5d-9eaf-9a8b7c6d5e4f",
791            SubjectMatcher::Any,
792            "document.export",
793            TargetSelector::kind("org"),
794        )
795        .scoped(Anchor::new("org", "other")),
796    ];
797    let subject = Subject::user("8f14e45f-ceea-467a-9575-0cbd1e4e7c21")
798        .with_role_in("editor", Anchor::new("org", org))
799        .with_role("auditor")
800        .with_attr("plan", "enterprise");
801    let resource = Resource::new("document", "5e6f7a8b-9c0d-4e1f-a2b3-c4d5e6f7a8b9")
802        .within("project", "3a4b5c6d-7e8f-4a9b-8c0d-1e2f3a4b5c6d")
803        .within("org", org);
804    let mut env = Attributes::new();
805    env.insert("hour".into(), 10.into());
806    let mut meta = Attributes::new();
807    meta.insert("ip".into(), "203.0.113.42".into());
808    meta.insert("request_id".into(), "req-01HZX3K9QW8E7R6T5Y4U3I2O1P".into());
809    meta.insert("route".into(), "POST /documents/:id/export".into());
810
811    let auditor = Auditor::new(level, Arc::new(MemoryAuditLog::new()))
812        .with_clock(|| 1_763_700_000_000)
813        .resume_chain("a".repeat(64));
814    let ctx = Context::new(&grants).with_env(&env);
815    let request = Request::new(&subject, "document.export", &resource);
816    let (_, record) = auditor.decide(&engine, &ctx, &request, &meta);
817    record.expect("registro de referência")
818}
819
820#[cfg(test)]
821mod tests {
822    use super::*;
823    use crate::resource::ObjectRef;
824
825    #[test]
826    fn decision_records_by_level() {
827        let minimal = reference_decision_record(AuditLevel::Minimal);
828        assert_eq!(minimal.outcome, AuditOutcome::Allowed);
829        assert!(minimal.object.starts_with("document.export@document:"));
830        assert!(minimal.decision.is_none());
831        let standard = reference_decision_record(AuditLevel::Standard);
832        assert_eq!(standard.decision.as_ref().unwrap().matched.len(), 1);
833        let detailed = reference_decision_record(AuditLevel::Detailed);
834        assert!(detailed.resource.is_some() && detailed.actor_detail.is_some());
835        let forensic = reference_decision_record(AuditLevel::Forensic);
836        let explanation = forensic.explanation.as_ref().unwrap();
837        assert_eq!(explanation.grants.len(), 3);
838        assert!(forensic.hash.is_some());
839        let back: AuditRecord = serde_json::from_str(&serde_json::to_string(&forensic).unwrap()).unwrap();
840        assert_eq!(back, forensic);
841    }
842
843    #[test]
844    fn decision_estimates_match_reference_records() {
845        let report: Vec<(AuditLevel, u64, u64)> = AuditLevel::ALL
846            .into_iter()
847            .map(|level| {
848                let actual = serde_json::to_vec(&reference_decision_record(level)).unwrap().len() as u64;
849                (level, actual, level.typical_decision_bytes())
850            })
851            .collect();
852        let drifted = report
853            .iter()
854            .any(|(_, actual, typical)| actual.abs_diff(*typical) as f64 / *typical as f64 > 0.10);
855        assert!(!drifted, "medido x documentado: {report:?}");
856    }
857
858    fn actor() -> Subject {
859        Subject::user("alice").with_role("admin")
860    }
861
862    fn grant(id: &str) -> Grant {
863        Grant::allow(
864            id,
865            SubjectMatcher::role("editor"),
866            "doc.edit",
867            TargetSelector::kind("doc"),
868        )
869    }
870
871    #[test]
872    fn levels_add_fields_progressively() {
873        let minimal = reference_record(AuditLevel::Minimal);
874        assert!(minimal.grant.is_none() && minimal.full_grant.is_none() && minimal.hash.is_none());
875        let standard = reference_record(AuditLevel::Standard);
876        assert!(standard.grant.as_ref().is_some_and(|g| g.conditional));
877        assert!(standard.full_grant.is_none() && standard.meta.is_empty());
878        let detailed = reference_record(AuditLevel::Detailed);
879        assert!(detailed.full_grant.is_some() && detailed.actor_detail.is_some());
880        assert_eq!(detailed.meta.len(), 3);
881        assert!(detailed.hash.is_none());
882        let forensic = reference_record(AuditLevel::Forensic);
883        assert!(forensic.hash.is_some() && forensic.before_digest.is_some());
884    }
885
886    #[test]
887    fn estimates_match_reference_records() {
888        for level in AuditLevel::ALL {
889            let actual = serde_json::to_vec(&reference_record(level)).unwrap().len() as u64;
890            let typical = level.typical_record_bytes();
891            let drift = actual.abs_diff(typical) as f64 / typical as f64;
892            assert!(drift <= 0.10, "{level}: medido {actual} B, documentado {typical} B");
893        }
894        assert!(AuditLevel::Minimal.estimate_bytes(1_000_000) < AuditLevel::Forensic.estimate_bytes(1_000_000));
895    }
896
897    #[test]
898    fn rejected_mutation_keeps_violations() {
899        let log = Arc::new(MemoryAuditLog::new());
900        let auditor = Auditor::new(AuditLevel::Standard, log.clone());
901        let result = Err(vec![Violation::new("forbid", "não pode")]);
902        auditor
903            .grant_mutation(&actor(), &Mutation::Add(grant("g1")), &[], &result, &Attributes::new())
904            .unwrap();
905        let records = log.records();
906        assert_eq!(records[0].outcome, AuditOutcome::Rejected);
907        assert_eq!(records[0].violations, ["forbid"]);
908    }
909
910    #[test]
911    fn forensic_chain_detects_tampering() {
912        let log = Arc::new(MemoryAuditLog::new());
913        let auditor = Auditor::new(AuditLevel::Forensic, log.clone()).with_clock(|| 1);
914        let mut current = Vec::new();
915        for id in ["g1", "g2", "g3"] {
916            let next = {
917                let mut v = current.clone();
918                v.push(grant(id));
919                v
920            };
921            let result = Ok(next.clone());
922            auditor
923                .grant_mutation(
924                    &actor(),
925                    &Mutation::Add(grant(id)),
926                    &current,
927                    &result,
928                    &Attributes::new(),
929                )
930                .unwrap();
931            current = next;
932        }
933        let tuple = Tuple::new(ObjectRef::new("doc", "d1"), "viewer", ObjectRef::new("user", "bob"));
934        auditor
935            .tuple_change(&actor(), true, &tuple, AuditOutcome::Applied, &Attributes::new())
936            .unwrap();
937        let records = log.records();
938        assert_eq!(verify_chain(&records), Ok(()));
939        assert_eq!(records[0].after_digest, records[1].before_digest);
940
941        let mut edited = records.clone();
942        edited[1].object = "g9".into();
943        assert_eq!(verify_chain(&edited), Err(ChainError::Tampered { index: 1 }));
944
945        let mut removed = records.clone();
946        removed.remove(1);
947        assert_eq!(verify_chain(&removed), Err(ChainError::Broken { index: 1 }));
948    }
949
950    #[test]
951    fn json_lines_sink_writes_one_record_per_line() {
952        let sink = Arc::new(JsonLinesAudit::new(Vec::new()));
953        let auditor = Auditor::new(AuditLevel::Minimal, sink.clone());
954        let change = RoleChange {
955            subject: "bob".into(),
956            role: "editor".into(),
957            scope: None,
958        };
959        auditor
960            .role_change(&actor(), true, &change, AuditOutcome::Applied, &Attributes::new())
961            .unwrap();
962        auditor
963            .role_change(&actor(), false, &change, AuditOutcome::Applied, &Attributes::new())
964            .unwrap();
965        drop(auditor);
966        let sink = Arc::try_unwrap(sink).ok().unwrap();
967        let text = String::from_utf8(sink.into_inner()).unwrap();
968        let lines: Vec<AuditRecord> = text.lines().map(|l| serde_json::from_str(l).unwrap()).collect();
969        assert_eq!(lines.len(), 2);
970        assert_eq!(lines[1].action, AuditAction::RoleRevoke);
971        assert_eq!(lines[0].object, "editor@bob");
972    }
973}