Skip to main content

ash_jsonapi/
audit.rs

1//! An audit trail, as a [`Hook`].
2//!
3//! A REST service that does not record its authorization decisions is a
4//! liability: when someone asks who deleted a row, "the logs" has to be an
5//! answer rather than a shrug. This module makes that answer a two-line
6//! registration.
7//!
8//! It is deliberately *not* a second interception mechanism. An audit record
9//! is exactly an [`after`](crate::hook::Hook::after) hook — it observes an
10//! operation and its outcome, and cannot change either — so it is built on
11//! the same [`Hooks`](crate::hook::Hooks) every other cross-cutting concern
12//! uses. Metrics and tracing will be the same shape.
13//!
14//! ```ignore
15//! use ash_jsonapi::audit::Audit;
16//! use ash_jsonapi::crud::Validators;
17//! use ash_jsonapi::hook::Hooks;
18//!
19//! let hooks = Hooks::new().with(Audit::new(logger));
20//!
21//! impl Validators for App {
22//!     fn hooks(&self) -> Option<&Hooks> {
23//!         Some(&self.hooks)
24//!     }
25//! }
26//! ```
27//!
28//! # What is recorded
29//!
30//! One event per operation, carrying the correlation id, the principal, the
31//! resource and operation, and the outcome. The record is written *after*
32//! the operation, so it states what actually happened rather than what was
33//! attempted.
34//!
35//! Attribute values are never recorded. An audit trail says that
36//! `alice@example.com` updated `todo/t_1` and that it succeeded; what she
37//! changed it to is the row's business, and a log that copies request bodies
38//! is a second place for personal data to leak from.
39
40use std::sync::Arc;
41
42use ash_log::{AuditEvent, AuditEventType, AuditResult, AuditSeverity, Logger};
43
44use crate::context::Context;
45use crate::hook::{Event, Hook, Outcome};
46
47/// Records every operation to an `ash-log` [`Logger`].
48///
49/// Register it on your [`Hooks`](crate::hook::Hooks); see the module docs.
50pub struct Audit {
51    logger: Arc<Logger>,
52}
53
54impl Audit {
55    /// Record to `logger`.
56    pub fn new(logger: Arc<Logger>) -> Self {
57        Self { logger }
58    }
59}
60
61impl Hook for Audit {
62    fn after(&self, event: &Event<'_>, outcome: &Outcome, ctx: &Context) {
63        // `method` is the operation as a client would name it — `read todo`,
64        // `delete todo/t_1` — so a record is legible without knowing this
65        // crate's internals.
66        let method = match event.id {
67            Some(id) => format!("{} {}/{}", event.operation.as_str(), event.resource, id),
68            None => format!("{} {}", event.operation.as_str(), event.resource),
69        };
70
71        let mut builder = AuditEvent::builder()
72            .event_type(event_type(outcome))
73            .result(result(outcome))
74            .severity(severity(event, outcome))
75            .correlation_id(ctx.correlation_id())
76            .method(method);
77
78        // Absent until authentication has run: an unauthenticated request is
79        // recorded as one rather than as an empty principal.
80        if let Some(principal) = ctx.principal() {
81            builder = builder.principal(principal);
82        }
83
84        self.logger.log(builder.build());
85    }
86}
87
88/// How to classify the record.
89///
90/// A `403` is an authorization decision, which is the event type a compliance
91/// review actually searches for; everything else is an invocation or an
92/// error.
93fn event_type(outcome: &Outcome) -> AuditEventType {
94    match outcome {
95        Outcome::Succeeded { .. } => AuditEventType::MethodInvocation,
96        Outcome::Failed { status: 401 | 403 } => AuditEventType::AuthorizationCheck,
97        Outcome::Failed { .. } => AuditEventType::ErrorOccurred,
98    }
99}
100
101/// Denied, failed, or succeeded — the three a reviewer cares to distinguish.
102fn result(outcome: &Outcome) -> AuditResult {
103    match outcome {
104        Outcome::Succeeded { .. } => AuditResult::Success,
105        Outcome::Failed { status: 401 | 403 } => AuditResult::Denied,
106        Outcome::Failed { .. } => AuditResult::Failure,
107    }
108}
109
110/// How loud the record is.
111///
112/// A denied *write* is the one worth waking someone for: a denied read is
113/// often just a client probing, but a denied delete is someone trying to
114/// remove data they do not own. A server error is likewise a warning, since
115/// it is the service's own fault.
116fn severity(event: &Event<'_>, outcome: &Outcome) -> AuditSeverity {
117    match outcome {
118        Outcome::Succeeded { .. } => AuditSeverity::Info,
119        Outcome::Failed { status: 401 | 403 } if event.operation.is_write() => {
120            AuditSeverity::Warning
121        }
122        Outcome::Failed { status } if *status >= 500 => AuditSeverity::Warning,
123        Outcome::Failed { .. } => AuditSeverity::Info,
124    }
125}