Skip to main content

hyprstream_core/mac/
exchange.rs

1//! **MAC S6 — runtime grant path: UCAN grant-request → access/refresh tokens.**
2//! Part of the native-MAC program.
3//!
4//! This is the **runtime** companion to S5's compile-time UCAN→Casbin/TE compiler.
5//! S5 compiles an *approved* UCAN into a ceiling (a `CompiledPolicy` +
6//! `SignedApproval` binding) — that is the standing authorization-to-REQUEST.
7//! S6 is the path a principal takes at runtime to turn a **subset-UCAN grant**
8//! into **ephemeral, sender-bound OAuth tokens** (RFC 8693 token-exchange shape).
9//!
10//! ## The #547 MAC model this honours
11//!
12//! - **UCAN authors; Casbin/TE enforces.** The grant presented here is a UCAN
13//!   delegation chain; we never mint tokens wider than that grant.
14//! - **ZSP (Zero Standing Privilege).** The ceiling is standing
15//!   authorization-to-REQUEST, NOT access. Access is **ephemeral** (short-ttl),
16//!   **per-task** (not per-op), and **re-evaluated on refresh**. There is no
17//!   long-lived bearer that bypasses the grant.
18//! - **Ceiling = the grant itself.** The subset-UCAN a principal presents is a
19//!   strict attenuated subset of an approved ceiling. The grant's root
20//!   capabilities ARE the ceiling for this request; `authorize(grant, request)`
21//!   is the ceiling-subset check.
22//! - **Fail-closed / single path.** Every failure mode — bad chain, over-ceiling
23//!   request, insufficient MAC clearance, missing sender-binding — denies. There
24//!   is **no fallback path**: a fallback is a downgrade vector. Authority being
25//!   unreachable is a denial, not a reason to mint a narrower token.
26//! - **Escalation ≠ auto-widen.** A request beyond the grant's ceiling is a
27//!   denial pending a **ceiling amendment** (the tiered decision — static Casbin
28//!   / agentic / admin-UDF — which is authority-owned and MAC-bounded). S6 does
29//!   NOT auto-escalate; it routes to `Decision::Escalate` and returns
30//!   `insufficient_scope`. The amendment flow is deferred (TODO locations below).
31//!
32//! ## What this module owns (and what it does NOT)
33//!
34//! **Owns (the fail-closed core):**
35//! - Validate the presented UCAN grant chain (delegates to S5's
36//!   [`hyprstream_rpc::auth::ucan::chain::validate`] — signatures + attenuation +
37//!   temporal validity at the trusted `now`).
38//! - **Ceiling-subset check**: the access being requested now must be authorized
39//!   by the grant's capabilities ([`mac::compiler::authorize`]).
40//! - **MAC clearance gate**: the principal's clearance (from verified key
41//!   material / S1 `SubjectContextClaims`) must dominate the request's label.
42//!   Insufficient clearance ⇒ deny (the S1 floor, reused — not reinvented).
43//! - Compose the subset of capabilities the token will actually carry
44//!   (never the whole grant — ZSP: mint the least subset that covers the
45//!   requested access).
46//!
47//! **Does NOT own (consumed from siblings — no parallel implementation):**
48//! - UCAN chain validation, attenuation, signature verification → S5
49//!   (`hyprstream_rpc::auth::ucan`).
50//! - The grant-vs-request authorization relation → S5's compiler
51//!   ([`mac::compiler::authorize`]).
52//! - Security labels, clearance, dominance → S1 (`hyprstream_rpc::auth::mac`).
53//! - DPoP sender-binding (#514/#515) → `services::oauth::dpop`.
54//! - JWT signing → `services::oauth` (via `hyprstream_rpc::auth::jwt`).
55//! - Hybrid-PQC signing of the minted tokens → **S8 (#574) landed**: the
56//!   `mint_grant_token` path now signs via the hybrid composite JWT
57//!   (`encode_composite_ml_dsa_65_ed25519`) when an ML-DSA-65 key is
58//!   provisioned, matching the hybrid signature on the UCAN/approval it
59//!   consumes. Classical Ed25519 is the explicit policy-selected fallback.
60//!
61//! ## Scope of this PR (core, sound, tested) vs. deferred
62//!
63//! **In scope:** the pure fail-closed core — grant validation, ceiling-subset
64//! check, MAC clearance gate, sender-binding requirement, and the
65//! `GrantDecision` it produces. Plus full negative-test coverage (over-ceiling,
66//! bad chain, insufficient clearance, missing DPoP). The HTTP grant wiring and
67//! token minting live in `services::oauth::token_exchange` and call into
68//! [`evaluate_grant`] here.
69//!
70//! **Deferred (fail-closed until landed):**
71//! - Full escalation tiers (static Casbin / agentic / admin-UDF amendment) —
72//!   see [`GrantDecision::Escalate`].
73//! - Refresh-token rotation with re-evaluation plumbing end-to-end (the
74//!   `evaluate_grant` call on refresh is wired; rotation storage is the OAuth
75//!   layer's job).
76//!
77//! Revocation propagation into the grant path (the former
78//! `TODO(#572-revocation)`) is closed by construction: every credential the
79//! grant path mints carries an issuer-scoped `jti` and is checked against the
80//! canonical revocation authority at every verification point; interactive
81//! refresh chains carry a session ID whose revocation prevents refresh
82//! without consuming the credential; and UCAN-grant refresh entries are
83//! single-use, re-evaluated here, and deletable through `/oauth/revoke`.
84
85use hyprstream_rpc::auth::mac::{
86    SecurityContext, SecurityLabel, SubjectContextClaims, VerifiedKeyMaterial,
87};
88use hyprstream_rpc::auth::ucan::capability::{Ability, Capability, Caveats, Resource};
89use hyprstream_rpc::auth::ucan::chain::{self, ChainError};
90use hyprstream_rpc::auth::ucan::token::{Ucan, UcanVerifier};
91
92use crate::mac::compiler::{authorize_at, AccessRequest};
93use crate::mac::te::Decision;
94
95/// The token-type URI identifying a UCAN grant as the RFC 8693 `subject_token`.
96///
97/// A presenter supplies a CBOR-encoded UCAN as `subject_token` with this
98/// `subject_token_type` at the token-exchange endpoint. Distinct from the OIDC
99/// `id_token` / `access_token` / `jwt` types so the grant path cannot be
100/// confused with the existing exchange flows.
101pub const UCAN_GRANT_TOKEN_TYPE: &str = "urn:hyprstream:token-type:ucan-grant";
102
103/// Hard ceiling on the access-token TTL minted from a UCAN grant. ZSP: grant
104/// tokens are deliberately short-lived so the re-evaluation-on-refresh property
105/// has teeth. The OAuth layer clamps its configured `token_ttl` down to this.
106pub const MAX_ACCESS_TOKEN_TTL_SECS: u32 = 900; // 15 minutes
107
108/// Why a grant request was denied. Every variant is fail-closed; there is no
109/// "best-effort" or "narrow-and-continue" outcome. The cardinal rule of #547:
110/// authority-unreachable ⇒ deny, never downgrade.
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub enum GrantError {
113    /// The UCAN chain failed S5 validation (bad signature, broken linkage,
114    /// widening, window escape, expired/not-yet-valid, or over-depth). Wrapped
115    /// verbatim from S5 so the failure mode is auditable.
116    Chain(ChainError),
117    /// The request exceeds the grant's ceiling — an escalation attempt. This is
118    /// routed to the (deferred) escalation tier; until that lands it is a
119    /// denial. **S6 never auto-escalates.** The offending requested capability
120    /// (the one no grant capability authorizes) is included for diagnostics.
121    OverCeiling { requested: Capability },
122    /// The principal's MAC clearance does not dominate the request's label — the
123    /// S1 floor denies. This is independent of the ceiling: a principal may hold
124    /// a valid grant for an object whose label they are not cleared for. Both
125    /// gates must pass.
126    InsufficientClearance,
127    /// No sender-binding (DPoP proof) was supplied. ZSP: the minted token MUST
128    /// be sender-bound — a bearer token minted from a grant would re-introduce
129    /// standing access, defeating the whole model.
130    MissingSenderBinding,
131    /// The subject carried no derivable clearance at all (unlabeled subject).
132    /// Per S1, an unlabeled subject has no context and the monitor denies —
133    /// there is no default clearance.
134    UnlabeledSubject,
135    /// The grant carries no capabilities at all, so there is no ceiling to
136    /// request a subset of. An empty grant mints nothing.
137    EmptyGrant,
138    /// **B2 (#674):** the request would otherwise `Permit`, but the decision
139    /// could not be durably audited (the audit sink's `record` failed, or its
140    /// signer cannot sign under the enforced crypto policy). Mirrors S7's
141    /// `AuditedAvc` fail-closed rule at the grant path: a decision that cannot
142    /// be audited is never allowed through. See [`audited_evaluate_grant`].
143    AuditUnavailable,
144}
145
146impl std::fmt::Display for GrantError {
147    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148        match self {
149            GrantError::Chain(e) => write!(f, "UCAN grant chain invalid: {e}"),
150            GrantError::OverCeiling { requested } => write!(
151                f,
152                "grant request exceeds ceiling (escalation denied pending amendment): {requested}"
153            ),
154            GrantError::InsufficientClearance => {
155                write!(
156                    f,
157                    "subject MAC clearance does not dominate the request label"
158                )
159            }
160            GrantError::MissingSenderBinding => {
161                write!(
162                    f,
163                    "UCAN grant token-exchange requires a sender-binding (DPoP) proof"
164                )
165            }
166            GrantError::UnlabeledSubject => {
167                write!(f, "subject carries no MAC clearance (unlabeled ⇒ deny)")
168            }
169            GrantError::EmptyGrant => write!(f, "grant carries no capabilities (empty ceiling)"),
170            GrantError::AuditUnavailable => write!(
171                f,
172                "grant decision could not be durably audited (fail-closed)"
173            ),
174        }
175    }
176}
177
178impl std::error::Error for GrantError {}
179
180/// The outcome of evaluating a grant request: the fail-closed "mint" decision.
181///
182/// On `Permit`, [`GrantedAccess`] holds the **minimum subset** of the grant the
183/// token will encode (ZSP: never mint the whole grant; mint the least authority
184/// that covers the request). On `Escalate`, the request is over-ceiling and
185/// awaits a (deferred) amendment; the caller returns `insufficient_scope`.
186#[derive(Debug, Clone, PartialEq, Eq)]
187pub enum GrantDecision {
188    /// The request is a valid subset of a valid grant, the subject is cleared,
189    /// and a sender-binding is present. The contained [`GrantedAccess`] is what
190    /// the token minting layer encodes.
191    Permit(GrantedAccess),
192    /// The request exceeds the grant ceiling. Routed to the escalation tier;
193    /// until the tiered-decision lands this is a denial. `requested` is the
194    /// over-ceiling capability for diagnostics.
195    Escalate { requested: Capability },
196}
197
198/// The minimum subset of the grant a minted token will carry — the ZSP output.
199///
200/// This is the single capability (resource + ability + caveats) that the
201/// presenter requested, re-checked against the grant. It is intentionally a
202/// *subset* (≤ the grant), not the grant verbatim: the minted token is the
203/// least authority covering the request, so a refresh re-evaluation can only
204/// re-grant what was originally requested, never grow toward the ceiling.
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct GrantedAccess {
207    /// The capability the minted token encodes: the requested access, which is
208    /// guaranteed (by the ceiling-subset check) to be authorized by the grant.
209    pub capability: Capability,
210    /// The audience the token is minted for (RFC 8707 resource indicator), if
211    /// any. Carried through to the JWT `aud` claim.
212    pub audience: Option<String>,
213}
214
215/// A resolved grant request: the principal's desired access, parsed off the
216/// token-exchange `resource`/`scope` form fields into the S5 capability shape so
217/// the compiler's `authorize` can evaluate it.
218#[derive(Debug, Clone)]
219pub struct GrantRequest {
220    /// The resource being requested (`mac://model/qwen-7b` style). Required.
221    pub resource: Resource,
222    /// The ability being requested (`infer`, `model/read`, …). Required.
223    pub ability: Ability,
224    /// Caveats the presenter asks to be bound by (e.g. tenant). May be empty;
225    /// the resulting token is at least this restricted.
226    pub caveats: Caveats,
227    /// Optional audience (RFC 8707 resource indicator).
228    pub audience: Option<String>,
229    /// The MAC label of the object the request targets — used for the S1
230    /// clearance floor. `None` ⇒ unlabeled object ⇒ deny (the S1 rule). The
231    /// caller (OAuth layer) obtains this from the manifest/TE vocabulary; S6
232    /// does not invent it.
233    pub object_label: Option<SecurityLabel>,
234}
235
236/// Evaluate a UCAN grant request: the single fail-closed S6 path.
237///
238/// Inputs:
239/// - `grant`: the presented subset-UCAN (a delegation chain whose root
240///   capabilities are the ceiling for this request).
241/// - `verifier`: the S5 `UcanVerifier` (trust store resolving each issuer's
242///   anchored ML-DSA-65 key). Signatures are verified under the hybrid policy.
243/// - `now`: the single trusted clock (unix seconds), threaded unchanged into
244///   every chain link by S5 — never read from the token.
245/// - `request`: what the principal is asking to do now (the subset).
246/// - `subject`: the principal's verified security context (S1 clearance +
247///   assurance, clamped to verified key material). `None` ⇒ unlabeled ⇒ deny.
248/// - `sender_bound`: whether a DPoP proof was supplied and verified by the
249///   caller. ZSP requires sender-binding; `false` ⇒ deny.
250///
251/// Gates, in order (all fail-closed; the first failure wins):
252/// 1. **Sender-binding required** (ZSP) — no bearer tokens from a grant.
253/// 2. **Non-empty grant** — an empty grant mints nothing.
254/// 3. **Labeled subject** — S1: unlabeled subject ⇒ deny (no default clearance).
255/// 4. **Labeled object** — S1: unlabeled object ⇒ deny.
256/// 5. **MAC clearance floor** — `subject.clearance ⊒ object_label`.
257/// 6. **UCAN chain valid** — S5 `validate` (signatures + attenuation + temporal).
258/// 7. **Ceiling-subset** — `authorize_at(grant.capabilities(), grant.window,
259///    request, now)` permits. `Deny` ⇒ over-ceiling ⇒ `Escalate` (not auto-mint).
260///
261/// Order rationale: the cheap structural/label gates run before the
262/// cryptographic chain walk, so a malformed or uncleared request is rejected
263/// without spending the signature-verification budget. The chain is validated
264/// before the ceiling check so an invalid chain can never reach `authorize`.
265pub fn evaluate_grant<V: UcanVerifier + ?Sized>(
266    grant: &Ucan,
267    verifier: &V,
268    now: u64,
269    request: &GrantRequest,
270    subject: Option<&SecurityContext>,
271    sender_bound: bool,
272) -> Result<GrantDecision, GrantError> {
273    // (1) ZSP: sender-binding is mandatory. A bearer token minted from a grant
274    // re-introduces standing access — the exact thing ZSP removes. The caller
275    // verifies the DPoP proof; we only require that it did.
276    if !sender_bound {
277        return Err(GrantError::MissingSenderBinding);
278    }
279
280    // (2) An empty grant is no ceiling at all. (set_attenuates treats an empty
281    // `held` as covering only an empty `claimed`; we surface it explicitly so
282    // the error is unambiguous.)
283    if grant.capabilities().is_empty() {
284        return Err(GrantError::EmptyGrant);
285    }
286
287    // (3)+(4) S1 floor: unlabeled subject or unlabeled object ⇒ deny. The MAC
288    // model has no default clearance and no default label; absence is denial.
289    let subject = subject.ok_or(GrantError::UnlabeledSubject)?;
290    let object_label = request
291        .object_label
292        .ok_or(GrantError::InsufficientClearance)?;
293
294    // (5) MAC clearance dominance — the S1 floor, reused not reinvented.
295    // `SecurityContext::can_access` is the intrinsic lattice dominance
296    // (level ≥, assurance ≥, compartments ⊇). This gate is INDEPENDENT of the
297    // ceiling: a principal may hold a valid grant for an object whose label they
298    // are not cleared for (e.g. PQC-required object, classical-only subject).
299    // Both must pass.
300    if !subject.can_access(&object_label) {
301        return Err(GrantError::InsufficientClearance);
302    }
303
304    // (6) S5 full chain validation: structure → hybrid signatures →
305    // attenuation/linkage → temporal validity at `now`. Fail-closed on any
306    // malformation, widening, broken linkage, window escape, expiry, or
307    // over-depth. This is the load-bearing authority check; nothing below runs
308    // against an unvalidated chain.
309    if let Err(e) = chain::validate(grant, verifier, now) {
310        return Err(GrantError::Chain(e));
311    }
312
313    // (7) Ceiling-subset: is the requested access authorized by the grant's
314    // capabilities at `now`? This is S5's compiler `authorize_at`, the same
315    // relation `check_no_escalation` uses — not a parallel implementation.
316    let req = AccessRequest {
317        resource: request.resource.clone(),
318        ability: request.ability.clone(),
319        caveats: request.caveats.clone(),
320    };
321    let decision = authorize_at(
322        grant.capabilities(),
323        grant.payload.not_before,
324        grant.payload.expiration,
325        &req,
326        now,
327    );
328    match decision {
329        Decision::Permit => {
330            // ZSP: mint the LEAST authority covering the request — the requested
331            // capability itself, which `authorize` just confirmed the grant
332            // covers. Never mint the whole grant; a refresh can only re-grant
333            // this subset.
334            let capability = Capability::with_caveats(
335                request.resource.clone(),
336                request.ability.clone(),
337                request.caveats.clone(),
338            );
339            Ok(GrantDecision::Permit(GrantedAccess {
340                capability,
341                audience: request.audience.clone(),
342            }))
343        }
344        // Over-ceiling. This is the escalation tier ingress. S6 does NOT
345        // auto-escalate: a request beyond the ceiling is denied pending a
346        // ceiling amendment via the (deferred) tiered decision (static
347        // Casbin / agentic / admin-UDF — authority-owned, MAC-bounded).
348        // Until that lands, over-ceiling is a hard denial via the caller's
349        // `insufficient_scope` response.
350        Decision::Deny | Decision::Escalate => Err(GrantError::OverCeiling {
351            requested: Capability::with_caveats(
352                request.resource.clone(),
353                request.ability.clone(),
354                request.caveats.clone(),
355            ),
356        }),
357    }
358}
359
360/// Re-evaluate a grant on token refresh: the ZSP "access is re-evaluated on
361/// refresh" property.
362///
363/// Refresh is NOT a free re-mint. The presenter must re-present the grant (the
364/// ceiling may have been amended or revoked since the access token was minted),
365/// and the same [`evaluate_grant`] gates run again. This is a thin forwarder
366/// today — the name exists so the refresh path has an obvious, audited call
367/// site distinct from the initial mint, and so the deferred rotation logic
368/// has a home.
369///
370/// SECURITY: the refresh MUST supply a fresh DPoP proof (`sender_bound` from a
371/// new proof, not carried over) and the same `now`-threading rules apply.
372pub fn evaluate_refresh<V: UcanVerifier + ?Sized>(
373    grant: &Ucan,
374    verifier: &V,
375    now: u64,
376    request: &GrantRequest,
377    subject: Option<&SecurityContext>,
378    sender_bound: bool,
379) -> Result<GrantDecision, GrantError> {
380    // Identical gates to the initial mint. ZSP: no path diverges here — a
381    // refresh that weakens any gate is a refresh that denies.
382    evaluate_grant(grant, verifier, now, request, subject, sender_bound)
383}
384
385/// As [`evaluate_grant`], but records a tamper-evident [`AuditRecord`] of the
386/// outcome through `sink` before returning — S7's complete-mediation guarantee
387/// extended to the grant path (B2, #674). This is the mint-path entry point
388/// production code should call; the plain [`evaluate_grant`] is the
389/// unaudited core the gate tests exercise directly.
390///
391/// Every gate outcome is audited, permit and deny alike (`DecisionReason`'s
392/// `Grant*` variants — see [`crate::mac::audit::DecisionReason`]). On a would-be
393/// `Permit`, the audit write happens **before** the token layer is told to
394/// mint: if it fails, the permit is downgraded to
395/// [`GrantError::AuditUnavailable`] rather than handed back — mirroring
396/// [`crate::mac::audit::AuditedAvc`]'s fail-closed rule that a decision which
397/// cannot be audited is never allowed through.
398#[allow(clippy::too_many_arguments)]
399pub fn audited_evaluate_grant<V: UcanVerifier + ?Sized>(
400    grant: &Ucan,
401    verifier: &V,
402    now: u64,
403    request: &GrantRequest,
404    subject: Option<&SecurityContext>,
405    on_behalf_of: Option<&SecurityContext>,
406    sender_bound: bool,
407    sink: &dyn crate::mac::audit::AuditSink,
408) -> Result<GrantDecision, GrantError> {
409    let result = evaluate_grant(grant, verifier, now, request, subject, sender_bound);
410    audit_grant_outcome(subject, on_behalf_of, request, &result, sink)
411}
412
413/// As [`evaluate_refresh`], with the same audit-then-decide wrapping as
414/// [`audited_evaluate_grant`]. The refresh path's audit records are
415/// indistinguishable in shape from the mint path's (both are grant-path
416/// decisions); the caller distinguishes them by context if needed.
417#[allow(clippy::too_many_arguments)]
418pub fn audited_evaluate_refresh<V: UcanVerifier + ?Sized>(
419    grant: &Ucan,
420    verifier: &V,
421    now: u64,
422    request: &GrantRequest,
423    subject: Option<&SecurityContext>,
424    on_behalf_of: Option<&SecurityContext>,
425    sender_bound: bool,
426    sink: &dyn crate::mac::audit::AuditSink,
427) -> Result<GrantDecision, GrantError> {
428    let result = evaluate_refresh(grant, verifier, now, request, subject, sender_bound);
429    audit_grant_outcome(subject, on_behalf_of, request, &result, sink)
430}
431
432/// Shared audit-then-decide core for [`audited_evaluate_grant`] /
433/// [`audited_evaluate_refresh`]. Builds the [`AuditRecord`] from whatever
434/// context is available (subject may be `None` on an unlabeled-subject
435/// denial; the request's ability may not parse as a canonical
436/// [`crate::auth::ScopeAction`] — both are still recorded, using the
437/// sentinel ids documented on [`crate::mac::te::GRANT_PATH_SUBJECT`]).
438fn audit_grant_outcome(
439    subject: Option<&SecurityContext>,
440    on_behalf_of: Option<&SecurityContext>,
441    request: &GrantRequest,
442    result: &Result<GrantDecision, GrantError>,
443    sink: &dyn crate::mac::audit::AuditSink,
444) -> Result<GrantDecision, GrantError> {
445    use crate::auth::scope_action_from_name;
446    use crate::mac::audit::{AuditRecord, DecisionReason, DelegationPrincipal};
447    use crate::mac::te::{Action, ACTION_UNRECOGNIZED, GRANT_PATH_OBJECT, GRANT_PATH_SUBJECT};
448    use hyprstream_rpc::auth::mac::SecurityLabel;
449
450    let (decision, reason) = match result {
451        Ok(GrantDecision::Permit(_)) => (Decision::Permit, DecisionReason::Permit),
452        Ok(GrantDecision::Escalate { .. }) => {
453            (Decision::Escalate, DecisionReason::GrantOverCeiling)
454        }
455        Err(GrantError::Chain(_)) => (Decision::Deny, DecisionReason::GrantChainInvalid),
456        Err(GrantError::OverCeiling { .. }) => (Decision::Deny, DecisionReason::GrantOverCeiling),
457        Err(GrantError::InsufficientClearance) => (Decision::Deny, DecisionReason::GrantFloorDeny),
458        Err(GrantError::MissingSenderBinding) => {
459            (Decision::Deny, DecisionReason::GrantMissingSenderBinding)
460        }
461        Err(GrantError::UnlabeledSubject) => {
462            (Decision::Deny, DecisionReason::GrantUnlabeledSubject)
463        }
464        Err(GrantError::EmptyGrant) => (Decision::Deny, DecisionReason::GrantEmptyGrant),
465        // Constructed below, never as the pre-audit decision — but exhaustive
466        // match requires a reachable-if-mis-called arm. Records as a deny.
467        Err(GrantError::AuditUnavailable) => (Decision::Deny, DecisionReason::GrantAuditFailClosed),
468    };
469
470    let action = scope_action_from_name(request.ability.as_str())
471        .map(Action::from)
472        .unwrap_or(ACTION_UNRECOGNIZED);
473    let record = AuditRecord {
474        seq: 0,               // the sink (WalAuditStore) assigns the real seq.
475        prev_hash: [0u8; 32], // the sink assigns the real chain link.
476        ts_unix_nanos: std::time::SystemTime::now()
477            .duration_since(std::time::UNIX_EPOCH)
478            .map(|d| d.as_nanos())
479            .unwrap_or(0),
480        decision,
481        generation: 0, // grant decisions are not TE-matrix-generation-versioned.
482        policy_hash: None,
483        subject_type: GRANT_PATH_SUBJECT,
484        subject_clearance: subject
485            .map(|s| *s.clearance())
486            .unwrap_or_else(SecurityLabel::bottom),
487        // #680/#681: on a delegated grant the delegator (authority source) is
488        // recorded here; `subject_clearance` above is the effective met context
489        // the gates evaluated. Same GRANT_PATH_SUBJECT sentinel type — the
490        // clearance is the distinguishing field on the grant path.
491        on_behalf_of: on_behalf_of.map(|d| DelegationPrincipal {
492            subject_type: GRANT_PATH_SUBJECT,
493            subject_clearance: *d.clearance(),
494        }),
495        object_type: GRANT_PATH_OBJECT,
496        object_label: request.object_label.unwrap_or_else(SecurityLabel::bottom),
497        action,
498        reason,
499        subject_id: None,
500        object_id: None,
501    };
502
503    match sink.record(&record) {
504        Ok(()) => result.clone(),
505        Err(_) => {
506            // Fail-closed: a would-be Permit that cannot be durably audited is
507            // downgraded. A deny that cannot be audited is still enforced as
508            // decided (the deny is not weakened by a broken audit sink) but the
509            // failure is surfaced so it is observable.
510            if matches!(result, Ok(GrantDecision::Permit(_))) {
511                let deny_record = AuditRecord {
512                    reason: DecisionReason::GrantAuditFailClosed,
513                    decision: Decision::Deny,
514                    ..record
515                };
516                let _ = sink.record(&deny_record);
517                Err(GrantError::AuditUnavailable)
518            } else {
519                tracing::error!(
520                    "MAC grant-path audit write failed on a Deny decision (deny still enforced)"
521                );
522                result.clone()
523            }
524        }
525    }
526}
527
528/// Resolve the S1 `SecurityContext` for a UCAN grant's audience from a
529/// `SubjectContextClaims` implementation.
530///
531/// This is the seam between "the UCAN names an audience DID" and "the S1
532/// clearance floor needs a verified subject context". The caller resolves the
533/// audience DID to whatever claims object it has (envelope claims, registered
534/// subject, …) implementing `SubjectContextClaims`, plus the assurance derived
535/// from the verified key material. Returns `None` for an unlabeled subject —
536/// which [`evaluate_grant`] maps to [`GrantError::UnlabeledSubject`].
537///
538/// S6 does not invent clearance: it only forwards what the claims layer
539/// already provides (S1 contract). The concrete `clearance` field on `Claims`
540/// lands with S8 (#574); until then implementors test against a stub claims
541/// object, exactly as S1/S2 do.
542pub fn subject_context(
543    claims: &dyn SubjectContextClaims,
544    key_material: VerifiedKeyMaterial,
545) -> Option<SecurityContext> {
546    claims.security_context(key_material)
547}
548
549// A small helper kept private so the public surface stays minimal: the
550// reference decision used by tests to cross-check the compiler path. Not part
551// of the contract.
552#[cfg(test)]
553fn reference_authorize(grant: &[Capability], request: &AccessRequest) -> Decision {
554    crate::mac::compiler::authorize(grant, request)
555}
556
557#[cfg(test)]
558#[allow(clippy::unwrap_used)]
559mod tests {
560    //! S6 negative tests + the happy path. No test asserts permissive behaviour:
561    //! every case either confirms a correct minimal mint or confirms a denial.
562    //! The denial cases are the security load — over-ceiling, bad chain,
563    //! insufficient clearance, missing DPoP.
564    use super::*;
565    use crate::mac::te::Decision;
566    use ed25519_dalek::{SigningKey, VerifyingKey};
567    use hyprstream_rpc::auth::mac::{
568        Assurance, CompartmentSet, Level, SecurityLabel, VerifiedKeyMaterial,
569    };
570    use hyprstream_rpc::auth::ucan::capability::{Ability, Capability, Resource};
571    use hyprstream_rpc::auth::ucan::token::{
572        Did, Ucan, UcanError, UcanPayload, UcanVerifier, UCAN_AAD,
573    };
574    use hyprstream_rpc::crypto::cose_sign::{sign_composite, verify_composite};
575    use hyprstream_rpc::crypto::pq::{ml_dsa_generate_keypair, MlDsaSigningKey, MlDsaVerifyingKey};
576    use std::collections::HashMap;
577
578    // UCAN payload-signature AAD is the public `hyprstream_rpc::auth::ucan::token::UCAN_AAD`
579    // constant (S8 promoted it so production verifiers and tests share the exact bytes).
580
581    /// Trusted `now` inside every test UCAN's validity window
582    /// (`not_before: None`, `expiration: 9_999_999_999`).
583    const NOW: u64 = 1_000;
584
585    /// A hybrid keypair (Ed25519 + ML-DSA-65) for one DID, mirroring S5's
586    /// `TestIdentity` but built here on public APIs so S6 tests do not depend on
587    /// S5's `pub(super)` test_support.
588    struct Identity {
589        ed_sk: SigningKey,
590        ed_vk: VerifyingKey,
591        pq_sk: MlDsaSigningKey,
592        pq_vk: MlDsaVerifyingKey,
593    }
594
595    impl Identity {
596        fn generate() -> Self {
597            use rand::rngs::OsRng;
598            let ed_sk = SigningKey::generate(&mut OsRng);
599            let ed_vk = ed_sk.verifying_key();
600            let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
601            Self {
602                ed_sk,
603                ed_vk,
604                pq_sk,
605                pq_vk,
606            }
607        }
608
609        fn did(&self) -> Did {
610            Did::from_ed25519(&self.ed_vk.to_bytes())
611        }
612    }
613
614    /// A trust store keyed by DID string → anchored ML-DSA-65 verifying key,
615    /// implementing `UcanVerifier` over the real hybrid composite verify. Mirrors
616    /// S5's `TestTrustStore`.
617    struct TrustStore {
618        pq_by_did: HashMap<String, MlDsaVerifyingKey>,
619    }
620
621    impl TrustStore {
622        fn new() -> Self {
623            Self {
624                pq_by_did: HashMap::new(),
625            }
626        }
627        fn anchor(&mut self, id: &Identity) {
628            self.pq_by_did
629                .insert(id.did().into_string(), id.pq_vk.clone());
630        }
631    }
632
633    impl UcanVerifier for TrustStore {
634        fn verify(
635            &self,
636            issuer: &Did,
637            ed_key: &[u8; 32],
638            payload: &[u8],
639            signature: &[u8],
640        ) -> Result<(), UcanError> {
641            let ed_vk = VerifyingKey::from_bytes(ed_key)
642                .map_err(|e| UcanError::BadSignature(e.to_string()))?;
643            let pq_vk = self.pq_by_did.get(issuer.as_str());
644            verify_composite(signature, &ed_vk, pq_vk, payload, UCAN_AAD, true)
645                .map(|_| ())
646                .map_err(|e| UcanError::BadSignature(e.to_string()))
647        }
648    }
649
650    /// Build and hybrid-sign a UCAN from `issuer` to `audience` with `caps` and
651    /// `proofs`. Mirrors S5's `signed_ucan` helper.
652    fn signed_ucan(
653        issuer: &Identity,
654        audience: &Did,
655        caps: Vec<Capability>,
656        proofs: Vec<Ucan>,
657    ) -> Ucan {
658        let payload = UcanPayload {
659            issuer: issuer.did(),
660            audience: audience.clone(),
661            capabilities: caps,
662            not_before: None,
663            expiration: Some(9_999_999_999),
664            nonce: vec![1, 2, 3],
665        };
666        let bytes = payload.signing_bytes().unwrap();
667        let signature =
668            sign_composite(&issuer.ed_sk, Some(&issuer.pq_sk), &bytes, UCAN_AAD).unwrap();
669        Ucan {
670            payload,
671            proofs,
672            signature,
673        }
674    }
675
676    fn cap(resource: &str, ability: &str) -> Capability {
677        Capability::new(Resource::new(resource), Ability::new(ability))
678    }
679
680    /// A compartment bitset from bit indices.
681    fn comps(bits: &[u32]) -> CompartmentSet {
682        bits.iter().copied().collect()
683    }
684
685    /// A subject cleared to (Secret, PqHybrid, {0,1}) — dominates most test
686    /// object labels. Built with PqHybrid key material so assurance is not the
687    /// binding constraint.
688    fn cleared_subject() -> SecurityContext {
689        SecurityContext::new(Level::Secret, comps(&[0, 1]), VerifiedKeyMaterial::PqHybrid)
690    }
691
692    fn req(resource: &str, ability: &str, label: SecurityLabel) -> GrantRequest {
693        GrantRequest {
694            resource: Resource::new(resource),
695            ability: Ability::new(ability),
696            caveats: Caveats::default(),
697            audience: None,
698            object_label: Some(label),
699        }
700    }
701
702    /// A single-capability self-issued root UCAN granting `cap`, hybrid-signed,
703    /// plus a trust store anchoring its PQ key.
704    fn root_grant(cap: Capability) -> (Ucan, TrustStore) {
705        let id = Identity::generate();
706        let u = signed_ucan(&id, &id.did(), vec![cap], vec![]);
707        let mut s = TrustStore::new();
708        s.anchor(&id);
709        (u, s)
710    }
711
712    // ── Happy path: subset within ceiling, cleared, sender-bound ────────────
713
714    #[test]
715    fn subset_within_ceiling_permits_minimal_mint() {
716        // Grant: mac://model/* / model/*. Request: mac://model/qwen / model/read
717        // — a strict subset. Subject cleared, DPoP present, object at a label
718        // the subject dominates.
719        let (grant, store) = root_grant(cap("mac://model/*", "model/*"));
720        let object_label =
721            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
722        let request = req("mac://model/qwen", "model/read", object_label);
723
724        let decision = match evaluate_grant(
725            &grant,
726            &store,
727            NOW,
728            &request,
729            Some(&cleared_subject()),
730            true, // sender-bound
731        ) {
732            Ok(d) => d,
733            Err(e) => {
734                panic!("a strict subset of a valid grant, cleared + bound, must permit: {e:?}")
735            }
736        };
737
738        let granted = match decision {
739            GrantDecision::Permit(g) => g,
740            other => panic!("expected Permit, got {other:?}"),
741        };
742        // ZSP: the minted capability is the REQUESTED subset, not the grant.
743        assert_eq!(
744            granted.capability.resource,
745            Resource::new("mac://model/qwen")
746        );
747        assert_eq!(granted.capability.ability, Ability::new("model/read"));
748        // Cross-check: the reference compiler decision agrees (no parallel impl).
749        assert_eq!(
750            reference_authorize(
751                grant.capabilities(),
752                &AccessRequest {
753                    resource: request.resource.clone(),
754                    ability: request.ability.clone(),
755                    caveats: request.caveats.clone(),
756                }
757            ),
758            Decision::Permit
759        );
760    }
761
762    // ── Fail-closed: over-ceiling (escalation) ──────────────────────────────
763
764    #[test]
765    fn over_ceiling_request_is_denied_not_escalated() {
766        // Grant: mac://model/qwen only. Request: mac://model/* (wider resource)
767        // — widening past the ceiling. Must deny; must NOT auto-mint the
768        // requested wider capability.
769        let (grant, store) = root_grant(cap("mac://model/qwen", "model/read"));
770        let object_label =
771            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
772        let request = req("mac://model/*", "model/read", object_label);
773
774        let outcome = evaluate_grant(
775            &grant,
776            &store,
777            NOW,
778            &request,
779            Some(&cleared_subject()),
780            true,
781        );
782        match outcome {
783            Err(GrantError::OverCeiling { .. }) => {}
784            other => panic!("expected OverCeiling denial, got {other:?}"),
785        }
786    }
787
788    #[test]
789    fn over_ceiling_on_ability_is_denied() {
790        // Grant: model/read. Request: model/write — wider ability. Deny.
791        let (grant, store) = root_grant(cap("mac://model/qwen", "model/read"));
792        let object_label =
793            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
794        let request = req("mac://model/qwen", "model/write", object_label);
795
796        assert!(matches!(
797            evaluate_grant(
798                &grant,
799                &store,
800                NOW,
801                &request,
802                Some(&cleared_subject()),
803                true
804            ),
805            Err(GrantError::OverCeiling { .. })
806        ));
807    }
808
809    // ── Fail-closed: bad chain ──────────────────────────────────────────────
810
811    #[test]
812    fn broken_signature_is_denied() {
813        // Tamper the grant's signature → S5 chain validation fails → S6 denies.
814        let (mut grant, store) = root_grant(cap("mac://model/*", "model/*"));
815        grant.signature[0] ^= 0xFF; // break the hybrid signature
816        let object_label =
817            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
818        let request = req("mac://model/qwen", "model/read", object_label);
819
820        match evaluate_grant(
821            &grant,
822            &store,
823            NOW,
824            &request,
825            Some(&cleared_subject()),
826            true,
827        ) {
828            Err(GrantError::Chain(_)) => {}
829            other => panic!("expected Chain denial on bad signature, got {other:?}"),
830        }
831    }
832
833    #[test]
834    fn widening_chain_is_denied() {
835        // A 2-link chain where the delegate widens past its delegator — S5
836        // rejects the chain; S6 must surface that as a Chain denial (NOT a
837        // ceiling check, because the chain never validated).
838        let root = Identity::generate();
839        let alice = Identity::generate();
840        let root_ucan = signed_ucan(
841            &root,
842            &alice.did(),
843            vec![cap("mac://model/*", "model/read")],
844            vec![],
845        );
846        // alice widens: claims mac://other/* past root's mac://model/*.
847        let alice_ucan = signed_ucan(
848            &alice,
849            &alice.did(),
850            vec![cap("mac://other/*", "model/*")],
851            vec![root_ucan],
852        );
853        let mut store = TrustStore::new();
854        store.anchor(&root);
855        store.anchor(&alice);
856
857        let object_label =
858            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
859        let request = req("mac://other/x", "model/read", object_label);
860
861        match evaluate_grant(
862            &alice_ucan,
863            &store,
864            NOW,
865            &request,
866            Some(&cleared_subject()),
867            true,
868        ) {
869            Err(GrantError::Chain(ChainError::Widening { .. })) => {}
870            other => panic!("expected Chain::Widening denial, got {other:?}"),
871        }
872    }
873
874    #[test]
875    fn expired_grant_is_denied() {
876        // A grant that has expired at now=2000. S5's absolute-time gate denies;
877        // S6 surfaces it as a Chain::Expired denial.
878        let id = Identity::generate();
879        let payload = UcanPayload {
880            issuer: id.did(),
881            audience: id.did(),
882            capabilities: vec![cap("mac://model/*", "model/*")],
883            not_before: None,
884            expiration: Some(500), // expired well before now=2000
885            nonce: vec![],
886        };
887        let bytes = payload.signing_bytes().unwrap();
888        let signature = sign_composite(&id.ed_sk, Some(&id.pq_sk), &bytes, UCAN_AAD).unwrap();
889        let grant = Ucan {
890            payload,
891            proofs: vec![],
892            signature,
893        };
894        let mut store = TrustStore::new();
895        store.anchor(&id);
896
897        let object_label =
898            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
899        let request = req("mac://model/qwen", "model/read", object_label);
900
901        match evaluate_grant(
902            &grant,
903            &store,
904            2000,
905            &request,
906            Some(&cleared_subject()),
907            true,
908        ) {
909            Err(GrantError::Chain(ChainError::Expired { .. })) => {}
910            other => panic!("expected Chain::Expired denial, got {other:?}"),
911        }
912    }
913
914    // ── Fail-closed: insufficient MAC clearance ─────────────────────────────
915
916    #[test]
917    fn insufficient_clearance_is_denied() {
918        // Grant valid for the request, but the object label requires a
919        // compartment (bit 5) the subject is NOT cleared into. The S1 floor
920        // denies independently of the ceiling.
921        let (grant, store) = root_grant(cap("mac://model/*", "model/*"));
922        // Object at {Confidential, PqHybrid, {5}} — subject only has {0,1}.
923        let object_label =
924            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[5]));
925        let request = req("mac://model/qwen", "model/read", object_label);
926
927        match evaluate_grant(
928            &grant,
929            &store,
930            NOW,
931            &request,
932            Some(&cleared_subject()),
933            true,
934        ) {
935            Err(GrantError::InsufficientClearance) => {}
936            other => panic!("expected InsufficientClearance denial, got {other:?}"),
937        }
938    }
939
940    #[test]
941    fn classical_subject_denied_on_pq_object() {
942        // #548 end-to-end at the grant path: an object labeled PqHybrid is
943        // unreachable by a Classical-assurance subject via the SAME dominance
944        // check — no separate path.
945        let (grant, store) = root_grant(cap("mac://model/*", "model/*"));
946        let object_label =
947            SecurityLabel::new(Level::Public, Assurance::PqHybrid, CompartmentSet::EMPTY);
948        let request = req("mac://model/qwen", "model/read", object_label);
949        // Classical subject (cleared high in level, but Classical assurance).
950        let classical = SecurityContext::new(
951            Level::Secret,
952            comps(&[0, 1]),
953            VerifiedKeyMaterial::Classical,
954        );
955
956        assert!(matches!(
957            evaluate_grant(&grant, &store, NOW, &request, Some(&classical), true),
958            Err(GrantError::InsufficientClearance)
959        ));
960    }
961
962    // ── Fail-closed: missing sender-binding (ZSP) ───────────────────────────
963
964    #[test]
965    fn missing_sender_binding_is_denied() {
966        // A request that would otherwise permit, but with no DPoP proof. ZSP:
967        // the minted token MUST be sender-bound. Deny before any other gate.
968        let (grant, store) = root_grant(cap("mac://model/*", "model/*"));
969        let object_label =
970            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
971        let request = req("mac://model/qwen", "model/read", object_label);
972
973        match evaluate_grant(
974            &grant,
975            &store,
976            NOW,
977            &request,
978            Some(&cleared_subject()),
979            false, // no sender-binding
980        ) {
981            Err(GrantError::MissingSenderBinding) => {}
982            other => panic!("expected MissingSenderBinding denial, got {other:?}"),
983        }
984    }
985
986    // ── Fail-closed: unlabeled subject / object, empty grant ────────────────
987
988    #[test]
989    fn unlabeled_subject_is_denied() {
990        let (grant, store) = root_grant(cap("mac://model/*", "model/*"));
991        let object_label =
992            SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY);
993        let request = req("mac://model/qwen", "model/read", object_label);
994
995        // No subject context at all.
996        assert!(matches!(
997            evaluate_grant(&grant, &store, NOW, &request, None, true),
998            Err(GrantError::UnlabeledSubject)
999        ));
1000    }
1001
1002    #[test]
1003    fn unlabeled_object_is_denied() {
1004        let (grant, store) = root_grant(cap("mac://model/*", "model/*"));
1005        // No object label supplied ⇒ the S1 floor cannot be evaluated ⇒ deny.
1006        let request = GrantRequest {
1007            resource: Resource::new("mac://model/qwen"),
1008            ability: Ability::new("model/read"),
1009            caveats: Caveats::default(),
1010            audience: None,
1011            object_label: None,
1012        };
1013
1014        assert!(matches!(
1015            evaluate_grant(
1016                &grant,
1017                &store,
1018                NOW,
1019                &request,
1020                Some(&cleared_subject()),
1021                true
1022            ),
1023            Err(GrantError::InsufficientClearance)
1024        ));
1025    }
1026
1027    #[test]
1028    fn empty_grant_is_denied() {
1029        // A self-issued root with NO capabilities — an empty ceiling.
1030        let id = Identity::generate();
1031        let empty = signed_ucan(&id, &id.did(), vec![], vec![]);
1032        let mut store = TrustStore::new();
1033        store.anchor(&id);
1034
1035        let object_label =
1036            SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY);
1037        let request = req("mac://x", "y", object_label);
1038
1039        assert!(matches!(
1040            evaluate_grant(
1041                &empty,
1042                &store,
1043                NOW,
1044                &request,
1045                Some(&cleared_subject()),
1046                true
1047            ),
1048            Err(GrantError::EmptyGrant)
1049        ));
1050    }
1051
1052    // ── Caveat subset honoured (more-restrictive request is still a subset) ──
1053
1054    #[test]
1055    fn caveat_added_in_request_still_subset() {
1056        // Grant: mac://model/* / * with tenant=acme caveat. Request: same but
1057        // ALSO adds a max=5 caveat (more restricted) ⇒ still attenuates.
1058        use hyprstream_rpc::auth::ucan::capability::CaveatValue;
1059        use std::collections::BTreeMap;
1060        let mut g_caveats = BTreeMap::new();
1061        g_caveats.insert("tenant".to_owned(), CaveatValue::Text("acme".to_owned()));
1062        let cap_with_caveat = Capability::with_caveats(
1063            Resource::new("mac://model/*"),
1064            Ability::new("model/*"),
1065            Caveats(g_caveats),
1066        );
1067        let (grant, store) = root_grant(cap_with_caveat);
1068
1069        let mut r_caveats = BTreeMap::new();
1070        r_caveats.insert("tenant".to_owned(), CaveatValue::Text("acme".to_owned()));
1071        r_caveats.insert("max".to_owned(), CaveatValue::Int(5));
1072        let object_label =
1073            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
1074        let request = GrantRequest {
1075            resource: Resource::new("mac://model/qwen"),
1076            ability: Ability::new("model/read"),
1077            caveats: Caveats(r_caveats),
1078            audience: None,
1079            object_label: Some(object_label),
1080        };
1081
1082        assert!(matches!(
1083            evaluate_grant(
1084                &grant,
1085                &store,
1086                NOW,
1087                &request,
1088                Some(&cleared_subject()),
1089                true
1090            ),
1091            Ok(GrantDecision::Permit(_))
1092        ));
1093    }
1094
1095    #[test]
1096    fn caveat_dropped_in_request_is_over_ceiling() {
1097        // Grant has tenant=acme; request drops it ⇒ widening on caveats ⇒ deny.
1098        use hyprstream_rpc::auth::ucan::capability::CaveatValue;
1099        use std::collections::BTreeMap;
1100        let mut g_caveats = BTreeMap::new();
1101        g_caveats.insert("tenant".to_owned(), CaveatValue::Text("acme".to_owned()));
1102        let cap_with_caveat = Capability::with_caveats(
1103            Resource::new("mac://model/*"),
1104            Ability::new("model/*"),
1105            Caveats(g_caveats),
1106        );
1107        let (grant, store) = root_grant(cap_with_caveat);
1108
1109        let object_label =
1110            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
1111        // Request has NO caveats — drops tenant ⇒ over-ceiling.
1112        let request = req("mac://model/qwen", "model/read", object_label);
1113
1114        assert!(matches!(
1115            evaluate_grant(
1116                &grant,
1117                &store,
1118                NOW,
1119                &request,
1120                Some(&cleared_subject()),
1121                true
1122            ),
1123            Err(GrantError::OverCeiling { .. })
1124        ));
1125    }
1126
1127    // ── Refresh is the same gate (ZSP: no weaker path) ─────────────────────
1128
1129    #[test]
1130    fn refresh_runs_the_same_gates_as_mint() {
1131        let (grant, store) = root_grant(cap("mac://model/*", "model/*"));
1132        let object_label =
1133            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
1134        let request = req("mac://model/qwen", "model/read", object_label);
1135
1136        let mint = evaluate_grant(
1137            &grant,
1138            &store,
1139            NOW,
1140            &request,
1141            Some(&cleared_subject()),
1142            true,
1143        );
1144        let refresh = evaluate_refresh(
1145            &grant,
1146            &store,
1147            NOW,
1148            &request,
1149            Some(&cleared_subject()),
1150            true,
1151        );
1152        assert_eq!(format!("{mint:?}"), format!("{refresh:?}"));
1153
1154        // And refresh denies on a missing binding just like mint.
1155        assert!(matches!(
1156            evaluate_refresh(
1157                &grant,
1158                &store,
1159                NOW,
1160                &request,
1161                Some(&cleared_subject()),
1162                false
1163            ),
1164            Err(GrantError::MissingSenderBinding)
1165        ));
1166    }
1167
1168    // ── B2 (#674): the audited grant path ───────────────────────────────────
1169
1170    /// An in-memory sink that records every [`crate::mac::audit::AuditRecord`]
1171    /// it's given, or can be told to fail the next `record` call (to exercise
1172    /// the fail-closed-on-audit-failure path without a real `WalAuditStore`).
1173    struct SpySink {
1174        records: parking_lot::Mutex<Vec<crate::mac::audit::AuditRecord>>,
1175        fail_next: std::sync::atomic::AtomicBool,
1176    }
1177    impl SpySink {
1178        fn new() -> Self {
1179            Self {
1180                records: parking_lot::Mutex::new(Vec::new()),
1181                fail_next: std::sync::atomic::AtomicBool::new(false),
1182            }
1183        }
1184        fn fail_next_write(&self) {
1185            self.fail_next
1186                .store(true, std::sync::atomic::Ordering::SeqCst);
1187        }
1188        fn records(&self) -> Vec<crate::mac::audit::AuditRecord> {
1189            self.records.lock().clone()
1190        }
1191    }
1192    impl crate::mac::audit::AuditSink for SpySink {
1193        fn record(
1194            &self,
1195            record: &crate::mac::audit::AuditRecord,
1196        ) -> Result<(), crate::mac::audit::AuditError> {
1197            if self
1198                .fail_next
1199                .swap(false, std::sync::atomic::Ordering::SeqCst)
1200            {
1201                return Err(crate::mac::audit::AuditError::Io("injected failure".into()));
1202            }
1203            self.records.lock().push(record.clone());
1204            Ok(())
1205        }
1206    }
1207
1208    /// A permit is audited (exactly one `Permit` record, with the grant-path
1209    /// sentinel ids) and the token still mints — auditing must not itself
1210    /// deny a decision the gates approved.
1211    #[test]
1212    fn audited_permit_is_recorded_and_still_mints() {
1213        let (grant, store) = root_grant(cap("mac://model/*", "model/read"));
1214        let object_label =
1215            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
1216        let request = req("mac://model/qwen", "model/read", object_label);
1217        let sink = SpySink::new();
1218
1219        let decision = audited_evaluate_grant(
1220            &grant,
1221            &store,
1222            NOW,
1223            &request,
1224            Some(&cleared_subject()),
1225            None, // no delegator — single-principal (self-issued) grant
1226            true,
1227            &sink,
1228        );
1229        assert!(
1230            matches!(decision, Ok(GrantDecision::Permit(_))),
1231            "an honest permit must still mint under audit: {decision:?}"
1232        );
1233
1234        let recs = sink.records();
1235        assert_eq!(recs.len(), 1, "exactly one record per decision");
1236        assert_eq!(recs[0].decision, crate::mac::te::Decision::Permit);
1237        assert_eq!(recs[0].reason, crate::mac::audit::DecisionReason::Permit);
1238        assert_eq!(recs[0].subject_type, crate::mac::te::GRANT_PATH_SUBJECT);
1239        assert_eq!(recs[0].object_type, crate::mac::te::GRANT_PATH_OBJECT);
1240        // Single-principal grant ⇒ no delegator recorded (#680/#681).
1241        assert!(
1242            recs[0].on_behalf_of.is_none(),
1243            "a self-issued grant records no delegator"
1244        );
1245    }
1246
1247    /// #680/#681: a delegated grant records the DELEGATOR on the audit record's
1248    /// `on_behalf_of`, distinct from the effective (met) `subject_clearance` the
1249    /// gates evaluated — so the audit trail names both principals of a delegated
1250    /// decision (the user-attribution #445 asks for), not just the actor.
1251    #[test]
1252    fn delegated_grant_records_delegator_as_on_behalf_of() {
1253        let (grant, store) = root_grant(cap("mac://model/*", "model/read"));
1254        let object_label =
1255            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
1256        let request = req("mac://model/qwen", "model/read", object_label);
1257        let sink = SpySink::new();
1258
1259        // The delegator (authority source): a DISTINCT clearance from the met
1260        // subject (`cleared_subject` is Secret/{0,1}), so the record must not
1261        // conflate the two.
1262        let delegator = SecurityContext::new(
1263            Level::Secret,
1264            comps(&[0, 1, 2]),
1265            VerifiedKeyMaterial::PqHybrid,
1266        );
1267
1268        let decision = audited_evaluate_grant(
1269            &grant,
1270            &store,
1271            NOW,
1272            &request,
1273            Some(&cleared_subject()), // met context the gates evaluate
1274            Some(&delegator),         // delegator, for two-principal audit
1275            true,
1276            &sink,
1277        );
1278        assert!(matches!(decision, Ok(GrantDecision::Permit(_))));
1279
1280        let recs = sink.records();
1281        assert_eq!(recs.len(), 1);
1282        // A delegated grant records its delegator.
1283        let obo = recs[0].on_behalf_of.unwrap();
1284        assert_eq!(
1285            obo.subject_clearance,
1286            *delegator.clearance(),
1287            "on_behalf_of carries the delegator's own clearance"
1288        );
1289        assert_ne!(
1290            obo.subject_clearance, recs[0].subject_clearance,
1291            "delegator (on_behalf_of) is distinct from the met subject clearance"
1292        );
1293        assert_eq!(obo.subject_type, crate::mac::te::GRANT_PATH_SUBJECT);
1294    }
1295
1296    /// The core #674 obligation: a would-be Permit that CANNOT be durably
1297    /// audited must be downgraded to a deny (`AuditUnavailable`), never handed
1298    /// back as a Permit — mirroring `AuditedAvc`'s fail-closed rule at the TE
1299    /// path. Also asserts the resulting deny record IS still attempted/audited.
1300    #[test]
1301    fn permit_downgrades_to_deny_when_audit_write_fails() {
1302        let (grant, store) = root_grant(cap("mac://model/*", "model/read"));
1303        let object_label =
1304            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
1305        let request = req("mac://model/qwen", "model/read", object_label);
1306        let sink = SpySink::new();
1307        sink.fail_next_write(); // the Permit's own audit write will fail
1308
1309        let decision = audited_evaluate_grant(
1310            &grant,
1311            &store,
1312            NOW,
1313            &request,
1314            Some(&cleared_subject()),
1315            None, // no delegator — single-principal (self-issued) grant
1316            true,
1317            &sink,
1318        );
1319        assert!(
1320            matches!(decision, Err(GrantError::AuditUnavailable)),
1321            "an unauditable permit must be downgraded, got {decision:?}"
1322        );
1323        // The fallback deny record was itself recorded (best-effort, per the
1324        // AuditedAvc precedent) — the second `record` call, which SpySink
1325        // allows since only the first was told to fail.
1326        let recs = sink.records();
1327        assert_eq!(recs.len(), 1, "the downgraded deny is recorded");
1328        assert_eq!(recs[0].decision, crate::mac::te::Decision::Deny);
1329        assert_eq!(
1330            recs[0].reason,
1331            crate::mac::audit::DecisionReason::GrantAuditFailClosed
1332        );
1333    }
1334
1335    /// A denial that cannot be audited is still enforced as a deny (auditing
1336    /// failure never WEAKENS a decision — only a would-be Permit is affected).
1337    #[test]
1338    fn deny_stays_deny_when_audit_write_fails() {
1339        let (grant, store) = root_grant(cap("mac://model/*", "model/read"));
1340        // Missing object label ⇒ InsufficientClearance (gate 4), independent of
1341        // the audit sink.
1342        let request = GrantRequest {
1343            resource: Resource::new("mac://model/qwen"),
1344            ability: Ability::new("model/read"),
1345            caveats: Caveats::default(),
1346            audience: None,
1347            object_label: None,
1348        };
1349        let sink = SpySink::new();
1350        sink.fail_next_write();
1351
1352        let decision = audited_evaluate_grant(
1353            &grant,
1354            &store,
1355            NOW,
1356            &request,
1357            Some(&cleared_subject()),
1358            None, // no delegator — single-principal (self-issued) grant
1359            true,
1360            &sink,
1361        );
1362        assert!(
1363            matches!(decision, Err(GrantError::InsufficientClearance)),
1364            "a deny must be enforced as decided even if its audit write fails: {decision:?}"
1365        );
1366        // The (failed) attempt leaves no record — asserting we don't silently
1367        // fabricate one; the failure was logged instead (see tracing::error!).
1368        assert!(sink.records().is_empty());
1369    }
1370
1371    /// An unrecognized ability (doesn't parse as a canonical `ScopeAction`)
1372    /// still produces a well-formed audit record — using the sentinel
1373    /// `ACTION_UNRECOGNIZED` id rather than dropping the record. Diagnosable,
1374    /// not silently lost.
1375    #[test]
1376    fn unparseable_ability_still_produces_a_diagnosable_record() {
1377        let (grant, store) = root_grant(cap("mac://model/*", "totally-not-a-verb"));
1378        let object_label =
1379            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
1380        let request = req("mac://model/qwen", "totally-not-a-verb", object_label);
1381        let sink = SpySink::new();
1382
1383        // The grant will actually Permit (the capability's ability string
1384        // matches verbatim), but the ability is not a canonical ScopeAction —
1385        // exercising the ACTION_UNRECOGNIZED fallback on a real decision.
1386        let _ = audited_evaluate_grant(
1387            &grant,
1388            &store,
1389            NOW,
1390            &request,
1391            Some(&cleared_subject()),
1392            None, // no delegator — single-principal (self-issued) grant
1393            true,
1394            &sink,
1395        );
1396        let recs = sink.records();
1397        assert_eq!(recs.len(), 1);
1398        assert_eq!(recs[0].action, crate::mac::te::ACTION_UNRECOGNIZED);
1399    }
1400
1401    /// `audited_evaluate_refresh` audits identically to
1402    /// `audited_evaluate_grant` (same gate chain, same record shape) — the
1403    /// refresh path is not a quieter/less-audited sibling.
1404    #[test]
1405    fn audited_refresh_is_recorded_the_same_way() {
1406        let (grant, store) = root_grant(cap("mac://model/*", "model/read"));
1407        let object_label =
1408            SecurityLabel::new(Level::Confidential, Assurance::PqHybrid, comps(&[0]));
1409        let request = req("mac://model/qwen", "model/read", object_label);
1410        let sink = SpySink::new();
1411
1412        let decision = audited_evaluate_refresh(
1413            &grant,
1414            &store,
1415            NOW,
1416            &request,
1417            Some(&cleared_subject()),
1418            None, // no delegator — single-principal (self-issued) grant
1419            true,
1420            &sink,
1421        );
1422        assert!(matches!(decision, Ok(GrantDecision::Permit(_))));
1423        assert_eq!(sink.records().len(), 1);
1424    }
1425}