hyprstream_core/mac/mod.rs
1//! Mandatory Access Control — the **Policy Decision Point** (PDP) for the 9P/VFS surface.
2//!
3//! This is ticket **S4 (#570)** of the native-MAC security epic (#547): the data-plane
4//! authorization engine. It implements, against an assumed S1 lattice interface:
5//!
6//! - [`lattice`] — a thin **re-export of S1's canonical types** (#567): the structured
7//! `SecurityLabel` (Level × Assurance × CompartmentSet, `Copy + Ord + Hash`, no `Default`),
8//! the `Lattice` *policy object* (closed compartment name↔bit vocabulary, versioned), and
9//! `SecurityContext`. Dominance/join are INTRINSIC to the label, not trait methods — the
10//! PDP floor calls them directly. (The original S4 stub lattice was deleted at
11//! reconciliation; see the `lattice` module docs.)
12//! - [`te`] — the **type-enforcement evaluator**: a TOTAL, default-deny
13//! `(subject_ctx, object_label, action) → Decision` over the compiled TE matrix AND the
14//! independent lattice floor. Small + verifiable. This is the PDP core.
15//! - [`avc`] — the **Access Vector Cache**: the fast local decision cache the PEP (S2) calls
16//! per op. Sub-µs hits (hash lookup, no Casbin, no signature verify, no lattice walk on a
17//! hit). Defines how an OAuth access token maps to a cached decision (token = distributed
18//! AVC entry).
19//! - [`compiled`] — **compiled-policy distribution + signing**: PolicyService hashes + signs
20//! the TE matrix (hybrid EdDSA + ML-DSA-65 COSE composite); the loader rejects any
21//! unsigned/mismatched/unapproved policy. Verification happens ONCE at load, never per op.
22//!
23//! ## The control-plane / data-plane split (be explicit)
24//!
25//! ```text
26//! CONTROL PLANE (authoring / compilation store) DATA PLANE (per-op enforcement)
27//! ───────────────────────────────────────────── ───────────────────────────────────
28//! UCAN the grant/delegation source
29//! Casbin Enforcer policy STORE + AUTHORING ── NEVER on the per-op hot path ──
30//! (auth::policy_manager::PolicyManager)
31//! S5 UCAN→TE compiler lowers Casbin/UCAN → matrix──► TeMatrix (compiled object code)
32//! PolicyService compiles + SIGNS policy ─────► compiled::SignedPolicy
33//! │ loader verifies ONCE
34//! ▼
35//! te::LatticeTeEvaluator (the PDP)
36//! avc::CachingAvc (the cache)
37//! ▲ PEP (S2) calls per op
38//! ```
39//!
40//! **Casbin stays control-plane.** The existing `casbin::Enforcer` in
41//! [`crate::auth::policy_manager::PolicyManager`] remains the policy store and authoring
42//! surface (RBAC/ABAC string matching, templates, `add_policy`/`apply_template`). Its
43//! `enforce()` string-matcher is **never** invoked per op — that would blow the latency
44//! budget and enlarge the TCB. Instead, S5's compiler lowers the authored policy into the
45//! compact [`te::TeMatrix`] (interned-id allow-set, O(1) lookup), which this PDP evaluates.
46//! The mandatory lattice floor is **independent of Casbin entirely** (design §5a: "the
47//! lattice is NOT encoded in Casbin").
48//!
49//! ## TCB note
50//!
51//! The per-op TCB is intentionally tiny: a hash lookup ([`avc`]), and on a miss a set lookup
52//! plus one intrinsic `SecurityLabel::can_access` call ([`te`]). All heavy/bug-prone logic
53//! (Casbin matching,
54//! UCAN chain validation, compilation, signature verification) is concentrated off the hot
55//! path — in PolicyService and the [`compiled`] loader, the one audited place (design §2).
56
57pub mod audit;
58pub mod avc;
59// S4 (#570): the daemon-boot compile → sign → verify-load → install path that
60// finally populates `COMPILED_POLICY`.
61pub mod bootload;
62pub mod compiled;
63pub mod compiler;
64// S6 (#572): runtime grant path — UCAN grant-request → access/refresh tokens.
65// Pure fail-closed core: grant validation + ceiling-subset + MAC clearance +
66// sender-binding, consuming S1/S5/the compiler rather than re-implementing.
67pub mod exchange;
68// S1 activation (#567): production genesis CONTENT + enumerator + composite
69// ObjectLabelResolver + boot-time coverage gate consumed by the active 9P PEP.
70pub mod genesis;
71// #1499: typed RPC dispatch labels — the declared (service, leaf/method)
72// object identity and deliberate service subject clearance the mandatory
73// dispatch PEP evaluates. Bare service domains never route through the VFS
74// object-label adapter.
75pub mod dispatch_labels;
76// #698 Phase 2: durable append-only enrollment-intent journal — provisioning
77// hooks record intent here; the offline reconciler folds intents into
78// unsigned reviewed inputs for the `trust sign-mac-boot-policy` ceremony.
79pub mod enrollment_journal;
80pub mod enrollment_reconcile;
81mod generated_dispatch;
82pub mod lattice;
83pub mod moq_audit;
84// #1319: audited MAC adapter at the tenant account-record read boundary.
85pub mod pds_pep;
86// #676: the production S3-scope ↔ S5-TE-rule vocabulary (injective + exact;
87// wildcards expand at compile time over a closed registry).
88// #1270: CAS-native MAC PEP — trusted content-bound label at seal +
89// can_access enforcement on ingest/read (epic #1267 T3).
90pub mod cas_pep;
91pub mod pep;
92pub mod permission_map;
93// #1273 (epic #1267): the reviewed public/declassifier exemption registry —
94// the explicit, pinned set of HTTP routes intentionally unmediated by native
95// MAC. Public routers derive from this so a new route must be added here (and
96// to the drift test) in the same reviewed PR.
97pub mod public_exemptions;
98pub mod te;
99
100// Re-export the per-op contract surface S2 (PEP) and S5/S6 (policy producers) consume.
101pub use avc::{Avc, AvcKey, CachingAvc, TokenScope};
102// S7 (#573): tamper-evident audit of every authorization decision + OTel fan-out.
103pub use audit::{
104 audit_signing_input, AuditError, AuditRecord, AuditSigner, AuditSink, AuditVerifier,
105 AuditedAvc, DecisionReason, NullAuditSink, WalAuditStore,
106};
107pub use compiled::{
108 sign_policy, CompiledPolicy, PolicyApproval, PolicyDistError, PolicyLoader, PolicySigner,
109 PolicyVerifier, SignedPolicy,
110};
111// Lattice surface is now S1's canonical types (#567), re-exported through `lattice` so the
112// PDP has one import path. `ifc_join` is the local forwarder over the intrinsic join.
113pub use lattice::{
114 ifc_join, Assurance, Compartment, CompartmentSet, LabelError, Lattice, LatticeCodecError,
115 LatticeDecodeError, LatticeVersion, Level, SecurityContext, SecurityLabel,
116 SubjectContextClaims, VerifiedKeyMaterial, MAX_COMPARTMENTS,
117};
118pub use te::{
119 Action, Decision, LatticeTeEvaluator, ObjectCtx, ObjectType, ScopeAction, SubjectCtx,
120 SubjectType, TeEvaluator, TeMatrix, TeRule,
121};
122
123/// Install the mandatory RPC-dispatch PEP using the process activation control.
124/// Verified identity-aware contexts are the default; explicit incident
125/// narrowing remains available without removing the monitor.
126///
127/// The object-label resolver is the validated generated schema inventory:
128/// exact `(service, full leaf path)` rows and verified caller clearance.
129/// Bare RPC service names are never mapped through the VFS object-label
130/// adapter (the genesis `CompositeObjectLabelResolver` now serves the VFS/9P
131/// plane only); unknown services, unknown leaves, and VFS-shaped aliases deny
132/// `UnlabeledObject` before handler entry.
133pub fn install_production_rpc_dispatch_pep() -> anyhow::Result<()> {
134 let default = generated_dispatch::GeneratedDispatchPep::production()?;
135 let bootstrap = dispatch_labels::DeclaredDispatchPep::new(
136 dispatch_labels::DeclaredDispatchTable::production(),
137 )
138 .with_activation_control();
139 hyprstream_rpc::auth::mac::install_mac_dispatch_pep(std::sync::Arc::new(
140 ProductionDispatchPep { default, bootstrap },
141 ));
142 Ok(())
143}
144
145/// Generated dispatch labels with the existing narrow local Policy bootstrap
146/// path preserved. Only the cryptographically verified, non-federated,
147/// bearerless `service:policy` authority may use that path. Its exact methods
148/// must remain declared in both the bootstrap table and generated inventory.
149struct ProductionDispatchPep {
150 default: generated_dispatch::GeneratedDispatchPep,
151 bootstrap: dispatch_labels::DeclaredDispatchPep,
152}
153
154impl hyprstream_rpc::auth::mac::MacDispatchPep for ProductionDispatchPep {
155 fn check(
156 &self,
157 ctx: &hyprstream_rpc::service::EnvelopeContext,
158 service_domain: &str,
159 method: Option<&[u16]>,
160 ) -> hyprstream_rpc::auth::mac::MacDecision {
161 let is_local_policy_check = service_domain == "policy"
162 && method == Some(&[policy_methods::CHECK][..])
163 && ctx.jwt_token().is_none()
164 && !ctx.subject().is_federated()
165 && ctx.subject().name() == Some("service:policy");
166 let is_local_policy_control_plane = is_local_policy_check
167 || (service_domain == "policy"
168 && matches!(
169 method,
170 Some([policy_methods::GET_POLICY
171 | policy_methods::APPLY_TEMPLATE
172 | policy_methods::APPLY_DRAFT
173 | policy_methods::ROLLBACK
174 | policy_methods::GET_HISTORY
175 | policy_methods::GET_DIFF
176 | policy_methods::GET_DRAFT_STATUS
177 | policy_methods::ADD_GROUPING
178 | policy_methods::REMOVE_GROUPING])
179 ));
180 if is_local_policy_control_plane {
181 if !self.default.is_declared(service_domain, method) {
182 return hyprstream_rpc::auth::mac::MacDecision::Deny(
183 hyprstream_rpc::auth::mac::MacDenyReason::UnlabeledObject,
184 );
185 }
186 if !(ctx.jwt_token().is_none()
187 && !ctx.subject().is_federated()
188 && ctx.subject().name() == Some("service:policy"))
189 {
190 return hyprstream_rpc::auth::mac::MacDecision::Deny(
191 hyprstream_rpc::auth::mac::MacDenyReason::NoClearance,
192 );
193 }
194
195 // This root-signed local bootstrap path intentionally carries no
196 // bearer claims. Keep its verified, declared policy-service
197 // context explicit so identity-aware activation does not turn the
198 // narrow control plane into `NoClearance` merely for being
199 // tokenless. The typed table and exact local-method guard still
200 // decide what it can reach.
201 let selected = SecurityContext::from_clearance(
202 BOOTSTRAP_SERVICE_CLEARANCE,
203 ctx.verified_key_material(),
204 );
205 return self.bootstrap.check_with_explicit_context(
206 ctx,
207 service_domain,
208 method,
209 selected,
210 );
211 }
212 self.default.check(ctx, service_domain, method)
213 }
214}
215
216/// Explicit permit fixture for unit tests that exercise service plumbing
217/// rather than MAC policy. Production's uninstalled dispatch state still
218/// denies at rest.
219#[cfg(test)]
220pub(crate) fn install_explicit_test_dispatch_pep() {
221 struct ExplicitTestPep;
222
223 impl hyprstream_rpc::auth::mac::MacDispatchPep for ExplicitTestPep {
224 fn check(
225 &self,
226 _ctx: &hyprstream_rpc::service::EnvelopeContext,
227 _service_domain: &str,
228 _method: Option<&[u16]>,
229 ) -> hyprstream_rpc::auth::mac::MacDecision {
230 hyprstream_rpc::auth::mac::MacDecision::Permit
231 }
232 }
233
234 hyprstream_rpc::auth::mac::install_mac_dispatch_pep(std::sync::Arc::new(ExplicitTestPep));
235}
236
237#[cfg(test)]
238mod production_dispatch_tests {
239 use super::*;
240 use hyprstream_rpc::auth::mac::{MacDecision, MacDispatchPep};
241 use hyprstream_rpc::envelope::Subject;
242 use hyprstream_rpc::service::EnvelopeContext;
243
244 fn production_pep() -> anyhow::Result<ProductionDispatchPep> {
245 Ok(ProductionDispatchPep {
246 default: generated_dispatch::GeneratedDispatchPep::production()?,
247 bootstrap: dispatch_labels::DeclaredDispatchPep::new(
248 dispatch_labels::DeclaredDispatchTable::production(),
249 )
250 .with_activation_control(),
251 })
252 }
253
254 #[test]
255 fn local_policy_control_plane_requires_the_exact_tokenless_policy_authority(
256 ) -> anyhow::Result<()> {
257 let signer = ed25519_dalek::SigningKey::from_bytes(&[0x91; 32]).verifying_key();
258 let policy =
259 EnvelopeContext::for_test_authenticated_subject(Subject::new("service:policy"), signer);
260 let registry = EnvelopeContext::for_test_authenticated_subject(
261 Subject::new("service:registry"),
262 signer,
263 );
264 let pep = production_pep()?;
265 let no_activation = dispatch_labels::DeclaredDispatchPep::new(
266 dispatch_labels::DeclaredDispatchTable::production(),
267 );
268
269 assert_eq!(
270 pep.check(&policy, "policy", Some(&[policy_methods::APPLY_TEMPLATE])),
271 MacDecision::Permit,
272 );
273 assert_eq!(
274 no_activation.check(&policy, "policy", Some(&[policy_methods::APPLY_TEMPLATE])),
275 MacDecision::Deny(hyprstream_rpc::auth::mac::MacDenyReason::NoClearance),
276 "the production wrapper must supply the explicit verified bootstrap context",
277 );
278 assert_eq!(
279 pep.check(®istry, "policy", Some(&[policy_methods::APPLY_TEMPLATE])),
280 MacDecision::Deny(hyprstream_rpc::auth::mac::MacDenyReason::NoClearance),
281 );
282 assert_eq!(
283 pep.check(&policy, "policy", Some(&[17])),
284 MacDecision::Deny(hyprstream_rpc::auth::mac::MacDenyReason::NoClearance),
285 );
286 // Ordinal 0 is now the declared `check` row (added by the staged
287 // policy dispatch work): the tokenless policy CA is its sanctioned
288 // caller, so the exact-authority requirement shows up as Permit while
289 // every other service stays denied (asserted above for registry).
290 // Undeclared ordinals must still deny; one is pinned below.
291 assert_eq!(
292 pep.check(&policy, "policy", Some(&[0])),
293 MacDecision::Permit,
294 "the tokenless policy authority reaches its own declared check row",
295 );
296 assert_eq!(
297 pep.check(&policy, "policy", Some(&[2])),
298 MacDecision::Deny(hyprstream_rpc::auth::mac::MacDenyReason::NoClearance),
299 "undeclared ordinals keep denying; the root authority's access must not be reported as another user's result",
300 );
301 Ok(())
302 }
303}
304// S5 (#571): the UCAN→TE policy compiler — compile a validated grant into a
305// CompiledPolicy, verify it grants no privilege beyond the grant, and sign it
306// (fail-closed). Lives here (not `hyprstream-rpc`) because it needs both the UCAN
307// model and S4's `TeMatrix`/`CompiledPolicy`.
308pub use compiler::{
309 authorize, authorize_at, check_no_escalation, compile, compile_policy, missing_permission,
310 AccessRequest, CompileError, PermissionMap, PrivilegeEscalation,
311};
312// S1 activation (#567): production genesis content/enumerator/resolver/gate.
313pub use genesis::{
314 floor_label, genesis_lattice, CompositeObjectLabelResolver, GeneratedNodeCoverage, GenesisGate,
315 ManifestLabelSource, NamespaceEnumerator, NoManifests, SitePolicy,
316};
317// #1499: typed dispatch-plane labels + the production dispatch PEP over them.
318pub use dispatch_labels::{
319 policy_methods, DeclaredDispatchPep, DeclaredDispatchTable, DispatchMethodId,
320 DispatchMethodPolicy, ServiceSubjectClearance, BOOTSTRAP_SERVICE_CLEARANCE,
321 SERVICE_SUBJECT_PREFIX,
322};
323pub use moq_audit::{
324 audited_moq_event_pep, production_moq_event_pep, production_moq_event_pep_with_clearance,
325 MoqAuditSinkAdapter, VerifiedClaimsMoqClearanceSource,
326};
327pub use pds_pep::{
328 production_pds_account_read_authorizer, EnrollmentPdsClearanceSource,
329 PdsAccountObjectLabelResolver, PdsAccountReadPep, PdsClearanceSource,
330};
331#[cfg(not(target_arch = "wasm32"))]
332pub use pds_pep::{production_pds_account_record_store, PdsDirectoryMount};
333// #1270: CAS-native MAC PEP — the shared CAS enforcement contract.
334pub use cas_pep::{
335 domain_label, production_cas_pep, seal_label, CasClearanceSource, CasObjectLabelResolver,
336 CasPep, DenyAllClearanceSource, MacCasAuthorizer, VerifiedClaimsCasClearanceSource,
337};
338pub use pep::{
339 enrollment_ninep_reference_monitor, production_ninep_decider,
340 production_ninep_reference_monitor, production_vfs_pep, EnrollmentClearanceSource,
341 NinePAccessDecider, NinePClearanceSource, VerifiedClaimsSubjects,
342 VerifiedClearanceSessionFactory, VfsAccessDecider,
343};
344// S4 (#570): the boot path that installs the verified `CompiledPolicy` at daemon
345// startup (dormant — makes the PDP inputs real without enabling enforcement).
346pub use bootload::{compile_sign_load_install, install_baseline_boot_policy, BootPolicyError};
347
348/// Construct the [`UcanVerifier`] the HTTP grant path uses to validate a
349/// presented UCAN's signatures.
350///
351/// This is the S6↔trust-store seam. **S8 (#574) wires it to the process-global
352/// `PqTrustStore`** (the same `register_pq_trust` binding the rest of the TCB
353/// uses, installed via `envelope::install_verify_config`). The verifier resolves
354/// each UCAN issuer's anchored ML-DSA-65 verifying key from that store and
355/// verifies the hybrid composite with `require_pq = true` (the Hybrid policy).
356///
357/// Returns `None` (→ the HTTP grant path denies every request, fail-closed) when
358/// no PQ trust store has been installed — a node that has not configured hybrid
359/// verification cannot validate hybrid-signed UCANs, and `evaluate_grant` never
360/// runs against an unverified chain.
361///
362/// The core `evaluate_grant` is exercised through its own tests with a real
363/// verifier, so the security-critical logic is covered independently of this
364/// wiring.
365pub fn exchange_ucan_verifier(
366 _state: &crate::services::oauth::state::OAuthState,
367) -> Option<Box<dyn hyprstream_rpc::auth::ucan::token::UcanVerifier + Send + Sync>> {
368 // The verifier needs the kid-anchored PQ store (the same `register_pq_trust`
369 // binding the envelope verifier uses). If none is installed, fail-closed.
370 let pq_store = hyprstream_rpc::envelope::global_pq_store()?;
371 Some(Box::new(GlobalPqUcanVerifier { pq_store }))
372}
373
374/// A `UcanVerifier` backed by the process-global `PqTrustStore` (the same store
375/// the envelope verifier uses). Resolves each UCAN issuer's anchored ML-DSA-65
376/// key and verifies the hybrid composite under the Hybrid policy (`require_pq`).
377///
378/// This is the S8 activation: the HTTP grant path now validates hybrid UCAN
379/// signatures against the node's trust store rather than denying by default.
380struct GlobalPqUcanVerifier {
381 pq_store: std::sync::Arc<dyn hyprstream_rpc::envelope::PqTrustStore>,
382}
383
384impl hyprstream_rpc::auth::ucan::token::UcanVerifier for GlobalPqUcanVerifier {
385 fn verify(
386 &self,
387 issuer: &hyprstream_rpc::auth::ucan::token::Did,
388 ed_key: &[u8; 32],
389 payload: &[u8],
390 signature: &[u8],
391 ) -> Result<(), hyprstream_rpc::auth::ucan::token::UcanError> {
392 use hyprstream_rpc::auth::ucan::token::UcanError;
393 let ed_vk = ed25519_dalek::VerifyingKey::from_bytes(ed_key)
394 .map_err(|e| UcanError::BadSignature(e.to_string()))?;
395 // kid-anchoring: resolve the issuer's trusted ML-DSA-65 key from the
396 // global PQ store, keyed by the Ed25519 identity (the cnf-equivalent).
397 // The `issuer` DID encodes the same Ed25519 key; the store is keyed by
398 // the raw bytes (the canonical anchor), so we resolve via `ed_key`.
399 // No anchor ⇒ fail-closed under Hybrid (require_pq).
400 let _ = issuer; // available for future per-DID anchoring policy.
401 let pq_vk = self.pq_store.ml_dsa_key_for(ed_key);
402 hyprstream_rpc::crypto::cose_sign::verify_composite(
403 signature,
404 &ed_vk,
405 pq_vk.as_ref(),
406 payload,
407 hyprstream_rpc::auth::ucan::token::UCAN_AAD,
408 /* require_pq */ true,
409 )
410 .map(|_| ())
411 .map_err(|e| UcanError::BadSignature(e.to_string()))
412 }
413}
414
415/// Process-global installed policy the [`exchange_enrollment_resolver`] seam reads.
416/// Mirrors `hyprstream_rpc::envelope::global_pq_store`'s pattern: a node loads and
417/// verifies a [`SignedPolicy`] via [`PolicyLoader`] at startup and installs the
418/// result once here; a node that hasn't leaves this `None` and the seam below
419/// fails closed.
420static COMPILED_POLICY: std::sync::OnceLock<std::sync::Arc<CompiledPolicy>> =
421 std::sync::OnceLock::new();
422
423/// Install the node's verified [`CompiledPolicy`] for the
424/// [`exchange_enrollment_resolver`] seam. **Write-once per process** (backed by a
425/// `OnceLock`): returns `true` if THIS call installed `policy`, `false` if a
426/// policy was already installed and this call was a no-op. The caller MUST have
427/// already verified the policy via [`PolicyLoader`] — this does not re-verify.
428///
429/// The `bool` return makes the write-once contract honest: because the slot is a
430/// `OnceLock`, the **first** installed policy pins the seam for the process
431/// lifetime. Today the only caller is the boot baseline
432/// ([`bootload::install_baseline_boot_policy`]), so this is exactly-once; a
433/// future config-driven real policy CANNOT swap the baseline out through this API
434/// (it would get `false` and leave the empty baseline in place). Making the seam
435/// swap-capable — e.g. an `ArcSwap<CompiledPolicy>` keyed by policy generation so
436/// a newer, verified generation replaces an older one atomically — is the
437/// follow-up; until then callers must treat `false` as "the global seam still
438/// holds the earlier policy", never as success.
439// `pub(crate)` — this seam installs `policy` WITHOUT re-verifying it (the caller
440// MUST have already run it through `PolicyLoader`). Keeping it crate-private
441// prevents an out-of-crate caller from bypassing the verify-once-at-load path and
442// pinning an unsigned / classical-only policy into the process-global seam. The
443// only caller is `bootload`, which self-verifies through the full sign→load path.
444#[must_use]
445pub(crate) fn install_compiled_policy(policy: std::sync::Arc<CompiledPolicy>) -> bool {
446 COMPILED_POLICY.set(policy).is_ok()
447}
448
449/// The installed [`CompiledPolicy`], if any. `None` on a node that hasn't loaded
450/// one — callers MUST fail closed (see [`exchange_enrollment_resolver`]), never
451/// substitute a permissive default.
452pub fn compiled_policy() -> Option<std::sync::Arc<CompiledPolicy>> {
453 COMPILED_POLICY.get().cloned()
454}
455
456/// The `SubjectContextResolver` for a delegated actor, backed by the signed
457/// policy's enrollment table (`CompiledPolicy::clearance_for`, #698 PR A).
458///
459/// **#698 Decision D** (operator-ratified, 2026-07-03): a delegated actor proves
460/// only DPoP possession of a classical ephemeral key at the grant path — UCAN
461/// chain validation (`GlobalPqUcanVerifier`, `require_pq: true`) proves *issuers*,
462/// never the audience — so this resolver clamps assurance to
463/// `VerifiedKeyMaterial::Classical` unconditionally, regardless of the enrolled
464/// clearance's own level/compartments. That is the truthful label for what the
465/// crypto actually proves; assigning anything higher would let an unverified
466/// actor claim PqHybrid assurance, defeating #548. An object labeled with a
467/// PqHybrid assurance requirement is therefore structurally unreachable through
468/// this resolver — by construction, not by a missing rule (see
469/// `docs/mac-architecture.md`). Raising a specific enrolled actor above Classical
470/// is the enrollment-key-registration follow-up (#718), not this resolver.
471///
472/// An unenrolled DID resolves to `None` — the existing fail-closed contract
473/// (`SubjectContextResolver::resolve`'s `None` ⇒ deny) is unchanged.
474pub struct EnrollmentSubjectContextResolver {
475 policy: std::sync::Arc<CompiledPolicy>,
476}
477
478impl EnrollmentSubjectContextResolver {
479 /// Construct a resolver over a verified, installed [`CompiledPolicy`].
480 pub fn new(policy: std::sync::Arc<CompiledPolicy>) -> Self {
481 Self { policy }
482 }
483}
484
485impl crate::services::oauth::token_exchange::SubjectContextResolver
486 for EnrollmentSubjectContextResolver
487{
488 fn resolve(&self, audience_did: &str) -> Option<SecurityContext> {
489 let clearance = self.policy.clearance_for(audience_did)?;
490 // Decision D: floor at Classical no matter what the enrollment table's
491 // clearance component says — the assurance axis is what's cryptographically
492 // proven here, not what's authorized.
493 Some(SecurityContext::from_clearance(
494 clearance,
495 VerifiedKeyMaterial::Classical,
496 ))
497 }
498}
499
500/// Construct the `SubjectContextResolver` the HTTP grant path resolves delegated
501/// actors' MAC context through (#698 Decision D).
502///
503/// Returns [`EnrollmentSubjectContextResolver`] when a compiled policy has been
504/// installed via [`install_compiled_policy`]; falls back to
505/// [`crate::services::oauth::token_exchange::DenyUnlabeledResolver`] (fail-closed)
506/// on a node that has not loaded one — mirrors [`exchange_ucan_verifier`]'s
507/// Option-to-fail-closed pattern.
508pub fn exchange_enrollment_resolver(
509) -> Box<dyn crate::services::oauth::token_exchange::SubjectContextResolver> {
510 match compiled_policy() {
511 Some(policy) => Box::new(EnrollmentSubjectContextResolver::new(policy)),
512 None => Box::new(crate::services::oauth::token_exchange::DenyUnlabeledResolver),
513 }
514}
515
516#[cfg(test)]
517#[allow(clippy::unwrap_used)]
518mod enrollment_resolver_tests {
519 use super::*;
520 use crate::services::oauth::token_exchange::SubjectContextResolver as _;
521 use std::collections::BTreeMap;
522
523 fn test_lattice() -> Lattice {
524 Lattice::new(LatticeVersion(1), [])
525 }
526
527 fn policy_with(did: &str, clearance: SecurityLabel) -> std::sync::Arc<CompiledPolicy> {
528 let lattice = test_lattice();
529 let mut policy = CompiledPolicy::new(TeMatrix::default(), &lattice);
530 policy = policy.with_enrollment(BTreeMap::from([(did.to_owned(), clearance)]));
531 std::sync::Arc::new(policy)
532 }
533
534 #[test]
535 fn enrolled_did_resolves_at_classical_regardless_of_table_assurance() {
536 // Enrollment table asserts PqHybrid for this DID; the resolver must
537 // still floor the resulting SecurityContext at Classical (#698 Decision
538 // D) — the table's own assurance component is not authoritative here.
539 let clearance =
540 SecurityLabel::new(Level::Secret, Assurance::PqHybrid, CompartmentSet::EMPTY);
541 let resolver =
542 EnrollmentSubjectContextResolver::new(policy_with("did:key:actor", clearance));
543
544 // enrolled DID must resolve
545 let ctx = resolver.resolve("did:key:actor").unwrap();
546
547 assert_eq!(ctx.clearance().assurance, Assurance::Classical);
548 assert_eq!(ctx.clearance().level, Level::Secret);
549 }
550
551 #[test]
552 fn unenrolled_did_denies() {
553 let resolver = EnrollmentSubjectContextResolver::new(policy_with(
554 "did:key:actor",
555 SecurityLabel::new(Level::Secret, Assurance::Classical, CompartmentSet::EMPTY),
556 ));
557
558 assert!(resolver.resolve("did:key:someone-else").is_none());
559 }
560}