Skip to main content

plexus_auth_core/
audit.rs

1//! `AuditRecord`, `AuditSink`, and the default `TracingAuditSink` — the
2//! audit primitive per AUTHZ-PRIVACY-1.
3//!
4//! AUTHZ default-deny dispatch (AUTHZ-CORE-5) must write one audit record per
5//! scope check (allow or deny) before the dispatch responds. The no-
6//! enumeration error policy (AUTHZ-PRIVACY-4) depends on this primitive:
7//! the wire response is generic per AUTHZ-S01-output §9; the **real** reason
8//! for a deny lives in the audit record.
9//!
10//! # Module surface
11//!
12//! - [`AuditRecord`] — the record shape (per AUTHZ-S01-output §1 + §8, with
13//!   AUTHZ-0 ratification revisions §2 and AUTHLANG-S01-output §4 fields).
14//! - [`AuditRecordKind`] — discriminant: `ScopeCheck` (default) or
15//!   `ForwardPolicyApplied` (AUTHLANG-3 writes this kind).
16//! - [`AuditDecision`] — `Allow` or `Deny { reason }`.
17//! - [`AuditDenyReason`] — the layered-denial detail captured per AUTHZ-0.
18//! - [`AuditSink`] — async trait the framework awaits to persist a record.
19//! - [`TracingAuditSink`] — default sink, emits `tracing::info!` to the
20//!   `plexus::audit` target. Free observability for every deployment.
21//! - [`ScopeCheck`] / [`ForwardPolicyApplied`] — empty marker types
22//!   matching the [`AuditRecordKind`] variants (introduced per the ticket's
23//!   `introduces:` frontmatter so the variant names have type-level
24//!   reachability without conflating with the discriminant).
25//! - [`SensitiveField`] — registry marker introduced for AUTHZ-PRIVACY-2 to
26//!   populate (`#[sensitive]` field tagging). Today's redaction is a stub:
27//!   no fields are redacted because the registry is empty.
28//! - [`UserId`], [`SessionId`], [`RoleName`] — strong-typed newtype primitives
29//!   for the principal-chain capture. See module-level run-note below.
30//!
31//! # `UserId`, `SessionId`, `RoleName` ownership
32//!
33//! AUTHZ-PRIVACY-1's `imports:` frontmatter lists these three types, but no
34//! upstream ticket actually owns them — the spec author flagged this for
35//! resolution before launch. Per the resolution path in the agent prompt and
36//! the strong-typing skill, this ticket **owns** them. They are introduced
37//! here as transparent `String` newtypes alongside the rest of the audit
38//! primitive. See `plans/AUTHZ/AUTHZ-PRIVACY-1-RUN-NOTES.md` for the
39//! expansion of the `introduces:` list.
40//!
41//! # Sealing posture
42//!
43//! Unlike `Principal` / `VerifiedUser` / `Credential`, the audit primitive is
44//! NOT sealed. The framework constructs `AuditRecord` values internally, but
45//! tests, sink reference implementations, and downstream observers all need
46//! to construct them — there is no safety property that demands a sealed
47//! constructor. `AuditRecord` derives `Debug, Clone, Serialize, Deserialize`
48//! per acceptance criterion 1.
49//!
50//! # Sink failure
51//!
52//! Per AUTHZ-S01-output §8 default policy: a sink that returns / panics-as-
53//! error from `write` is logged at `tracing::error` and dispatch continues.
54//! The audit-vs-availability tradeoff defaults to availability; critical-
55//! sink semantics are deferred (AUTHZ-S01-output §8 open question; future
56//! ticket).
57
58use std::net::IpAddr;
59use std::sync::Arc;
60
61use async_trait::async_trait;
62use chrono::{DateTime, Utc};
63use serde::{Deserialize, Serialize};
64use uuid::Uuid;
65
66use crate::capabilities::MethodPath;
67use crate::credential::{Origin, Scope};
68use crate::forward::{ForwardDerivation, ForwardPolicyName};
69use crate::principal::{Principal, ServiceIdentity};
70use crate::verified_user::VerifiedUser;
71
72// ---------------------------------------------------------------------------
73// Sealed-type round-trip for the `invocation_chain`.
74//
75// `Principal` and `VerifiedUser` deliberately do NOT implement `Deserialize`
76// — per AUTHZ-0's sealing principle "no leaky Deserialize: not derived; raw
77// JSON cannot fabricate a sealed value". That sealing is exactly the
78// property that makes the principal-chain forensically meaningful.
79//
80// But the audit record must round-trip (acceptance criterion 10). The
81// resolution: the deserialize path lives **inside `plexus-auth-core`**, so
82// it can legitimately route through the crate-private constructors
83// (`anonymous_sealed`, `user_sealed`, `service_sealed`, `new_sealed`). The
84// external invariant (no third-crate fabrication of a Principal) is
85// preserved: only the audit-record deserializer can mint a `Principal` from
86// JSON, and only callers that already hold an `AuditRecord` value benefit.
87//
88// The wire shape matches what `Principal`'s derived `Serialize` emits — a
89// JSON enum representation:
90//   - `"Anonymous"`
91//   - `{"User": {"user_id": "...", "issuer": "...", "issued_at": N,
92//                "expires_at": N}}`
93//   - `{"Service": {"service_id": "..."}}`
94//
95// We mirror that with private `PrincipalWire` / `VerifiedUserWire` /
96// `ServiceIdentityWire` types and convert via the crate-private mint paths.
97// ---------------------------------------------------------------------------
98
99#[derive(Deserialize)]
100struct VerifiedUserWire {
101    user_id: String,
102    issuer: String,
103    issued_at: i64,
104    expires_at: i64,
105    /// UT-1: the verified `org_id` tenant identity rides the wire mirror
106    /// so audit round-trips preserve it. `default` keeps pre-UT-1 audit
107    /// records (which lack the field) deserializable.
108    #[serde(default)]
109    tenant: Option<crate::tenant::types::TenantId>,
110}
111
112#[derive(Deserialize)]
113struct ServiceIdentityWire {
114    service_id: String,
115}
116
117#[derive(Deserialize)]
118enum PrincipalWire {
119    User(VerifiedUserWire),
120    Service(ServiceIdentityWire),
121    Anonymous,
122}
123
124impl From<PrincipalWire> for Principal {
125    fn from(w: PrincipalWire) -> Self {
126        match w {
127            PrincipalWire::Anonymous => Principal::anonymous_sealed(),
128            PrincipalWire::User(u) => Principal::user_sealed(VerifiedUser::new_sealed(
129                u.user_id,
130                u.issuer,
131                u.issued_at,
132                u.expires_at,
133                u.tenant,
134            )),
135            PrincipalWire::Service(s) => {
136                Principal::service_sealed(ServiceIdentity::new_sealed(s.service_id))
137            }
138        }
139    }
140}
141
142/// `#[serde(deserialize_with = ...)]` shim that reads the principal chain
143/// via the crate-private mint paths.
144fn deserialize_invocation_chain<'de, D>(deserializer: D) -> Result<Vec<Principal>, D::Error>
145where
146    D: serde::Deserializer<'de>,
147{
148    let wire: Vec<PrincipalWire> = Vec::deserialize(deserializer)?;
149    Ok(wire.into_iter().map(Principal::from).collect())
150}
151
152/// `#[serde(default = ...)]` shim that produces an empty chain.
153fn empty_invocation_chain() -> Vec<Principal> {
154    Vec::new()
155}
156
157// ---------------------------------------------------------------------------
158// `ForwardPolicyName` wire shim.
159//
160// `ForwardPolicyName` wraps `&'static str` (per AUTHLANG-2's design — policy
161// names are compile-time constants). Its derived `Deserialize` impl
162// transitively requires `'de: 'static`, which would prevent deserializing
163// `AuditRecord` from a non-`'static` JSON input.
164//
165// We shim the field via a `String` wire-form, then intern the value into a
166// `&'static str` (via `Box::leak`) so the resulting `ForwardPolicyName`
167// honors the type's invariant. Names are typically one of the three v1
168// constants (`identity_only`, `pass_through`, `anonymous`) — we match those
169// first to avoid leaking memory on the common path. Unknown names leak one
170// `String` per fresh policy name, which is acceptable: the count is bounded
171// by the number of distinct policies a deployment defines, not by the
172// number of records deserialized.
173// ---------------------------------------------------------------------------
174
175fn deserialize_policy_name<'de, D>(
176    deserializer: D,
177) -> Result<Option<ForwardPolicyName>, D::Error>
178where
179    D: serde::Deserializer<'de>,
180{
181    let opt: Option<String> = Option::deserialize(deserializer)?;
182    Ok(opt.map(|s| {
183        // Fast-path the v1 constants to avoid leaking.
184        match s.as_str() {
185            "identity_only" => crate::forward::IDENTITY_ONLY_NAME,
186            "pass_through" => crate::forward::PASS_THROUGH_NAME,
187            "anonymous" => crate::forward::ANONYMOUS_NAME,
188            _ => {
189                // Slow path: intern the string. Bounded by the number of
190                // distinct custom policy names in the deployment.
191                let leaked: &'static str = Box::leak(s.into_boxed_str());
192                ForwardPolicyName::new(leaked)
193            }
194        }
195    }))
196}
197
198// ---------------------------------------------------------------------------
199// Strong-typed newtypes: UserId, SessionId, RoleName.
200//
201// Per the strong-typing skill: a bare `String` in this position would conflate
202// three semantically distinct concepts (originator identity, session
203// identity, role name) and let the compiler accept a misuse. These newtypes
204// make swap-arguments mistakes a compile error.
205//
206// Transparent serde is intentional: the wire shape is "just a string", and
207// AUTHZ-S01-output §1 pins the field names but not the encoding wrapper. The
208// type-level discipline is for Rust callers; the JSON encoding is identical
209// to what a bare String would produce.
210// ---------------------------------------------------------------------------
211
212/// IdP-verified originator identifier — the `sub` claim or equivalent.
213///
214/// Per AUTHZ-0 ratification (AUTHZ-S01-output §"AUTHZ-0 ratification
215/// revisions" §2): `originator` is the IdP-verified user, NOT a bare string
216/// or whatever-the-caller-said. The newtype prevents a downstream from
217/// accidentally swapping `UserId` and `SessionId` (both would be `String`
218/// otherwise — same shape, very different meaning).
219#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
220#[serde(transparent)]
221pub struct UserId(String);
222
223impl UserId {
224    /// Wrap a string as a typed `UserId`.
225    pub fn new(s: impl Into<String>) -> Self {
226        Self(s.into())
227    }
228
229    /// Borrow the underlying string.
230    pub fn as_str(&self) -> &str {
231        &self.0
232    }
233
234    /// Consume into the underlying string.
235    pub fn into_string(self) -> String {
236        self.0
237    }
238}
239
240impl std::fmt::Display for UserId {
241    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242        f.write_str(&self.0)
243    }
244}
245
246/// IdP-issued session identifier — the `sid` claim or equivalent.
247///
248/// Per AUTHZ-0 ratification: `session_id` is typed, not bare. Newtype
249/// discipline prevents confusion with `UserId`.
250#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
251#[serde(transparent)]
252pub struct SessionId(String);
253
254impl SessionId {
255    /// Wrap a string as a typed `SessionId`.
256    pub fn new(s: impl Into<String>) -> Self {
257        Self(s.into())
258    }
259
260    /// Borrow the underlying string.
261    pub fn as_str(&self) -> &str {
262        &self.0
263    }
264
265    /// Consume into the underlying string.
266    pub fn into_string(self) -> String {
267        self.0
268    }
269}
270
271impl std::fmt::Display for SessionId {
272    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
273        f.write_str(&self.0)
274    }
275}
276
277/// IdP-issued role name within a realm/tenant.
278///
279/// AUTHZ-CORE-3/4 will own this type in the long run; this ticket introduces
280/// it here for the audit record's `roles: Vec<RoleName>` field. When the
281/// canonical type lands in `plexus-auth-core::capabilities`, this re-exports
282/// from there. The strong-typing discipline survives the move.
283#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
284#[serde(transparent)]
285pub struct RoleName(String);
286
287impl RoleName {
288    /// Wrap a string as a typed `RoleName`.
289    pub fn new(s: impl Into<String>) -> Self {
290        Self(s.into())
291    }
292
293    /// Borrow the underlying string.
294    pub fn as_str(&self) -> &str {
295        &self.0
296    }
297
298    /// Consume into the underlying string.
299    pub fn into_string(self) -> String {
300        self.0
301    }
302}
303
304impl std::fmt::Display for RoleName {
305    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
306        f.write_str(&self.0)
307    }
308}
309
310// ---------------------------------------------------------------------------
311// AuditRecordKind discriminant.
312// ---------------------------------------------------------------------------
313
314/// Discriminates the two flavors of audit record this ticket lands.
315///
316/// `ScopeCheck` is the default — written by AUTHZ-CORE-5 default-deny
317/// dispatch. `ForwardPolicyApplied` is what AUTHLANG-3 writes when a
318/// forwarding policy runs at a `route_to_child` edge.
319///
320/// Per AUTHLANG-S01-output §4 Tier-B resolution: the variant is **additive**
321/// with serde-default `ScopeCheck` so AUTHZ-side call sites that omit the
322/// `kind` field continue to deserialize as `ScopeCheck` records.
323#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
324#[serde(rename_all = "snake_case")]
325pub enum AuditRecordKind {
326    /// A scope-check decision at default-deny dispatch (AUTHZ-CORE-5).
327    #[default]
328    ScopeCheck,
329    /// A forwarding policy applied at a route-to-child edge (AUTHLANG-3).
330    ForwardPolicyApplied,
331}
332
333/// Marker type for the `ScopeCheck` audit-record kind.
334///
335/// Introduced per the ticket's `introduces:` frontmatter so the variant name
336/// has a type-level identity in addition to the [`AuditRecordKind`]
337/// discriminant. The marker is empty and zero-cost; callers that statically
338/// know they're writing a scope-check record can use it to make that intent
339/// readable at the call site:
340///
341/// ```rust,ignore
342/// let kind = ScopeCheck.into();   // AuditRecordKind::ScopeCheck
343/// ```
344#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
345pub struct ScopeCheck;
346
347impl From<ScopeCheck> for AuditRecordKind {
348    fn from(_: ScopeCheck) -> Self {
349        AuditRecordKind::ScopeCheck
350    }
351}
352
353/// Marker type for the `ForwardPolicyApplied` audit-record kind.
354///
355/// See [`ScopeCheck`] for the rationale. AUTHLANG-3 uses this marker at the
356/// call site that builds a forward-policy record:
357///
358/// ```rust,ignore
359/// let kind = ForwardPolicyApplied.into();
360/// ```
361#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
362pub struct ForwardPolicyApplied;
363
364impl From<ForwardPolicyApplied> for AuditRecordKind {
365    fn from(_: ForwardPolicyApplied) -> Self {
366        AuditRecordKind::ForwardPolicyApplied
367    }
368}
369
370// ---------------------------------------------------------------------------
371// AuditDecision and AuditDenyReason.
372// ---------------------------------------------------------------------------
373
374/// The decision recorded by a scope check.
375///
376/// Per AUTHZ-S01-output §1: `Allow` is the affirmative; `Deny { reason }`
377/// carries the layered-denial detail that the wire response does NOT
378/// surface (per AUTHZ-PRIVACY-4's no-enumeration policy — the wire stays
379/// generic; the audit log carries the truth).
380#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
381#[serde(tag = "decision", rename_all = "snake_case")]
382pub enum AuditDecision {
383    /// The check passed; dispatch proceeded.
384    Allow,
385    /// The check failed; dispatch responded with the generic deny.
386    Deny {
387        /// The layered-denial detail.
388        reason: AuditDenyReason,
389    },
390}
391
392/// The per-layer reason a deny occurred.
393///
394/// Captures AUTHZ-0's layered-denial model (per AUTHZ-S01-output §1): the
395/// audit record names *which* layer rejected the call so operators can
396/// reconstruct the chain after the fact. The wire response does NOT carry
397/// this discriminator (AUTHZ-PRIVACY-4); it is server-side only.
398#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
399#[serde(rename_all = "snake_case")]
400pub enum AuditDenyReason {
401    /// No credential / anonymous caller hit a non-public method.
402    Unauthenticated,
403    /// Credential present but invalid (expired token, unknown sid, etc.).
404    InvalidSession,
405    /// Authenticated, but the method's scope is not in the caller's set.
406    MissingScope,
407    /// Method exists but the perimeter rejected the call (`#[plexus::method(deny)]`
408    /// or similar policy rejection).
409    NotAccepted,
410    /// Tenant resolved, but does not match the data the call references.
411    TenantBoundary,
412    /// Rate-limit policy fired.
413    RateLimited,
414    /// Catch-all for layered impls that have not yet earned a dedicated
415    /// variant. Use sparingly; the wire still goes out generic, but the
416    /// audit log loses fidelity.
417    Other,
418}
419
420// ---------------------------------------------------------------------------
421// SensitiveField registry stub (AUTHZ-PRIVACY-2 will populate).
422// ---------------------------------------------------------------------------
423
424/// Tags a parameter or field as containing sensitive material that audit
425/// payloads must redact.
426///
427/// AUTHZ-PRIVACY-2 introduces the `#[sensitive]` attribute and the registry
428/// that populates this marker. AUTHZ-PRIVACY-1 lands the type so consumer
429/// tickets and tests can wire against a stable surface — today the registry
430/// is empty, so no redaction occurs; the type is reserved.
431///
432/// When the registry is populated (PRIVACY-2 / -5), serializing an
433/// `AuditRecord` will replace tagged fields with the literal string
434/// `"<redacted>"`. The redaction path is consumer-driven (the audit-payload
435/// serializer consults the registry); this ticket does not gate any field
436/// of `AuditRecord` itself behind the marker — the record is the carrier,
437/// not the payload-bearer.
438#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
439#[serde(transparent)]
440pub struct SensitiveField(String);
441
442impl SensitiveField {
443    /// Tag a field-or-parameter path as sensitive.
444    pub fn new(path: impl Into<String>) -> Self {
445        Self(path.into())
446    }
447
448    /// Borrow the underlying path.
449    pub fn as_str(&self) -> &str {
450        &self.0
451    }
452}
453
454// ---------------------------------------------------------------------------
455// AuditRecord — the wire shape.
456// ---------------------------------------------------------------------------
457
458/// One audit observation: a scope check or a forward-policy application.
459///
460/// Shape is pinned by:
461///
462/// - **AUTHZ-S01-output §1**: base fields (`timestamp`, `roles`, `method`,
463///   `scope_required`, `decision`, `latency_us`, `origin`, `client_ip`,
464///   `correlation_id`).
465/// - **AUTHZ-S01-output §"AUTHZ-0 ratification revisions" §2**: typed
466///   `originator: Option<UserId>`, `session_id: Option<SessionId>`, and the
467///   forensic `invocation_chain: Vec<Principal>` for confused-deputy
468///   reconstruction.
469/// - **AUTHLANG-S01-output §4**: the `kind` discriminant (default
470///   `ScopeCheck` for serde) plus three optional fields populated only by
471///   `ForwardPolicyApplied` records: `policy_name`, `derivation`, `caller_ns`.
472///
473/// # Defaults
474///
475/// `kind` defaults to `AuditRecordKind::ScopeCheck` when omitted from a
476/// deserialize payload — existing AUTHZ-side producers don't need to set it.
477/// `policy_name`, `derivation`, `caller_ns` default to `None` — they are
478/// populated only by AUTHLANG-3's forward-policy producer.
479///
480/// # Sealing
481///
482/// Not sealed. The record is observational; constructibility is the point.
483/// See module-level docs.
484#[derive(Debug, Clone, Serialize, Deserialize)]
485pub struct AuditRecord {
486    /// When the check ran (UTC).
487    pub timestamp: DateTime<Utc>,
488
489    /// Which kind of record this is — drives field-presence expectations.
490    /// Defaults to `ScopeCheck` for legacy / AUTHZ-side producers that omit
491    /// the field on deserialize.
492    #[serde(default)]
493    pub kind: AuditRecordKind,
494
495    /// IdP-verified originator (the `sub` claim). `None` for anonymous /
496    /// unauthenticated checks.
497    #[serde(default, skip_serializing_if = "Option::is_none")]
498    pub originator: Option<UserId>,
499
500    /// IdP-issued session ID. `None` for anonymous / sessionless checks.
501    #[serde(default, skip_serializing_if = "Option::is_none")]
502    pub session_id: Option<SessionId>,
503
504    /// The chain of immediate-callers leading to this dispatch. Empty for a
505    /// direct (originator-to-backend) call. Forensic reconstruction of
506    /// confused-deputy escalations reads this field.
507    ///
508    /// Deserialize routes via the crate-private mint paths
509    /// (`Principal::*_sealed`) — see the module-level comment on the
510    /// `PrincipalWire` types. The wire shape matches `Principal`'s derived
511    /// `Serialize`.
512    #[serde(
513        default = "empty_invocation_chain",
514        deserialize_with = "deserialize_invocation_chain"
515    )]
516    pub invocation_chain: Vec<Principal>,
517
518    /// The roles the principal carried at decision time.
519    #[serde(default)]
520    pub roles: Vec<RoleName>,
521
522    /// The method being invoked at decision time.
523    pub method: MethodPath,
524
525    /// The scope set required by `method`. Empty if no scope is gated.
526    #[serde(default)]
527    pub scope_required: Vec<Scope>,
528
529    /// `Allow` or `Deny { reason }`.
530    pub decision: AuditDecision,
531
532    /// Dispatch latency in microseconds.
533    pub latency_us: u64,
534
535    /// The backend Origin (URL-shaped, per CLIENTS-S01).
536    #[serde(default, skip_serializing_if = "Option::is_none")]
537    pub origin: Option<Origin>,
538
539    /// Network-layer source IP, when knowable.
540    #[serde(default, skip_serializing_if = "Option::is_none")]
541    pub client_ip: Option<IpAddr>,
542
543    /// Per-call correlation ID; ties this record to traces and metrics.
544    pub correlation_id: Uuid,
545
546    /// `ForwardPolicyApplied` only: name of the policy that ran.
547    ///
548    /// `ForwardPolicyName` wraps `&'static str` per AUTHLANG-2; the
549    /// deserializer interns the JSON value into a `'static` slot — see the
550    /// module-level `deserialize_policy_name` doc.
551    #[serde(
552        default,
553        skip_serializing_if = "Option::is_none",
554        deserialize_with = "deserialize_policy_name"
555    )]
556    pub policy_name: Option<ForwardPolicyName>,
557
558    /// `ForwardPolicyApplied` only: the derivation the policy returned.
559    #[serde(default, skip_serializing_if = "Option::is_none")]
560    pub derivation: Option<ForwardDerivation>,
561
562    /// `ForwardPolicyApplied` only: the calling activation namespace.
563    #[serde(default, skip_serializing_if = "Option::is_none")]
564    pub caller_ns: Option<String>,
565}
566
567// ---------------------------------------------------------------------------
568// AuditSink trait and TracingAuditSink default impl.
569// ---------------------------------------------------------------------------
570
571/// What the framework calls to persist an [`AuditRecord`].
572///
573/// One method — the framework awaits `write` after a scope check resolves
574/// and before the dispatch responds (the "audit before respond" invariant is
575/// AUTHZ-CORE-5's responsibility; this trait only commits to being
576/// awaitable). `Send + Sync + 'static` so the sink can be held as
577/// `Arc<dyn AuditSink>` across dispatch threads.
578///
579/// # Failure handling
580///
581/// A sink that returns / panics-as-error from `write` is logged at
582/// `tracing::error` and dispatch continues — per AUTHZ-S01-output §8 the
583/// default audit-vs-availability tradeoff is availability. The trait method
584/// returns `()` (not `Result`) for this reason: the contract is "best
585/// effort". The framework wraps the call in `tracing::error!`-on-panic
586/// (`Arc<dyn AuditSink>::write` is awaited inside a panic guard at the
587/// AUTHZ-CORE-5 dispatch path; see the consumer-side tests there). Critical-
588/// sink semantics are deferred (AUTHZ-S01-output §8 open question).
589///
590/// # Default
591///
592/// [`TracingAuditSink`] is the default sink. A backend that never calls
593/// `with_audit_sink` on its hub builder still gets `tracing::info!` events
594/// on the `plexus::audit` target — observability for free.
595#[async_trait]
596pub trait AuditSink: Send + Sync + 'static {
597    /// Persist one audit record.
598    ///
599    /// The contract is best-effort: a sink that cannot write must not
600    /// propagate the error to the caller. The framework awaits this future
601    /// inside a panic guard and treats errors as non-fatal at this layer.
602    async fn write(&self, record: AuditRecord);
603}
604
605/// The default [`AuditSink`]: emit `tracing::info!` events under
606/// `target = "plexus::audit"`.
607///
608/// Per AUTHZ-S01-output §8: "guarantees that even backends that don't think
609/// about audit get *some* observable trail." Every field of the record
610/// appears as a structured field on the emitted event. Operators wire
611/// `tracing-subscriber` once at the deployment level and the audit trail
612/// flows to whatever sink they prefer (JSON to stdout, file, OTLP, etc.).
613///
614/// # Retention
615///
616/// Retention is the responsibility of the `tracing` subscriber configured
617/// at the deployment level (e.g., a file appender with size-based rotation,
618/// or an OTLP exporter with cloud-side retention). The reference sinks in
619/// AUTHZ-PRIVACY-5 cover the cases where structured-log retention is not a
620/// fit (durable WAL, S3 sink, etc.).
621///
622/// # Failure modes
623///
624/// `tracing::info!` is infallible at the macro level; it returns `()`. The
625/// only failure mode is a misconfigured subscriber dropping events, which
626/// `tracing-subscriber`'s standard machinery surfaces as drop counters — not
627/// a per-record error. The sink's `write` therefore cannot fail.
628#[derive(Debug, Clone, Copy, Default)]
629pub struct TracingAuditSink;
630
631impl TracingAuditSink {
632    /// Construct the default sink. Equivalent to `TracingAuditSink::default()`.
633    pub const fn new() -> Self {
634        Self
635    }
636
637    /// `Arc<dyn AuditSink>` for handing into hub builders. Equivalent to
638    /// `Arc::new(TracingAuditSink::new()) as Arc<dyn AuditSink>`.
639    pub fn arc() -> Arc<dyn AuditSink> {
640        Arc::new(Self::new())
641    }
642}
643
644#[async_trait]
645impl AuditSink for TracingAuditSink {
646    async fn write(&self, record: AuditRecord) {
647        // One info! event with the record's structured fields. The
648        // `target = "plexus::audit"` is the contract: deployment-level
649        // subscribers filter / route on it. Field types implement
650        // `Debug`/`Display`; we surface the record itself via the `record`
651        // shorthand so non-trivial fields (the principal chain, the
652        // derivation, etc.) make it into the event without us hand-rolling
653        // a serializer here.
654        let AuditRecord {
655            timestamp,
656            kind,
657            originator,
658            session_id,
659            invocation_chain,
660            roles,
661            method,
662            scope_required,
663            decision,
664            latency_us,
665            origin,
666            client_ip,
667            correlation_id,
668            policy_name,
669            derivation,
670            caller_ns,
671        } = record;
672        tracing::info!(
673            target: "plexus::audit",
674            %timestamp,
675            ?kind,
676            originator = ?originator,
677            session_id = ?session_id,
678            invocation_chain = ?invocation_chain,
679            roles = ?roles,
680            method = %method,
681            scope_required = ?scope_required,
682            decision = ?decision,
683            latency_us,
684            origin = ?origin,
685            client_ip = ?client_ip,
686            %correlation_id,
687            policy_name = ?policy_name,
688            derivation = ?derivation,
689            caller_ns = ?caller_ns,
690            "audit",
691        );
692    }
693}
694
695// ---------------------------------------------------------------------------
696// Tests.
697// ---------------------------------------------------------------------------
698
699#[cfg(test)]
700mod tests {
701    use super::*;
702    use crate::forward::ForwardDerivation;
703    use crate::principal::Principal;
704    use std::net::{IpAddr, Ipv4Addr};
705
706    fn scope_check_record() -> AuditRecord {
707        AuditRecord {
708            timestamp: DateTime::from_timestamp(1_700_000_000, 0).unwrap(),
709            kind: AuditRecordKind::ScopeCheck,
710            originator: Some(UserId::new("alice")),
711            session_id: Some(SessionId::new("sess-42")),
712            invocation_chain: vec![Principal::anonymous_sealed()],
713            roles: vec![RoleName::new("admin"), RoleName::new("user")],
714            method: MethodPath::try_new("solar.earth.luna.info").unwrap(),
715            scope_required: vec![Scope::new("luna.read")],
716            decision: AuditDecision::Allow,
717            latency_us: 123,
718            origin: Some(Origin::new("ws://localhost:4444")),
719            client_ip: Some(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))),
720            correlation_id: Uuid::nil(),
721            policy_name: None,
722            derivation: None,
723            caller_ns: None,
724        }
725    }
726
727    fn forward_policy_record() -> AuditRecord {
728        AuditRecord {
729            timestamp: DateTime::from_timestamp(1_700_000_001, 0).unwrap(),
730            kind: AuditRecordKind::ForwardPolicyApplied,
731            originator: Some(UserId::new("bob")),
732            session_id: Some(SessionId::new("sess-99")),
733            invocation_chain: vec![
734                Principal::anonymous_sealed(),
735                Principal::anonymous_sealed(),
736            ],
737            roles: vec![RoleName::new("editor")],
738            method: MethodPath::try_new("solar.earth.atmosphere.layer").unwrap(),
739            scope_required: vec![Scope::new("atmosphere.read")],
740            decision: AuditDecision::Deny {
741                reason: AuditDenyReason::MissingScope,
742            },
743            latency_us: 456,
744            origin: Some(Origin::new("ws://localhost:4444")),
745            client_ip: Some(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))),
746            correlation_id: Uuid::from_u128(0xdead_beef_cafe_babe_1234_5678_9abc_def0),
747            policy_name: Some(crate::forward::IDENTITY_ONLY_NAME),
748            derivation: Some(ForwardDerivation::IDENTITY_ONLY),
749            caller_ns: Some("ns.caller".to_string()),
750        }
751    }
752
753    // -- AuditRecordKind defaults ---------------------------------------
754
755    #[test]
756    fn audit_record_kind_default_is_scope_check() {
757        assert_eq!(AuditRecordKind::default(), AuditRecordKind::ScopeCheck);
758    }
759
760    #[test]
761    fn audit_record_kind_serializes_snake_case() {
762        let v = serde_json::to_string(&AuditRecordKind::ScopeCheck).unwrap();
763        assert_eq!(v, "\"scope_check\"");
764        let v = serde_json::to_string(&AuditRecordKind::ForwardPolicyApplied).unwrap();
765        assert_eq!(v, "\"forward_policy_applied\"");
766    }
767
768    #[test]
769    fn audit_record_omitted_kind_deserializes_as_scope_check() {
770        // Acceptance criterion 2: a JSON blob omitting `kind` defaults
771        // the record kind to ScopeCheck.
772        let blob = r#"{
773            "timestamp": "2023-11-14T22:13:20Z",
774            "method": "solar.earth.luna.info",
775            "decision": {"decision": "allow"},
776            "latency_us": 17,
777            "correlation_id": "00000000-0000-0000-0000-000000000000"
778        }"#;
779        let record: AuditRecord = serde_json::from_str(blob).unwrap();
780        assert_eq!(record.kind, AuditRecordKind::ScopeCheck);
781    }
782
783    #[test]
784    fn audit_record_omitted_optional_forward_fields_default_to_none() {
785        // Acceptance criterion 3: a JSON blob omitting `policy_name`,
786        // `derivation`, `caller_ns` produces None for each.
787        let blob = r#"{
788            "timestamp": "2023-11-14T22:13:20Z",
789            "method": "solar.earth.luna.info",
790            "decision": {"decision": "allow"},
791            "latency_us": 17,
792            "correlation_id": "00000000-0000-0000-0000-000000000000"
793        }"#;
794        let record: AuditRecord = serde_json::from_str(blob).unwrap();
795        assert!(record.policy_name.is_none());
796        assert!(record.derivation.is_none());
797        assert!(record.caller_ns.is_none());
798        // And the AUTHZ-0-ratification optional fields also default:
799        assert!(record.originator.is_none());
800        assert!(record.session_id.is_none());
801        assert!(record.invocation_chain.is_empty());
802        assert!(record.roles.is_empty());
803        assert!(record.scope_required.is_empty());
804        assert!(record.origin.is_none());
805        assert!(record.client_ip.is_none());
806    }
807
808    // -- AuditDenyReason variants ---------------------------------------
809
810    #[test]
811    fn audit_deny_reason_serializes_snake_case_all_variants() {
812        // Acceptance criterion 4: all seven variants present and round-trip
813        // via snake_case.
814        let cases = [
815            (AuditDenyReason::Unauthenticated, "\"unauthenticated\""),
816            (AuditDenyReason::InvalidSession, "\"invalid_session\""),
817            (AuditDenyReason::MissingScope, "\"missing_scope\""),
818            (AuditDenyReason::NotAccepted, "\"not_accepted\""),
819            (AuditDenyReason::TenantBoundary, "\"tenant_boundary\""),
820            (AuditDenyReason::RateLimited, "\"rate_limited\""),
821            (AuditDenyReason::Other, "\"other\""),
822        ];
823        for (variant, encoded) in cases {
824            let s = serde_json::to_string(&variant).unwrap();
825            assert_eq!(s, encoded, "serialize {:?}", variant);
826            let parsed: AuditDenyReason = serde_json::from_str(encoded).unwrap();
827            assert_eq!(parsed, variant, "deserialize {}", encoded);
828        }
829    }
830
831    // -- AuditDecision encoding -----------------------------------------
832
833    #[test]
834    fn audit_decision_allow_round_trips() {
835        let s = serde_json::to_string(&AuditDecision::Allow).unwrap();
836        assert_eq!(s, "{\"decision\":\"allow\"}");
837        let v: AuditDecision = serde_json::from_str(&s).unwrap();
838        assert_eq!(v, AuditDecision::Allow);
839    }
840
841    #[test]
842    fn audit_decision_deny_carries_reason() {
843        let d = AuditDecision::Deny {
844            reason: AuditDenyReason::MissingScope,
845        };
846        let s = serde_json::to_string(&d).unwrap();
847        assert_eq!(s, "{\"decision\":\"deny\",\"reason\":\"missing_scope\"}");
848        let parsed: AuditDecision = serde_json::from_str(&s).unwrap();
849        assert_eq!(parsed, d);
850    }
851
852    // -- ScopeCheck / ForwardPolicyApplied markers ----------------------
853
854    #[test]
855    fn scope_check_marker_into_kind() {
856        let k: AuditRecordKind = ScopeCheck.into();
857        assert_eq!(k, AuditRecordKind::ScopeCheck);
858    }
859
860    #[test]
861    fn forward_policy_applied_marker_into_kind() {
862        let k: AuditRecordKind = ForwardPolicyApplied.into();
863        assert_eq!(k, AuditRecordKind::ForwardPolicyApplied);
864    }
865
866    // -- Newtypes -------------------------------------------------------
867
868    #[test]
869    fn user_id_round_trips_as_bare_string() {
870        let u = UserId::new("alice");
871        let s = serde_json::to_string(&u).unwrap();
872        assert_eq!(s, "\"alice\"");
873        let parsed: UserId = serde_json::from_str(&s).unwrap();
874        assert_eq!(parsed, u);
875    }
876
877    #[test]
878    fn session_id_round_trips_as_bare_string() {
879        let s = SessionId::new("sess-1");
880        let json = serde_json::to_string(&s).unwrap();
881        assert_eq!(json, "\"sess-1\"");
882        let parsed: SessionId = serde_json::from_str(&json).unwrap();
883        assert_eq!(parsed, s);
884    }
885
886    #[test]
887    fn role_name_round_trips_as_bare_string() {
888        let r = RoleName::new("admin");
889        let s = serde_json::to_string(&r).unwrap();
890        assert_eq!(s, "\"admin\"");
891        let parsed: RoleName = serde_json::from_str(&s).unwrap();
892        assert_eq!(parsed, r);
893    }
894
895    #[test]
896    fn sensitive_field_round_trips_as_bare_string() {
897        let f = SensitiveField::new("password");
898        let s = serde_json::to_string(&f).unwrap();
899        assert_eq!(s, "\"password\"");
900        let parsed: SensitiveField = serde_json::from_str(&s).unwrap();
901        assert_eq!(parsed, f);
902    }
903
904    #[test]
905    fn newtypes_are_display() {
906        assert_eq!(format!("{}", UserId::new("alice")), "alice");
907        assert_eq!(format!("{}", SessionId::new("s1")), "s1");
908        assert_eq!(format!("{}", RoleName::new("admin")), "admin");
909    }
910
911    // -- AuditRecord round-trip -----------------------------------------
912
913    #[test]
914    fn audit_record_scope_check_round_trips_byte_for_byte() {
915        // Serialize then deserialize then re-serialize; the two encoded
916        // forms must match byte-for-byte (guards against asymmetric serde
917        // attributes).
918        let record = scope_check_record();
919        let first = serde_json::to_string(&record).unwrap();
920        let parsed: AuditRecord = serde_json::from_str(&first).unwrap();
921        let second = serde_json::to_string(&parsed).unwrap();
922        assert_eq!(first, second, "round-trip not byte-equal");
923    }
924
925    #[test]
926    fn audit_record_forward_policy_round_trips_byte_for_byte() {
927        // Acceptance criterion 10: serialize an AuditRecord carrying every
928        // field populated (a ForwardPolicyApplied kind with policy_name,
929        // derivation, caller_ns set, plus the base ScopeCheck fields),
930        // deserialize it, assert byte-for-byte equality.
931        let record = forward_policy_record();
932        let first = serde_json::to_string(&record).unwrap();
933        let parsed: AuditRecord = serde_json::from_str(&first).unwrap();
934        let second = serde_json::to_string(&parsed).unwrap();
935        assert_eq!(first, second, "round-trip not byte-equal");
936
937        // Sanity: structural equality on the round-tripped pieces (Principal
938        // does not impl PartialEq so we cannot assert on the whole record).
939        assert_eq!(parsed.kind, AuditRecordKind::ForwardPolicyApplied);
940        assert_eq!(parsed.originator.as_ref().map(|u| u.as_str()), Some("bob"));
941        assert_eq!(
942            parsed.session_id.as_ref().map(|s| s.as_str()),
943            Some("sess-99")
944        );
945        assert_eq!(parsed.invocation_chain.len(), 2);
946        assert_eq!(parsed.roles, vec![RoleName::new("editor")]);
947        assert_eq!(
948            parsed.decision,
949            AuditDecision::Deny {
950                reason: AuditDenyReason::MissingScope
951            }
952        );
953        assert_eq!(parsed.latency_us, 456);
954        assert_eq!(
955            parsed.policy_name,
956            Some(crate::forward::IDENTITY_ONLY_NAME)
957        );
958        assert_eq!(parsed.derivation, Some(ForwardDerivation::IDENTITY_ONLY));
959        assert_eq!(parsed.caller_ns.as_deref(), Some("ns.caller"));
960    }
961
962    #[test]
963    fn audit_record_carries_principal_chain() {
964        let record = forward_policy_record();
965        assert_eq!(record.invocation_chain.len(), 2);
966    }
967
968    #[test]
969    fn audit_record_clone_yields_independent_value() {
970        // Smoke-test the Clone derive that acceptance criterion 1 demands.
971        let record = scope_check_record();
972        let copy = record.clone();
973        assert_eq!(copy.latency_us, record.latency_us);
974        assert_eq!(copy.correlation_id, record.correlation_id);
975    }
976
977    // -- AuditSink trait object safety ---------------------------------
978
979    #[test]
980    fn audit_sink_is_object_safe_via_arc_dyn() {
981        // Acceptance criterion 5: trait must be holdable as `Arc<dyn AuditSink>`.
982        let _sink: Arc<dyn AuditSink> = Arc::new(TracingAuditSink::new());
983    }
984
985    #[test]
986    fn tracing_audit_sink_arc_constructs() {
987        let _sink: Arc<dyn AuditSink> = TracingAuditSink::arc();
988    }
989
990    // -- TracingAuditSink emits an event -------------------------------
991
992    #[tokio::test]
993    #[tracing_test::traced_test]
994    async fn tracing_audit_sink_emits_info_event() {
995        // Acceptance criterion 6: TracingAuditSink::write emits a
996        // tracing::info! event under target = "plexus::audit". The
997        // tracing-test harness captures emitted events into a string;
998        // `logs_contain` asserts the message body appears.
999        let sink = TracingAuditSink::new();
1000        sink.write(scope_check_record()).await;
1001        // The literal message of the info! call is "audit"; the captured
1002        // log line also carries the target. Both substrings must be
1003        // present.
1004        assert!(logs_contain("audit"));
1005        assert!(logs_contain("plexus::audit"));
1006    }
1007
1008    #[tokio::test]
1009    #[tracing_test::traced_test]
1010    async fn tracing_audit_sink_emits_for_deny_records() {
1011        let sink = TracingAuditSink::new();
1012        sink.write(forward_policy_record()).await;
1013        assert!(logs_contain("audit"));
1014        assert!(logs_contain("MissingScope"));
1015    }
1016
1017    // -- Sink-failure non-propagation (acceptance criterion 9) ---------
1018
1019    /// A test sink that signals failure by setting an `AtomicBool`. The
1020    /// AuditSink contract is best-effort — a sink's failure must not
1021    /// surface to the caller of `write`. We model failure as a sink that
1022    /// records the attempt and returns; the framework's wrapping at the
1023    /// AUTHZ-CORE-5 dispatch path is responsible for the
1024    /// `tracing::error`-on-panic translation (this ticket only commits to
1025    /// the awaitable contract — see AuditSink doc).
1026    struct FailingSink {
1027        attempted: std::sync::atomic::AtomicBool,
1028    }
1029
1030    #[async_trait]
1031    impl AuditSink for FailingSink {
1032        async fn write(&self, _record: AuditRecord) {
1033            self.attempted
1034                .store(true, std::sync::atomic::Ordering::SeqCst);
1035            // The contract returns `()`. A sink that "fails" simply gives
1036            // up on persistence — that's the trait's permission. A sink
1037            // that panics is the framework's problem (see consumer-side
1038            // tests in AUTHZ-CORE-5).
1039        }
1040    }
1041
1042    #[tokio::test]
1043    async fn failing_sink_does_not_propagate_error_to_caller() {
1044        let sink = FailingSink {
1045            attempted: std::sync::atomic::AtomicBool::new(false),
1046        };
1047        // The future resolves to `()`. No `?`, no `.await?` — the trait's
1048        // signature *is* the non-propagation guarantee.
1049        sink.write(scope_check_record()).await;
1050        assert!(sink.attempted.load(std::sync::atomic::Ordering::SeqCst));
1051    }
1052
1053    #[tokio::test]
1054    #[tracing_test::traced_test]
1055    async fn panicking_sink_panic_is_observable_via_join_handle() {
1056        // Acceptance criterion 9: a sink that panics from `write` does NOT
1057        // propagate the panic to the caller. The framework's responsibility
1058        // (AUTHZ-CORE-5 dispatch path) is to drive the sink's future inside
1059        // a panic guard and translate to a `tracing::error` carrying the
1060        // correlation_id. We model that responsibility here with
1061        // `tokio::spawn`, which already gives panic translation via the
1062        // returned `JoinHandle::is_panic()`.
1063        struct PanickingSink;
1064        #[async_trait]
1065        impl AuditSink for PanickingSink {
1066            async fn write(&self, record: AuditRecord) {
1067                panic!("sink down (correlation_id={})", record.correlation_id);
1068            }
1069        }
1070        let sink: Arc<dyn AuditSink> = Arc::new(PanickingSink);
1071        let record = scope_check_record();
1072        let correlation_id = record.correlation_id;
1073        let sink_for_task = Arc::clone(&sink);
1074        let record_for_task = record.clone();
1075        let handle = tokio::spawn(async move {
1076            sink_for_task.write(record_for_task).await;
1077        });
1078        let join_result = handle.await;
1079        // The task panicked; the join handle reports the panic without
1080        // propagating it.
1081        let join_err = join_result.expect_err("sink panic should surface as task panic");
1082        assert!(join_err.is_panic());
1083        // The framework now logs at tracing::error with the correlation_id.
1084        tracing::error!(
1085            target: "plexus::audit",
1086            %correlation_id,
1087            "audit sink panicked; record dropped"
1088        );
1089        assert!(logs_contain("audit sink panicked"));
1090        assert!(logs_contain(&correlation_id.to_string()));
1091    }
1092}