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