Skip to main content

hyprstream_rpc/auth/
atproto_perimeter.rs

1//! ATProto perimeter gateway — external-DID → assurance binding (#549, first half).
2//!
3//! This is the **enrollment-time** translation seam between a federated ATProto
4//! identity (an external `Did`) and the internal MAC lattice (#548). It "translates,
5//! does not tunnel": an external DID is resolved **once, off the auth path**, its
6//! verified key material is mapped to an [`Assurance`], and the result is pinned as
7//! an [`EnrolledPeer`] carrying a derived [`SecurityContext`]. The per-op reference
8//! monitor (#548 S2) then reads the *cached* context and never re-resolves.
9//!
10//! ## What this module is / is not
11//!
12//! - **Is:** the `external Did → VerifiedKeyMaterial → SecurityContext` mapping,
13//!   mutable admission-gated [`EnrollmentStore`], and exact, DPoP-gated ATProto
14//!   OAuth-scope/lexicon → bounded interior UCAN+MAC translation. It consumes the
15//!   (mirrored) #579 resolver and the *existing* epic MAC types ([`Assurance`],
16//!   [`SecurityLabel`], [`SecurityContext`], [`VerifiedKeyMaterial`]) — it does
17//!   **not** re-declare any of them.
18//! - **Is not:** per-op enforcement (#548 S2), concrete DPoP proof verification
19//!   (performed by the OAuth boundary before translation), or a concrete
20//!   `did:plc`/`did:web` resolver (#579).
21//!
22//! ## Fail-closed
23//!
24//! Any resolver error, a `None` DID, or a missing verifying key yields `Err` ⇒ the
25//! peer is **not** enrolled. There is no default enrollment and no default
26//! assurance: an un-resolvable identity dominates nothing above the lattice floor.
27//!
28//! ## Zero standing privilege (ZSP)
29//!
30//! The enrollment edge ceiling is `Level::Internal × <crypto-derived assurance> ×
31//! EMPTY` compartments. Compartments are **explicit grants made later**, never
32//! conferred at enrollment. The clamp-down in
33//! [`SecurityContext::from_clearance`] guarantees a classical peer can never obtain
34//! a `PqHybrid` context even if the ceiling allowed it.
35
36use std::collections::HashMap;
37use std::sync::Arc;
38
39use anyhow::{anyhow, Result};
40use parking_lot::RwLock;
41
42use crate::admission::AdmittedIdentity;
43use crate::auth::mac::{
44    Assurance, CompartmentSet, Level, SecurityContext, SecurityLabel, VerifiedKeyMaterial,
45};
46use crate::identity::{Did, IdentityResolver};
47
48/// A pinned, enrolled external peer.
49///
50/// Produced by [`AtprotoPerimeterGateway::enroll`] and cached in the
51/// [`EnrollmentStore`]. The reference monitor (#548 S2) reads `context` per-op via
52/// [`EnrollmentStore::get`]; it never re-resolves. The `(did, channel_key,
53/// assurance)` triple is the deliberate pin — rotation requires re-enrollment.
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct EnrolledPeer {
56    /// The external identity this peer enrolled under.
57    pub did: Did,
58    /// The peer's authenticated 32-byte channel/envelope key (the admission `cnf`).
59    pub channel_key: [u8; 32],
60    /// The crypto-derived assurance pinned at enrollment.
61    pub assurance: Assurance,
62    /// The derived subject context the monitor compares against object labels.
63    pub context: SecurityContext,
64    /// The PDS endpoint advertised for this identity, if any (discovery only).
65    pub pds_endpoint: Option<String>,
66}
67
68/// Map a crypto-derived [`Assurance`] to the MAC seam [`VerifiedKeyMaterial`], 1:1
69/// by name. This is a *routing* step — assurance is already established by the
70/// resolver; this only re-expresses it in the type the lattice consumes.
71fn assurance_to_key_material(assurance: Assurance) -> VerifiedKeyMaterial {
72    match assurance {
73        Assurance::Unverified => VerifiedKeyMaterial::Unverified,
74        Assurance::Classical => VerifiedKeyMaterial::Classical,
75        Assurance::PqHybrid => VerifiedKeyMaterial::PqHybrid,
76    }
77}
78
79/// The perimeter gateway: turns an admission-gated external identity into an
80/// enrolled internal peer with a derived MAC context.
81///
82/// Generic over the resolver so it scaffolds against the #579 mirror and fixtures
83/// today, and against the real `did:plc`/`did:web` resolver once #579 merges.
84pub struct AtprotoPerimeterGateway<R: IdentityResolver> {
85    resolver: R,
86}
87
88impl<R: IdentityResolver> AtprotoPerimeterGateway<R> {
89    /// Construct a gateway over an [`IdentityResolver`].
90    pub fn new(resolver: R) -> Self {
91        Self { resolver }
92    }
93
94    /// The enrollment edge ceiling: `Level::Internal × <derived assurance> × {}`.
95    ///
96    /// ZSP: the level is the federation edge default (`Internal`), assurance is the
97    /// crypto-derived axis (so [`SecurityContext::from_clearance`]'s clamp-down is a
98    /// no-op against an honest ceiling, and a *defensive* upper bound otherwise),
99    /// and compartments are **EMPTY** — every need-to-know compartment is an
100    /// explicit grant made after enrollment, never conferred here.
101    fn edge_ceiling(derived: Assurance) -> SecurityLabel {
102        SecurityLabel::new(Level::Internal, derived, CompartmentSet::EMPTY)
103    }
104
105    /// Enroll an [`AdmittedIdentity`] (admission-gated) into an [`EnrolledPeer`].
106    ///
107    /// Steps (all enrollment-time, never per-op):
108    /// 1. resolve the admitted DID's verified key material (#579 mirror);
109    /// 2. map [`Assurance`] → [`VerifiedKeyMaterial`] 1:1 by name;
110    /// 3. clamp the edge ceiling DOWN to the crypto-derived assurance via
111    ///    [`SecurityContext::from_clearance`] (the #548 invariant);
112    /// 4. pin the result as an [`EnrolledPeer`].
113    ///
114    /// **Fail-closed:** a `None` admitted DID, any resolver error, or a missing
115    /// verifying key for the resolved assurance returns `Err` ⇒ not enrolled.
116    pub fn enroll(&self, admitted: &AdmittedIdentity) -> Result<EnrolledPeer> {
117        // An admission that matched only via JWKS fallback carries no DID; without a
118        // DID there is nothing to resolve → fail-closed.
119        let did_str = admitted.did.as_deref().ok_or_else(|| {
120            anyhow!("perimeter enroll: admitted identity carries no DID (fail-closed)")
121        })?;
122        let did = Did::new(did_str.to_owned());
123
124        // Resolve OFF the auth path. Any resolver error is fail-closed.
125        let keys = self
126            .resolver
127            .resolve_identity_keys(&did)
128            .map_err(|e| anyhow!("perimeter enroll: DID {did} did not resolve: {e}"))?;
129
130        // Admission already verified `admitted.key` against the DID document.
131        // Select that exact candidate from the named set rather than granting
132        // document-order authority to another overlap/rotation slot.
133        let candidate = keys.candidate_for_ed25519(&admitted.key).ok_or_else(|| {
134            anyhow!(
135                "perimeter enroll: DID {did} no longer publishes the admitted Ed25519 signer — fail-closed"
136            )
137        })?;
138        let key_material = assurance_to_key_material(candidate.assurance());
139        let derived = key_material.assurance();
140
141        // Edge ceiling × clamp-DOWN to crypto-derived assurance (#548).
142        let context = SecurityContext::from_clearance(Self::edge_ceiling(derived), key_material);
143
144        Ok(EnrolledPeer {
145            did,
146            channel_key: admitted.key,
147            assurance: context.assurance(),
148            context,
149            pds_endpoint: None,
150        })
151    }
152}
153
154/// A mutable, admission-gated store of enrolled external peers.
155///
156/// **Deliberately separate** from the native, admin-anchored, post-install
157/// **immutable** [`crate::envelope::KeyedPqTrustStore`] — that PQ anchor is left
158/// untouched. This store holds the *federation perimeter's* enrolled peers and is
159/// mutated only through [`AtprotoPerimeterGateway::enroll`]'s admission-gated path:
160/// [`insert`](EnrollmentStore::insert) takes an [`EnrolledPeer`], which can only be
161/// produced from an [`AdmittedIdentity`].
162///
163/// [`get`](EnrollmentStore::get) is the read seam the future per-op monitor (#548
164/// S2) uses to fetch a peer's cached [`SecurityContext`] without re-resolving.
165#[derive(Clone, Default)]
166pub struct EnrollmentStore {
167    peers: Arc<RwLock<HashMap<Did, EnrolledPeer>>>,
168}
169
170impl EnrollmentStore {
171    /// Create an empty store.
172    pub fn new() -> Self {
173        Self::default()
174    }
175
176    /// Insert (or replace) an enrolled peer, keyed by its DID.
177    ///
178    /// Only an [`EnrolledPeer`] — which is produced exclusively from an
179    /// admission-gated enrollment — can be inserted, so the store stays
180    /// admission-gated by construction.
181    pub fn insert(&self, peer: EnrolledPeer) {
182        self.peers.write().insert(peer.did.clone(), peer);
183    }
184
185    /// Look up an enrolled peer's cached state by DID, if present.
186    pub fn get(&self, did: &Did) -> Option<EnrolledPeer> {
187        self.peers.read().get(did).cloned()
188    }
189
190    /// Number of enrolled peers.
191    pub fn len(&self) -> usize {
192        self.peers.read().len()
193    }
194
195    /// Whether no peer is enrolled.
196    pub fn is_empty(&self) -> bool {
197        self.len() == 0
198    }
199}
200
201/// An exact ATProto OAuth scope plus lexicon permission presented at the
202/// federation edge.
203///
204/// Scope strings and lexicon NSIDs are deliberately opaque here: accepting a
205/// prefix or wildcard would turn an OAuth permission we do not understand into
206/// an interior authority grant. The perimeter therefore maps only exact,
207/// administrator-configured pairs.
208#[derive(Clone, Debug, PartialEq, Eq, Hash)]
209pub struct AtprotoPermission {
210    /// The OAuth scope asserted by the already-verified ATProto authorization.
211    pub scope: String,
212    /// The lexicon NSID / operation the caller wants to use under `scope`.
213    pub lexicon: String,
214}
215
216impl AtprotoPermission {
217    /// Build an exact external permission. Empty or whitespace-containing
218    /// components are not valid OAuth scope tokens / lexicon NSIDs and are
219    /// rejected before they reach the mapping table.
220    pub fn new(scope: impl Into<String>, lexicon: impl Into<String>) -> Result<Self> {
221        let scope = scope.into();
222        let lexicon = lexicon.into();
223        if scope.is_empty() || scope.bytes().any(|b| b.is_ascii_whitespace()) {
224            return Err(anyhow!(
225                "perimeter authorization: invalid ATProto OAuth scope"
226            ));
227        }
228        if lexicon.is_empty() || lexicon.bytes().any(|b| b.is_ascii_whitespace()) {
229            return Err(anyhow!(
230                "perimeter authorization: invalid ATProto lexicon permission"
231            ));
232        }
233        Ok(Self { scope, lexicon })
234    }
235}
236
237/// Evidence that the surrounding OAuth resource server verified a DPoP proof
238/// and bound this authorization to its JWK thumbprint (`jkt`).
239///
240/// This module intentionally does not parse or verify DPoP JWTs: that belongs
241/// to the OAuth boundary (`services::oauth::dpop`) where the request method,
242/// URI, nonce, and replay cache are available. Requiring this value makes the
243/// dependency explicit and ensures a translation result is sender-bound rather
244/// than usable as a bearer grant.
245#[derive(Clone, Debug, PartialEq, Eq)]
246pub struct VerifiedDpopBinding(String);
247
248impl VerifiedDpopBinding {
249    /// Construct from a `jkt` returned by a successful DPoP verifier.
250    ///
251    /// Callers MUST NOT construct this from an unverified request header; the
252    /// verifier is responsible for signature, `htm`/`htu`, nonce, and replay
253    /// validation. We reject empty/whitespace values so a missing proof cannot
254    /// be represented as a binding.
255    pub fn from_verified_jkt(jkt: impl Into<String>) -> Result<Self> {
256        let jkt = jkt.into();
257        if jkt.is_empty() || jkt.bytes().any(|b| b.is_ascii_whitespace()) {
258            return Err(anyhow!(
259                "perimeter authorization: missing verified DPoP binding"
260            ));
261        }
262        Ok(Self(jkt))
263    }
264
265    /// The verified sender-binding JWK thumbprint for token minting/audit.
266    pub fn jkt(&self) -> &str {
267        &self.0
268    }
269}
270
271/// A policy-approved, one-way translation from an exact ATProto permission to
272/// an interior UCAN capability and the greatest MAC object label it may target.
273///
274/// This is configuration supplied by the local authority, never by an external
275/// DID. `maximum_label` does not grant clearance: the enrolled peer must already
276/// dominate it, so an OAuth permission cannot raise MLS, assurance, or
277/// compartment clearance.
278#[derive(Clone, Debug, PartialEq, Eq)]
279pub struct AtprotoPermissionMapping {
280    /// The exact interior capability the trusted gateway may place in a new
281    /// local UCAN. External ATProto records never carry that UCAN themselves.
282    pub capability: crate::auth::ucan::capability::Capability,
283    /// The bounded MAC label enforced alongside this translated capability.
284    pub maximum_label: SecurityLabel,
285}
286
287impl AtprotoPermissionMapping {
288    /// Create a mapping after rejecting wildcard interior authority. A broad
289    /// external grant must be expanded into individually reviewed exact entries
290    /// instead of being smuggled through `*` or a wildcard resource.
291    pub fn new(
292        capability: crate::auth::ucan::capability::Capability,
293        maximum_label: SecurityLabel,
294    ) -> Result<Self> {
295        let resource = capability.resource.as_str();
296        let ability = capability.ability.as_str();
297        if !resource.starts_with("mac://")
298            || resource.len() == "mac://".len()
299            || resource.contains('*')
300            || resource.bytes().any(|b| b.is_ascii_whitespace())
301            || ability.is_empty()
302            || ability.contains('*')
303            || ability.bytes().any(|b| b.is_ascii_whitespace())
304        {
305            return Err(anyhow!(
306                "perimeter authorization: mapping must contain an exact non-wildcard interior capability"
307            ));
308        }
309        Ok(Self {
310            capability,
311            maximum_label,
312        })
313    }
314}
315
316/// A configured, fail-closed ATProto OAuth/lexicon → UCAN+MAC translator.
317///
318/// It owns no DID resolver and has no network capability. Enrollment resolves
319/// and pins the DID before this translator is ever called; authorization reads
320/// only [`EnrolledPeer::context`]. This keeps did:web/did:plc/PLC resolution out
321/// of the per-operation authorization path by construction.
322#[derive(Clone, Default)]
323pub struct AtprotoPermissionTranslator {
324    mappings: HashMap<AtprotoPermission, AtprotoPermissionMapping>,
325}
326
327impl AtprotoPermissionTranslator {
328    /// Build from a closed, locally administered mapping table. Duplicate
329    /// external permissions are rejected rather than allowing load order to
330    /// select an authority unexpectedly.
331    pub fn new(
332        mappings: impl IntoIterator<Item = (AtprotoPermission, AtprotoPermissionMapping)>,
333    ) -> Result<Self> {
334        let mut table = HashMap::new();
335        for (permission, mapping) in mappings {
336            if table.insert(permission.clone(), mapping).is_some() {
337                return Err(anyhow!(
338                    "perimeter authorization: duplicate mapping for scope {:?}, lexicon {:?}",
339                    permission.scope,
340                    permission.lexicon
341                ));
342            }
343        }
344        Ok(Self { mappings: table })
345    }
346
347    /// Translate verified external permissions into narrowly bounded interior
348    /// capability requests.
349    ///
350    /// The OAuth resource server must verify DPoP before constructing
351    /// `dpop_binding`; the gateway then requires every permission to have an
352    /// exact local mapping and every target label to be dominated by the cached
353    /// enrollment context. Any missing mapping, over-clearance request, absent
354    /// peer, or malformed binding returns `Err` — there is no fallback,
355    /// wildcard, or default capability.
356    pub fn translate(
357        &self,
358        peer: &EnrolledPeer,
359        dpop_binding: VerifiedDpopBinding,
360        permissions: &[AtprotoPermission],
361    ) -> Result<TranslatedAtprotoAuthorization> {
362        if permissions.is_empty() {
363            return Err(anyhow!(
364                "perimeter authorization: no ATProto permissions presented (fail-closed)"
365            ));
366        }
367
368        let mut capabilities = Vec::with_capacity(permissions.len());
369        let mut maximum_labels = Vec::with_capacity(permissions.len());
370        for permission in permissions {
371            let mapping = self.mappings.get(permission).ok_or_else(|| {
372                anyhow!(
373                    "perimeter authorization: unmappable ATProto scope {:?} / lexicon {:?} (fail-closed)",
374                    permission.scope,
375                    permission.lexicon
376                )
377            })?;
378
379            // A translated OAuth permission is never a clearance grant. The
380            // pinned crypto-derived context is the independent MAC floor.
381            if !peer.context.can_access(&mapping.maximum_label) {
382                return Err(anyhow!(
383                    "perimeter authorization: peer {} cannot access mapped label {} (fail-closed)",
384                    peer.did,
385                    mapping.maximum_label
386                ));
387            }
388            capabilities.push(mapping.capability.clone());
389            maximum_labels.push(mapping.maximum_label);
390        }
391
392        Ok(TranslatedAtprotoAuthorization {
393            did: peer.did.clone(),
394            dpop_binding,
395            capabilities,
396            maximum_labels,
397        })
398    }
399}
400
401/// The bounded result of edge translation, ready for the trusted interior UCAN
402/// issuer / MAC compiler. It is deliberately not an external UCAN transport
403/// format: UCAN authoring and delegation remain inside HyprStream.
404#[derive(Clone, Debug, PartialEq, Eq)]
405pub struct TranslatedAtprotoAuthorization {
406    /// The enrolled DID whose cached context bounded the translation.
407    pub did: Did,
408    /// Sender binding that must be retained by the local token/UCAN issuer.
409    pub dpop_binding: VerifiedDpopBinding,
410    /// Exact local capabilities to be authored into an interior UCAN.
411    pub capabilities: Vec<crate::auth::ucan::capability::Capability>,
412    /// Corresponding maximum MAC labels, checked against the cached context.
413    pub maximum_labels: Vec<SecurityLabel>,
414}
415
416#[cfg(test)]
417#[allow(clippy::unwrap_used, clippy::expect_used)]
418mod tests {
419    use super::*;
420    use crate::crypto::pq::ml_dsa_generate_keypair;
421    use crate::identity::{IdentityKeyCandidate, IdentityKeys, MlDsaVk};
422
423    const DID_WEB: &str = "did:web:peer.example";
424
425    fn admitted(did: Option<&str>, key: [u8; 32]) -> AdmittedIdentity {
426        AdmittedIdentity {
427            origin: "https://peer.example".to_owned(),
428            did: did.map(str::to_owned),
429            key,
430        }
431    }
432
433    fn an_ml_dsa_vk() -> MlDsaVk {
434        ml_dsa_generate_keypair().1
435    }
436
437    fn classical_keys(ed25519: [u8; 32]) -> IdentityKeys {
438        IdentityKeys::single_ed25519("did:web:peer.example#mesh", ed25519)
439    }
440
441    fn hybrid_keys(ed25519: [u8; 32]) -> IdentityKeys {
442        IdentityKeys::new(vec![IdentityKeyCandidate {
443            id: "did:web:peer.example#mesh".to_owned(),
444            ed25519,
445            ml_dsa_65: Some(an_ml_dsa_vk()),
446        }])
447    }
448
449    /// Fixture resolver returning fixed key material — the #549 stand-in for #579,
450    /// mirroring `admission.rs`'s `FixtureDoc`/`FailingResolve` test doubles.
451    struct FixtureResolver(IdentityKeys);
452    impl IdentityResolver for FixtureResolver {
453        fn resolve_identity_keys(&self, _did: &Did) -> Result<IdentityKeys> {
454            Ok(self.0.clone())
455        }
456    }
457
458    /// Fixture resolver that always fails — exercises the fail-closed path.
459    struct FailingResolver;
460    impl IdentityResolver for FailingResolver {
461        fn resolve_identity_keys(&self, did: &Did) -> Result<IdentityKeys> {
462            Err(anyhow!("simulated resolution failure for {did}"))
463        }
464    }
465
466    #[test]
467    fn classical_peer_enrolls_at_classical_assurance() {
468        let keys = classical_keys([7u8; 32]);
469        let gw = AtprotoPerimeterGateway::new(FixtureResolver(keys));
470        let peer = gw
471            .enroll(&admitted(Some(DID_WEB), [7u8; 32]))
472            .expect("classical must enroll");
473
474        assert_eq!(peer.assurance, Assurance::Classical);
475        assert_eq!(peer.context.assurance(), Assurance::Classical);
476        // ZSP edge ceiling: Internal level, no compartments.
477        assert_eq!(peer.context.level(), Level::Internal);
478        assert!(peer.context.compartments().is_empty());
479        assert_eq!(peer.channel_key, [7u8; 32]);
480        assert_eq!(peer.did.as_str(), DID_WEB);
481    }
482
483    #[test]
484    fn pqhybrid_peer_enrolls_at_pqhybrid_assurance() {
485        let keys = hybrid_keys([9u8; 32]);
486        let gw = AtprotoPerimeterGateway::new(FixtureResolver(keys));
487        let peer = gw
488            .enroll(&admitted(Some(DID_WEB), [9u8; 32]))
489            .expect("pq-hybrid must enroll");
490
491        assert_eq!(peer.assurance, Assurance::PqHybrid);
492        assert_eq!(peer.context.assurance(), Assurance::PqHybrid);
493    }
494
495    #[test]
496    fn unverified_resolution_fails_closed() {
497        let keys = IdentityKeys::default();
498        let gw = AtprotoPerimeterGateway::new(FixtureResolver(keys));
499        assert!(gw.enroll(&admitted(Some(DID_WEB), [0u8; 32])).is_err());
500    }
501
502    #[test]
503    fn resolver_error_fails_closed() {
504        let gw = AtprotoPerimeterGateway::new(FailingResolver);
505        assert!(gw.enroll(&admitted(Some(DID_WEB), [1u8; 32])).is_err());
506    }
507
508    #[test]
509    fn missing_did_fails_closed() {
510        // Admission matched via JWKS fallback only — no DID to resolve.
511        let keys = classical_keys([2u8; 32]);
512        let gw = AtprotoPerimeterGateway::new(FixtureResolver(keys));
513        assert!(gw.enroll(&admitted(None, [2u8; 32])).is_err());
514    }
515
516    #[test]
517    fn candidate_set_without_admitted_signer_fails_closed() {
518        let keys = classical_keys([4u8; 32]);
519        let gw = AtprotoPerimeterGateway::new(FixtureResolver(keys));
520        assert!(gw.enroll(&admitted(Some(DID_WEB), [3u8; 32])).is_err());
521    }
522
523    #[test]
524    fn overlap_selects_each_admitted_signer_then_rejects_the_retired_candidate() {
525        let old = [30u8; 32];
526        let new = [31u8; 32];
527        let overlap = IdentityKeys::new(vec![
528            IdentityKeyCandidate {
529                id: "did:web:peer.example#mesh-old".to_owned(),
530                ed25519: old,
531                ml_dsa_65: None,
532            },
533            IdentityKeyCandidate {
534                id: "did:web:peer.example#mesh-new".to_owned(),
535                ed25519: new,
536                ml_dsa_65: Some(an_ml_dsa_vk()),
537            },
538        ]);
539        let old_peer = AtprotoPerimeterGateway::new(FixtureResolver(overlap.clone()))
540            .enroll(&admitted(Some(DID_WEB), old))
541            .expect("draining key remains accepted during overlap");
542        let new_peer = AtprotoPerimeterGateway::new(FixtureResolver(overlap))
543            .enroll(&admitted(Some(DID_WEB), new))
544            .expect("new key is accepted during overlap");
545        assert_eq!(old_peer.assurance, Assurance::Classical);
546        assert_eq!(new_peer.assurance, Assurance::PqHybrid);
547
548        let retired = IdentityKeys::single_ed25519("did:web:peer.example#mesh-new", new);
549        let gateway = AtprotoPerimeterGateway::new(FixtureResolver(retired));
550        assert!(gateway.enroll(&admitted(Some(DID_WEB), old)).is_err());
551    }
552
553    #[test]
554    fn classical_peer_cannot_obtain_pqhybrid_context() {
555        // A classical-key peer, even resolved at the PqHybrid-capable edge, must
556        // clamp to Classical and fail to dominate a PqHybrid object.
557        let keys = classical_keys([4u8; 32]);
558        let gw = AtprotoPerimeterGateway::new(FixtureResolver(keys));
559        let peer = gw.enroll(&admitted(Some(DID_WEB), [4u8; 32])).unwrap();
560
561        let pq_object =
562            SecurityLabel::new(Level::Public, Assurance::PqHybrid, CompartmentSet::EMPTY);
563        assert!(!peer.context.can_access(&pq_object));
564        assert_eq!(peer.context.assurance(), Assurance::Classical);
565    }
566
567    #[test]
568    fn enrollment_store_insert_get_roundtrip() {
569        let keys = classical_keys([5u8; 32]);
570        let gw = AtprotoPerimeterGateway::new(FixtureResolver(keys));
571        let peer = gw.enroll(&admitted(Some(DID_WEB), [5u8; 32])).unwrap();
572
573        let store = EnrollmentStore::new();
574        assert!(store.is_empty());
575        store.insert(peer.clone());
576        assert_eq!(store.len(), 1);
577
578        let got = store
579            .get(&Did::new(DID_WEB.to_owned()))
580            .expect("must round-trip");
581        assert_eq!(got, peer);
582        assert!(store
583            .get(&Did::new("did:web:absent.example".to_owned()))
584            .is_none());
585    }
586
587    #[test]
588    fn native_pq_anchor_is_untouched_by_enrollment() {
589        // The perimeter EnrollmentStore is separate from the native, immutable
590        // KeyedPqTrustStore. Enrolling peers must not touch the native anchor.
591        let native = crate::envelope::KeyedPqTrustStore::new();
592        assert!(native.is_empty());
593
594        let keys = hybrid_keys([6u8; 32]);
595        let gw = AtprotoPerimeterGateway::new(FixtureResolver(keys));
596        let peer = gw.enroll(&admitted(Some(DID_WEB), [6u8; 32])).unwrap();
597
598        let store = EnrollmentStore::new();
599        store.insert(peer);
600        assert_eq!(store.len(), 1);
601
602        // Native anchor still empty — no cross-contamination.
603        assert!(native.is_empty());
604    }
605
606    fn classical_peer() -> EnrolledPeer {
607        let keys = classical_keys([11u8; 32]);
608        AtprotoPerimeterGateway::new(FixtureResolver(keys))
609            .enroll(&admitted(Some(DID_WEB), [11u8; 32]))
610            .unwrap()
611    }
612
613    fn mapping(
614        ability: &str,
615        resource: &str,
616        maximum_label: SecurityLabel,
617    ) -> AtprotoPermissionMapping {
618        use crate::auth::ucan::capability::{Ability, Capability, Resource};
619        AtprotoPermissionMapping::new(
620            Capability::new(Resource::new(resource), Ability::new(ability)),
621            maximum_label,
622        )
623        .unwrap()
624    }
625
626    #[test]
627    fn exact_permission_translates_to_bounded_interior_capability() {
628        let permission =
629            AtprotoPermission::new("atproto.transition:read", "ai.hyprstream.model.get").unwrap();
630        let max_label =
631            SecurityLabel::new(Level::Internal, Assurance::Classical, CompartmentSet::EMPTY);
632        let translator = AtprotoPermissionTranslator::new([(
633            permission.clone(),
634            mapping("read", "mac://model/qwen3", max_label),
635        )])
636        .unwrap();
637
638        let result = translator
639            .translate(
640                &classical_peer(),
641                VerifiedDpopBinding::from_verified_jkt("verified-jkt").unwrap(),
642                &[permission],
643            )
644            .unwrap();
645
646        assert_eq!(result.did.as_str(), DID_WEB);
647        assert_eq!(result.dpop_binding.jkt(), "verified-jkt");
648        assert_eq!(result.capabilities.len(), 1);
649        assert_eq!(result.capabilities[0].ability.as_str(), "read");
650        assert_eq!(
651            result.capabilities[0].resource.as_str(),
652            "mac://model/qwen3"
653        );
654        assert_eq!(result.maximum_labels, vec![max_label]);
655    }
656
657    #[test]
658    fn unmappable_scope_or_lexicon_fails_closed() {
659        let known =
660            AtprotoPermission::new("atproto.transition:read", "ai.hyprstream.model.get").unwrap();
661        let translator = AtprotoPermissionTranslator::new([(
662            known,
663            mapping(
664                "read",
665                "mac://model/qwen3",
666                SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY),
667            ),
668        )])
669        .unwrap();
670        let unknown =
671            AtprotoPermission::new("atproto.transition:write", "ai.hyprstream.model.get").unwrap();
672
673        assert!(translator
674            .translate(
675                &classical_peer(),
676                VerifiedDpopBinding::from_verified_jkt("verified-jkt").unwrap(),
677                &[unknown],
678            )
679            .is_err());
680    }
681
682    #[test]
683    fn mapped_permission_cannot_raise_cached_assurance_or_clearance() {
684        let permission =
685            AtprotoPermission::new("atproto.transition:read", "ai.hyprstream.model.get").unwrap();
686        let translator = AtprotoPermissionTranslator::new([(
687            permission.clone(),
688            mapping(
689                "read",
690                "mac://model/qwen3",
691                SecurityLabel::new(Level::Public, Assurance::PqHybrid, CompartmentSet::EMPTY),
692            ),
693        )])
694        .unwrap();
695
696        assert!(translator
697            .translate(
698                &classical_peer(),
699                VerifiedDpopBinding::from_verified_jkt("verified-jkt").unwrap(),
700                &[permission],
701            )
702            .is_err());
703    }
704
705    #[test]
706    fn translator_rejects_wildcard_capabilities_and_duplicate_mappings() {
707        use crate::auth::ucan::capability::{Ability, Capability, Resource};
708        let label = SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY);
709        assert!(AtprotoPermissionMapping::new(
710            Capability::new(Resource::new("mac://model/*"), Ability::new("read")),
711            label,
712        )
713        .is_err());
714        assert!(AtprotoPermissionMapping::new(
715            Capability::new(Resource::new("mac://model/qwen3"), Ability::new("read/*")),
716            label,
717        )
718        .is_err());
719
720        let permission =
721            AtprotoPermission::new("atproto.transition:read", "ai.hyprstream.model.get").unwrap();
722        let approved = mapping("read", "mac://model/qwen3", label);
723        assert!(AtprotoPermissionTranslator::new([
724            (permission.clone(), approved.clone()),
725            (permission, approved),
726        ])
727        .is_err());
728    }
729
730    #[test]
731    fn empty_permissions_and_missing_dpop_binding_fail_closed() {
732        let translator = AtprotoPermissionTranslator::default();
733        assert!(VerifiedDpopBinding::from_verified_jkt("").is_err());
734        assert!(translator
735            .translate(
736                &classical_peer(),
737                VerifiedDpopBinding::from_verified_jkt("verified-jkt").unwrap(),
738                &[],
739            )
740            .is_err());
741    }
742}