Skip to main content

hyprstream_core/services/
policy.rs

1//! Policy service for authorization checks over ZMQ
2//!
3//! Wraps PolicyManager and exposes it as a RequestService.
4//! Handlers are async and use `.await` directly (compatible with single-threaded runtime).
5
6use async_trait::async_trait;
7#[cfg(feature = "postgres")]
8mod federate_admission;
9use crate::auth::policy_templates;
10use crate::auth::PolicyManager;
11use crate::services::generated::policy_client::{
12    dispatch_policy, serialize_response, PolicyHandler,
13};
14use crate::services::{EnvelopeContext, RequestService};
15use anyhow::{anyhow, Result};
16use git2db::{Git2DB, RepoId};
17use hyprstream_pds::repo_authority::is_path_form_did_web;
18use hyprstream_rpc::prelude::*;
19use hyprstream_rpc::transport::TransportConfig;
20use hyprstream_rpc_std::policy_client::{
21    AddGrouping, ApplyDraft, ApplyTemplate, CheckCredentialRevocation, CheckSession,
22    DepositWrappedKeys, DraftStatus, ErrorInfo, EventPrefixAccess, ExchangeDelegated, ExchangeWit,
23    GetDiff, GetHistory, GetPendingSubscribers, Grouping, IssueToken, IssueTokenProfile,
24    MediatedPolicyCheck, PendingSubscribers, PolicyCheck, PolicyCheckBatch, PolicyCheckBatchResult,
25    PolicyHistory, PolicyHistoryEntry, PolicyInfo, PolicyResponseVariant, PolicyRule,
26    RefreshServiceTokenRequest, RegisterEventPrefix, RegisterServiceKey, RegisterSession,
27    RemoveGrouping, ResolveServiceKey, RevokeCredential, RevokeSession, RollbackPolicy, ScopeList,
28    ServiceKeyCandidate, ServiceKeyResponse, SetBranchVisibility, SubscribeEventPrefix, TokenInfo,
29};
30use std::collections::HashMap;
31use std::sync::Arc;
32use tokio::sync::{Mutex, RwLock};
33use tracing::{debug, info, trace, warn};
34
35fn enrolled_user_clearance_for_issue(
36    profile: IssueTokenProfile,
37    required: bool,
38    subject: &str,
39    resolver: &(dyn Fn(&str) -> Option<hyprstream_rpc::auth::mac::SecurityLabel> + Send + Sync),
40) -> Option<hyprstream_rpc::auth::mac::SecurityLabel> {
41    if required
42        || matches!(
43            profile,
44            IssueTokenProfile::InteractiveSession | IssueTokenProfile::Rfc8693
45        )
46    {
47        resolver(subject).map(|clearance| {
48            let context = hyprstream_rpc::auth::mac::SecurityContext::from_clearance(
49                clearance,
50                hyprstream_rpc::auth::mac::VerifiedKeyMaterial::Classical,
51            );
52            *context.clearance()
53        })
54    } else {
55        None
56    }
57}
58
59#[cfg(feature = "postgres")]
60#[path = "policy_inventory.rs"]
61pub(in crate::services) mod inventory;
62
63/// Evaluate a policy check on behalf of an already-verified upstream caller.
64///
65/// The compatibility `PolicyCheck.subject/domain` fields are never identity
66/// evidence. A service that mediates a user request relays the original bearer
67/// in its signed envelope so PolicyService can independently verify both the
68/// user and the hosted-account tenant.
69pub(crate) async fn check_with_verified_bearer(
70    client: &hyprstream_rpc_std::policy_client::PolicyClient,
71    request: &PolicyCheck,
72    bearer: Option<&str>,
73    upstream_subject: &Subject,
74) -> Result<bool> {
75    check_with_holder_evidence(client, request, bearer, upstream_subject, None).await
76}
77
78/// Service credentials are holder-bound, not transferable bearer authority.
79/// Authenticate the mediator with its own primary credential and prove the
80/// original service caller with the signed request received at ingress.
81pub(crate) async fn check_with_holder_evidence(
82    client: &hyprstream_rpc_std::policy_client::PolicyClient,
83    request: &PolicyCheck,
84    bearer: Option<&str>,
85    upstream_subject: &Subject,
86    evidence: Option<&[u8]>,
87) -> Result<bool> {
88    if bearer.is_some()
89        && !upstream_subject.is_federated()
90        && upstream_subject
91            .name()
92            .is_some_and(|name| name.starts_with("service:"))
93    {
94        let evidence = evidence.ok_or_else(|| {
95            anyhow!("service-mediated policy check requires original holder evidence")
96        })?;
97        return client
98            .check_mediated(&MediatedPolicyCheck {
99                evidence: evidence.to_vec().into(),
100                resource: request.resource.clone(),
101                operation: request.operation.clone(),
102            })
103            .await;
104    }
105    match bearer {
106        Some(token) => {
107            client
108                .clone()
109                .with_delegated_bearer(token.to_owned())
110                .check(request)
111                .await
112        }
113        None => {
114            anyhow::ensure!(
115                !upstream_subject.is_federated()
116                    && upstream_subject
117                        .name()
118                        .is_some_and(|name| { name == "system" || name.starts_with("service:") }),
119                "service-mediated user policy check requires a verified upstream bearer"
120            );
121            client.check(request).await
122        }
123    }
124}
125
126/// Intersect an external delegated user's signed scope ceiling with a
127/// read/inference Policy check. Wildcards cover only their own axis; a token
128/// cannot turn a read grant into inference or an unrelated resource grant.
129fn delegated_resource_scope_allows(
130    claims: &hyprstream_rpc::auth::Claims,
131    resource: &str,
132    operation: &str,
133) -> bool {
134    let action = match operation {
135        "query" | "read" | "query.status" => "read",
136        "infer" | "infer.generate" => "infer",
137        _ => return false,
138    };
139    let Some((kind, identifier)) = resource.split_once(':') else {
140        return false;
141    };
142    if kind.is_empty() || identifier.is_empty() {
143        return false;
144    }
145    claims.granted_scopes().any(|granted| {
146        let Ok(scope) = hyprstream_rpc::auth::Scope::parse(granted) else {
147            return false;
148        };
149        let action_allowed = scope.action == action
150            || (action == "read"
151                && matches!(operation, "query" | "query.status")
152                && kind == "model"
153                && identifier != "Status"
154                && scope.action == "infer");
155        action_allowed
156            && (scope.resource == kind || scope.resource == "*")
157            && (scope.identifier == identifier || scope.identifier == "*")
158    })
159}
160
161// ============================================================================
162// PolicyService (server-side)
163// ============================================================================
164
165/// Policy service that wraps PolicyManager.
166/// Receives policy check requests over ZMQ and delegates to PolicyManager.
167/// Per-prefix event state (blind key relay).
168///
169/// PolicyService stores opaque wrapped key blobs — it never sees plaintext
170/// group keys or wrap keys. The publisher wraps directly against subscriber
171/// pubkeys via DH.
172struct EventPrefixState {
173    owner: String,
174    publisher_pubkey: [u8; 32],
175    schema: String,
176    /// Subscriber ephemeral pubkeys, keyed by Blake3 hash of pubkey.
177    subscriber_pubkeys: HashMap<[u8; 32], [u8; 32]>,
178    /// Opaque wrapped key blobs deposited by the publisher, keyed by subscriber pubkey hash.
179    wrapped_keys: HashMap<[u8; 32], Vec<u8>>,
180}
181
182#[derive(Clone, Debug, Eq, Hash, PartialEq)]
183struct EventPrefixKey {
184    tenant: String,
185    prefix: String,
186}
187impl EventPrefixKey {
188    fn new(tenant: String, prefix: &str) -> Self {
189        Self {
190            tenant,
191            prefix: prefix.to_owned(),
192        }
193    }
194}
195fn cross_tenant_prefix_shadow(a: &EventPrefixKey, b: &EventPrefixKey) -> bool {
196    a.tenant != b.tenant
197        && a.prefix != b.prefix
198        && (a.prefix.starts_with(&b.prefix) || b.prefix.starts_with(&a.prefix))
199}
200#[derive(Debug, Eq, PartialEq)]
201enum EventPrefixRegistrationError {
202    OwnedByAnotherSubject,
203    CrossTenantShadow,
204}
205fn validate_event_prefix_registration(
206    prefixes: &HashMap<EventPrefixKey, EventPrefixState>,
207    key: &EventPrefixKey,
208    owner: &str,
209) -> Result<(), EventPrefixRegistrationError> {
210    if prefixes.get(key).is_some_and(|state| state.owner != owner) {
211        return Err(EventPrefixRegistrationError::OwnedByAnotherSubject);
212    }
213    if prefixes
214        .keys()
215        .any(|existing| cross_tenant_prefix_shadow(existing, key))
216    {
217        return Err(EventPrefixRegistrationError::CrossTenantShadow);
218    }
219    Ok(())
220}
221
222/// Default revocation-publication horizon: covers the hard 30-day
223/// service-JWT renewal clamp with margin. Production construction derives
224/// the horizon from the configured issuance maxima instead — see
225/// `PolicyService::with_revocation_max_ttl_secs`.
226const DEFAULT_REVOCATION_MAX_TTL_SECS: i64 = 45 * 24 * 3600;
227
228pub struct PolicyService {
229    /// Source-only OAuth→Policy challenge RPC. No production installer yet.
230    #[cfg(feature = "postgres")]
231    federate_admission: Option<Arc<federate_admission::AdmissionService>>,
232    /// Disabled until the authenticated serving adapter and causal RPC tests
233    /// are installed. No constructor currently populates this field.
234    #[cfg(feature = "postgres")]
235    federate_request_use: Option<federate_admission::RequestUseReader>,
236    // Business logic
237    policy_manager: Arc<PolicyManager>,
238    signing_key: Arc<SigningKey>,
239    /// Purpose-derived key for JWT token signing (isolated from envelope signing)
240    jwt_signing_key: SigningKey,
241    token_config: crate::config::TokenConfig,
242    /// Supported scopes computed once at construction from ServiceFactory inventory
243    supported_scopes: Vec<String>,
244    /// Shared git2db registry for git operations on .registry repo
245    git2db: Arc<RwLock<Git2DB>>,
246    /// Serializes role mutation, persistence, rollback, and audit commit as a
247    /// single local control-plane transaction.
248    policy_write_lock: Mutex<()>,
249    /// RepoId of the .registry self-tracked entry
250    registry_repo_id: RepoId,
251    /// Exact HTTP resource audiences accepted only from enrolled service relays.
252    delegated_resource_audiences: Option<(String, String)>,
253    /// Default audience for issued tokens (OAuth issuer URL, shared instance identifier).
254    /// Used when IssueToken.audience is empty, ensuring all tokens get an `aud` claim.
255    default_audience: Option<String>,
256    /// JWT key source for verifying JWTs (local and federated).
257    jwt_key_source: Option<std::sync::Arc<dyn hyprstream_rpc::auth::JwtKeySource>>,
258    // Infrastructure (for Spawnable)
259    transport: TransportConfig,
260    /// Event prefix state for secure event transport (Phase 7).
261    /// PolicyService is a blind relay — stores opaque wrapped blobs, never plaintext keys.
262    event_prefixes: RwLock<HashMap<EventPrefixKey, EventPrefixState>>,
263    /// ES256 (P-256) key rotation store for DPoP/atproto interop.
264    es256_key_store: Option<Arc<crate::auth::Es256SigningKeyStore>>,
265    /// ML-DSA-65 key rotation store for PQ-hybrid composite token issuance.
266    ml_dsa_key_store: Option<Arc<crate::auth::MlDsaSigningKeyStore>>,
267    /// Authority-owned enrollment lookup for MAC-labeled credentials.
268    token_clearance_resolver:
269        Arc<dyn Fn(&str) -> Option<hyprstream_rpc::auth::mac::SecurityLabel> + Send + Sync>,
270    /// Maximum retention horizon the revocation authority accepts for a
271    /// published entry (`expires_at - now`). Derived at construction from the
272    /// configured issuance maxima so no issuable credential can outlive its
273    /// revocability — see `with_revocation_max_ttl_secs`.
274    revocation_max_ttl_secs: i64,
275    /// Fail-closed authority for derived `AsOriginator` delegation edges
276    /// (`exchangeDelegated`). `None` (uninstalled) ⇒ every delegation DENIES;
277    /// WS-E installs the reviewed `DispatchCallManifest` implementation. See
278    /// [`DelegationEdgeAuthorizer`].
279    delegation_edge_authorizer: Option<Arc<dyn DelegationEdgeAuthorizer>>,
280    /// Optional injected service-enrollment manifest override. `None` uses the
281    /// process-global manifest (`global_service_enrollment`). Set in isolated
282    /// fixtures so a test can supply its own enrollment without touching the
283    /// set-once process global. See [`Self::enrollment`].
284    enrollment_manifest: Option<Arc<crate::auth::service_enrollment::ServiceEnrollmentManifest>>,
285    /// Fail-closed authoritative primary-enrollment resolver for user/classical
286    /// source credentials (frozen A §5/T1). `None` (uninstalled) ⇒ a user
287    /// primary confirmation DENIES; WS-C installs the real resolver. See
288    /// [`PrimaryEnrollmentResolver`].
289    primary_enrollment_resolver: Option<Arc<dyn PrimaryEnrollmentResolver>>,
290}
291
292impl PolicyService {
293    /// Create a new policy service with infrastructure
294    pub fn new(
295        policy_manager: Arc<PolicyManager>,
296        signing_key: Arc<SigningKey>,
297        token_config: crate::config::TokenConfig,
298        git2db: Arc<RwLock<Git2DB>>,
299        transport: TransportConfig,
300    ) -> Self {
301        let registry_repo_id = RepoId::from_uuid(git2db::registry::registry_self_uuid());
302        let jwt_signing_key =
303            hyprstream_rpc::node_identity::derive_purpose_key(&signing_key, "hyprstream-jwt-v1");
304        Self {
305            #[cfg(feature = "postgres")]
306            federate_admission: None,
307            #[cfg(feature = "postgres")]
308            federate_request_use: None,
309            policy_manager,
310            signing_key,
311            jwt_signing_key,
312            token_config,
313            supported_scopes: compute_supported_scopes(),
314            git2db,
315            policy_write_lock: Mutex::new(()),
316            registry_repo_id,
317            delegated_resource_audiences: None,
318            default_audience: None,
319            jwt_key_source: None,
320            transport,
321            event_prefixes: RwLock::new(HashMap::new()),
322            es256_key_store: None,
323            ml_dsa_key_store: None,
324            token_clearance_resolver: Arc::new(|subject| {
325                let policy = crate::mac::compiled_policy()?;
326                policy.clearance_for(subject)
327            }),
328            revocation_max_ttl_secs: DEFAULT_REVOCATION_MAX_TTL_SECS,
329            delegation_edge_authorizer: None,
330            enrollment_manifest: None,
331            primary_enrollment_resolver: None,
332        }
333    }
334
335    /// Install the stateless Federate runtime after the factory has verified
336    /// the trusted service enrollment and complete collision inventory. Only
337    /// shared request-proof replay uses PostgreSQL; credentials and `sid` do
338    /// not require a session-row lookup.
339    #[cfg(feature = "postgres")]
340    pub(super) fn with_federate_runtime(
341        mut self,
342        enrollment: Arc<crate::auth::service_enrollment::ServiceEnrollmentManifest>,
343        collision_inventory: hyprstream_session_store::primary::CollisionInventory,
344        host: crate::services::oauth::federate_source::FederateHost,
345        tui_client: Option<&str>,
346    ) -> Self {
347        let admission = Arc::new(federate_admission::AdmissionService::configured(
348            Arc::clone(&self.policy_manager),
349            enrollment,
350            collision_inventory,
351            None,
352            host,
353            tui_client,
354        ));
355        self.federate_request_use = Some(federate_admission::RequestUseReader::new(
356            Arc::clone(&admission),
357            None,
358        ));
359        self.federate_admission = Some(admission);
360        self
361    }
362
363    /// Install the fail-closed authoritative primary-enrollment resolver (WS-C's
364    /// enrollment store) used to confirm a user/classical source credential's
365    /// `cnf`. Without it, user primaries deny.
366    pub fn with_primary_enrollment_resolver(
367        mut self,
368        resolver: Arc<dyn PrimaryEnrollmentResolver>,
369    ) -> Self {
370        self.primary_enrollment_resolver = Some(resolver);
371        self
372    }
373
374    /// Install the fail-closed delegation-edge authorizer (WS-E's reviewed
375    /// `DispatchCallManifest`). Without it, `exchangeDelegated` denies every
376    /// edge — the end-state default, never a bypass.
377    pub fn with_delegation_edge_authorizer(
378        mut self,
379        authorizer: Arc<dyn DelegationEdgeAuthorizer>,
380    ) -> Self {
381        self.delegation_edge_authorizer = Some(authorizer);
382        self
383    }
384
385    /// Override the service-enrollment manifest for an isolated fixture (avoids
386    /// the set-once process global). **Test-only** — production is single
387    /// authority (the process global); there is no production manifest-injection
388    /// path, so this setter is compiled only under `cfg(test)`.
389    #[cfg(test)]
390    pub fn with_enrollment_manifest(
391        mut self,
392        manifest: Arc<crate::auth::service_enrollment::ServiceEnrollmentManifest>,
393    ) -> Self {
394        self.enrollment_manifest = Some(manifest);
395        self
396    }
397
398    /// The effective service-enrollment manifest: the injected override if set,
399    /// else the process-global manifest.
400    fn enrollment(
401        &self,
402    ) -> Option<Arc<crate::auth::service_enrollment::ServiceEnrollmentManifest>> {
403        self.enrollment_manifest
404            .clone()
405            .or_else(|| crate::auth::service_enrollment::global_service_enrollment().cloned())
406    }
407
408    /// Set the revocation-publication horizon. The service factory computes
409    /// this as max(every configured issuance maximum) plus a clock-skew
410    /// margin, so an operator raising token TTLs automatically raises the
411    /// authority's retention horizon — issuance and revocation horizons are
412    /// bound by construction rather than by a shared default.
413    pub fn with_revocation_max_ttl_secs(mut self, secs: i64) -> Self {
414        self.revocation_max_ttl_secs = secs;
415        self
416    }
417
418    /// Install exact MCP and OpenAI resource audiences for verified delegated
419    /// Policy.check requests. No setting means native issuer audience only.
420    pub fn with_delegated_resource_audiences(mut self, mcp: String, oai: String) -> Self {
421        self.delegated_resource_audiences = Some((mcp, oai));
422        self
423    }
424
425    /// Set the default audience for issued tokens (typically the OAuth issuer URL).
426    pub fn with_default_audience(mut self, audience: String) -> Self {
427        self.default_audience = Some(audience);
428        self
429    }
430
431    /// Override enrollment lookup for an isolated service fixture.
432    pub fn with_token_clearance_resolver(
433        mut self,
434        resolver: Arc<
435            dyn Fn(&str) -> Option<hyprstream_rpc::auth::mac::SecurityLabel> + Send + Sync,
436        >,
437    ) -> Self {
438        self.token_clearance_resolver = resolver;
439        self
440    }
441
442    /// Sign a token with the mandatory hybrid suite (Fu3/#677).
443    ///
444    /// The composite PQ signature (EdDSA + ML-DSA-65) is used under a Hybrid
445    /// policy. If no ML-DSA-65 signing key is provisioned, this returns `Err`
446    /// rather than silently minting a classical-only token — mirroring
447    /// [`crate::mac::audit::CoseAuditSigner`],
448    /// which the S7 audit path already gates the same way. Previously this seam
449    /// picked composite-vs-classical by *keystore state*, so a Hybrid node with
450    /// an empty/rotating ML-DSA store quietly downgraded minted tokens.
451    async fn sign_token(
452        &self,
453        claims: &hyprstream_rpc::auth::Claims,
454        is_service: bool,
455    ) -> Result<String> {
456        // Sign against the SAME configured local authority the source
457        // verification path resolves keys from: the policy service's own
458        // `jwt_key_source` composite ledger. In production the factory always
459        // installs a `ClusterKeySource` (whose ledger defaults to the
460        // process-global authority, so behaviour is identical); an isolated
461        // fixture supplies its own via `with_composite_key_set`, keeping
462        // verification and mint on ONE exact issuer-scoped ledger. Fail closed
463        // if no key source is configured — never fall back to the global
464        // authority, which would reopen cross-issuer ambiguity.
465        let key_source = self
466            .jwt_key_source
467            .as_ref()
468            .ok_or_else(|| anyhow!("no configured key source for token signing"))?;
469        let snapshot = key_source
470            .composite_key_set()
471            .mint_snapshot()
472            .map_err(|error| anyhow!("composite authority unavailable: {error}"))?;
473        let signing = snapshot
474            .active_signing_pair(hyprstream_rpc::auth::CompositePairRole::Policy)
475            .and_then(hyprstream_rpc::auth::CompositeKeyPair::signing_keys);
476        let Some((ml_key, ed_key)) = signing else {
477            warn!("no authorized active Policy composite pair; refusing to mint");
478            return Err(anyhow!("hybrid token signing pair not provisioned"));
479        };
480        Ok(if is_service {
481            crate::auth::jwt::encode_composite_service_jwt(claims, &ml_key, &ed_key)
482        } else {
483            crate::auth::jwt::encode_composite_ml_dsa_65_ed25519(claims, &ml_key, &ed_key)
484        })
485    }
486
487    /// Set the JWT key source for verifying JWTs (local and federated).
488    pub fn with_jwt_key_source(
489        mut self,
490        src: std::sync::Arc<dyn hyprstream_rpc::auth::JwtKeySource>,
491    ) -> Self {
492        self.jwt_key_source = Some(src);
493        self
494    }
495
496    /// Resolve the workload-session disposition for a service-credential renewal
497    /// (v16 §3.3), as a pure function of the canonical session registry and the
498    /// authoritative family policy. The renewal handler applies the result to
499    /// the renewed claims; extracting it keeps the security-critical
500    /// check-BEFORE-narrowing ordering testable without the signing/persistence
501    /// boundary.
502    ///
503    /// - A carried session (`old_wsid = Some`) is checked for revocation FIRST,
504    ///   independent of `family_policy` — a revoked/expired/unresolvable session
505    ///   DENIES, so removing the family policy can never launder a revoked family
506    ///   into an unsessioned renewal. A live session is re-stamped only while the
507    ///   family remains enrolled; a narrowed (policy-removed) family drops it.
508    /// - No carried session (`old_wsid = None`) creates one only for a family
509    ///   EXPLICITLY enrolled (`family_policy == Some(true)`); a legacy-default or
510    ///   disabled family carries none.
511    async fn resolve_renewal_workload_session(
512        &self,
513        issuer: &str,
514        subject: &str,
515        tenant: &str,
516        now: i64,
517        family_policy: Option<bool>,
518        old_wsid: Option<&str>,
519    ) -> RenewalWorkloadSession {
520        // No manifest at all: legacy continuity (an unenrolled deployment keeps
521        // renewing). An enrolled family with `workload_session = false` is a
522        // deliberate policy, NOT legacy — `family_policy` distinguishes them.
523        let family_allowed = family_policy.unwrap_or(true);
524        match (old_wsid, family_allowed) {
525            (Some(wsid), allowed) => {
526                // A carried workload session must be ACTIVE before renewal,
527                // regardless of current enrollment policy — the revocation
528                // check runs BEFORE the narrowing branch below.
529                let session_key =
530                    hyprstream_rpc::auth::SessionKey::workload(issuer.to_owned(), wsid.to_owned());
531                let Some(registry) = hyprstream_rpc::auth::global_session_registry() else {
532                    return RenewalWorkloadSession::Deny {
533                        code: "UNAVAILABLE",
534                        message: "session registry is not initialized".to_owned(),
535                    };
536                };
537                if registry.is_revoked(&session_key).await {
538                    return RenewalWorkloadSession::Deny {
539                        code: "SESSION_REVOKED",
540                        message: "workload session is revoked or expired; re-bootstrap the service credential".to_owned(),
541                    };
542                }
543                // Only a still-enrolled family carries the session forward;
544                // `!allowed` is deliberate narrowing of a LIVE family — the
545                // session ID does not survive this renewal (the session itself
546                // expires naturally; no credential carries it forward).
547                RenewalWorkloadSession::Stamp(allowed.then(|| wsid.to_owned()))
548            }
549            (None, true) => {
550                // First online renewal of an ENROLLED family creates the
551                // workload session with the canonical registry; a legacy-default
552                // family (`family_policy == None`) manufactures no session.
553                if family_policy != Some(true) {
554                    return RenewalWorkloadSession::Stamp(None);
555                }
556                use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
557                use rand::RngCore;
558                let mut id_bytes = [0u8; 32];
559                rand::rngs::OsRng.fill_bytes(&mut id_bytes);
560                let wsid = URL_SAFE_NO_PAD.encode(id_bytes);
561                let Some(registry) = hyprstream_rpc::auth::global_session_registry() else {
562                    return RenewalWorkloadSession::Deny {
563                        code: "UNAVAILABLE",
564                        message: "session registry is not initialized".to_owned(),
565                    };
566                };
567                let session_state = hyprstream_rpc::auth::SessionState {
568                    subject: subject.to_owned(),
569                    tenant: tenant.to_owned(),
570                    kind: hyprstream_rpc::auth::SessionKind::Workload,
571                    created_at: now,
572                    expires_at: now + self.revocation_max_ttl_secs,
573                    status: hyprstream_rpc::auth::ActiveOrRevoked::Active,
574                    clearance_epoch: 0,
575                };
576                if let Err(e) = registry
577                    .register_session(
578                        hyprstream_rpc::auth::SessionKey::workload(issuer.to_owned(), wsid.clone()),
579                        session_state,
580                    )
581                    .await
582                {
583                    return RenewalWorkloadSession::Deny {
584                        code: "UNAVAILABLE",
585                        message: format!("workload session registration failed: {e}"),
586                    };
587                }
588                RenewalWorkloadSession::Stamp(Some(wsid))
589            }
590            (None, false) => RenewalWorkloadSession::Stamp(None),
591        }
592    }
593
594    /// Attach the ES256 (P-256) key rotation store.
595    pub fn with_es256_key_store(mut self, store: Arc<crate::auth::Es256SigningKeyStore>) -> Self {
596        self.es256_key_store = Some(store);
597        self
598    }
599
600    /// Attach the ML-DSA-65 key rotation store for composite token issuance.
601    pub fn with_ml_dsa_key_store(mut self, store: Arc<crate::auth::MlDsaSigningKeyStore>) -> Self {
602        self.ml_dsa_key_store = Some(store);
603        self
604    }
605
606    /// Commit only the two policy files; never collect other registry state.
607    async fn stage_and_commit_policies(&self, message: &str) -> Result<String> {
608        let reg = self.git2db.read().await;
609        let handle = reg.repo(&self.registry_repo_id)?;
610        let staging = handle.staging();
611        for path in ["policies/model.conf", "policies/policy.csv"] {
612            staging
613                .add(path)
614                .await
615                .map_err(|e| anyhow!("Failed to stage policy file {path}: {e}"))?;
616        }
617        let staged = staging
618            .staged_files()
619            .await
620            .map_err(|e| anyhow!("Failed to inspect policy staging: {e}"))?;
621        anyhow::ensure!(
622            staged.iter().all(|file| {
623                file.path == std::path::Path::new("policies/model.conf")
624                    || file.path == std::path::Path::new("policies/policy.csv")
625            }),
626            "Refusing policy commit with staged non-policy files"
627        );
628
629        let oid = handle
630            .commit(message)
631            .await
632            .map_err(|e| anyhow!("Failed to commit policy: {e}"))?;
633
634        Ok(oid.to_string())
635    }
636
637    /// Select the Casbin domain for PolicyService itself.
638    ///
639    /// Tenant-bearing callers stay in their authority-verified tenant. The
640    /// policy/OAuth authority is also a global, cross-tenant subsystem: a
641    /// tenantless, authenticated `service:*` principal (or the PolicyService
642    /// authority key itself during bootstrap) therefore remains in the global
643    /// policy domain. Ordinary tenantless identities still fail closed.
644    fn request_domain(&self, ctx: &EnvelopeContext) -> Result<String> {
645        if ctx.verified_tenant().is_some() {
646            return ctx.domain();
647        }
648
649        let subject = ctx.subject();
650        let is_global_service = subject
651            .name()
652            .is_some_and(|name| name.starts_with("service:"))
653            && !subject.is_federated();
654        let is_policy_authority = ctx.cnf == self.signing_key.verifying_key().to_bytes();
655        anyhow::ensure!(
656            is_global_service || is_policy_authority,
657            "authorization denied: no verified tenant domain"
658        );
659        Ok("*".to_owned())
660    }
661}
662
663/// Collect all supported scopes from compile-time schema metadata
664/// via the ServiceFactory inventory. No hardcoded service imports needed.
665///
666/// Scopes use flat format `action:service:*` — coarse-grained per OAuth convention.
667/// Fine-grained authorization is handled by Casbin resource patterns.
668fn compute_supported_scopes() -> Vec<String> {
669    use hyprstream_service::list_factories;
670
671    let mut scopes = std::collections::BTreeSet::new();
672
673    for factory in list_factories() {
674        if let Some(metadata_fn) = factory.metadata {
675            let (service_name, methods) = metadata_fn();
676            for method in methods {
677                // S3 (#547): scope is mandatory at build time, so `method.scope` is
678                // non-empty for every enforced method. An empty scope here can only be a
679                // `$scopeExempt` method (e.g. the authz check itself) — it requires no
680                // grant, so it contributes no advertised scope. No silent "query" default.
681                if method.scope.is_empty() {
682                    continue;
683                }
684                scopes.insert(format!("{}:{}:*", method.scope, service_name));
685            }
686        }
687    }
688
689    scopes.into_iter().collect()
690}
691
692// ============================================================================
693// PolicyHandler implementation (generated trait)
694// ============================================================================
695
696/// Validate an event prefix string.
697///
698/// Rejects empty strings, path traversal (`..`), and Casbin metacharacters (`*`, `#`).
699/// Only allows alphanumeric, `.`, `-`, and `_`.
700fn validate_event_prefix(prefix: &str) -> Result<(), String> {
701    if prefix.is_empty() {
702        return Err("prefix must not be empty".to_owned());
703    }
704    if prefix.len() > 128 {
705        return Err("prefix exceeds 128 characters".to_owned());
706    }
707    if prefix.contains("..") {
708        return Err("prefix must not contain '..'".to_owned());
709    }
710    if !prefix
711        .chars()
712        .all(|c| c.is_alphanumeric() || c == '.' || c == '-' || c == '_')
713    {
714        return Err("prefix may only contain alphanumeric, '.', '-', '_' characters".to_owned());
715    }
716    Ok(())
717}
718
719/// Build the rotation-safe wire projection of a service's published key set.
720///
721/// The scalar verification key is a transition projection for one-key
722/// deployments. Attestation JWTs are bearer credentials: discovery never
723/// serializes them, including in the per-key rotation projection.
724fn published_service_key_response(
725    trust: &hyprstream_service::TrustStore,
726    service_name: &str,
727) -> Result<ServiceKeyResponse> {
728    let keys = trust.published_keys_for_scope(service_name);
729    if keys.is_empty() {
730        anyhow::bail!("service key '{service_name}' not registered");
731    }
732    let singleton = (keys.len() == 1).then(|| &keys[0]);
733    Ok(ServiceKeyResponse {
734        verifying_key: singleton
735            .map(|entry| entry.verifying_key.to_bytes().to_vec())
736            .unwrap_or_default(),
737        service_jwt: None,
738        keys: keys
739            .into_iter()
740            .map(|entry| ServiceKeyCandidate {
741                key_id: entry.key_id,
742                verifying_key: entry.verifying_key.to_bytes().to_vec(),
743                service_jwt: None,
744                not_after: entry.attestation.expires_at,
745            })
746            .collect(),
747    })
748}
749
750/// Confirmation material is mandatory: an absent or malformed `cnf.jwk` must
751/// never turn a valid CA token into authority for arbitrary key material.
752/// Claims for a renewed service JWT.
753///
754/// `aud` is stamped alongside `iss` — the same shape the provisioning path
755/// mints — because strict composite audience validation rejects an aud-less
756/// token on every dispatch, and the on-disk reuse predicate treats a token
757/// that does not bind the local issuer URL in both claims as stale.
758fn renewed_service_claims(
759    subject: String,
760    now: i64,
761    expires_at: i64,
762    issuer: &str,
763    tenant: Option<&str>,
764    cnf_key: &[u8; 32],
765) -> hyprstream_rpc::auth::Claims {
766    let mut claims =
767        hyprstream_rpc::auth::Claims::new(subject, now, expires_at).with_cnf_jwk(cnf_key);
768    if let Some(tenant) = tenant {
769        claims = claims.with_tenant(tenant.to_owned());
770    }
771    if !issuer.is_empty() {
772        claims = claims
773            .with_issuer(issuer.to_owned())
774            .with_audience(Some(issuer.to_owned()));
775    }
776    claims
777}
778
779/// Verify a service JWT presented to `registerServiceKey`.
780///
781/// Hybrid (`ML-DSA-65-Ed25519`) tokens resolve their composite kid through
782/// the same key-source path the dispatch plane uses, with the CA's own
783/// derived pair as the authoritative fallback (PolicyService IS the CA, so it
784/// can reconstruct the exact pair the hybrid service-JWT mint signs with); an
785/// unknown kid fails closed. Classical EdDSA tokens verify against the CA key
786/// only when `policy` permits classical — matching the dispatch alg gate.
787fn verify_service_registration_jwt(
788    service_jwt: &str,
789    key_source: Option<&dyn hyprstream_rpc::auth::JwtKeySource>,
790    ca_jwt_key: &SigningKey,
791    policy: hyprstream_rpc::crypto::CryptoPolicy,
792) -> Result<hyprstream_rpc::auth::Claims> {
793    let is_composite = hyprstream_rpc::auth::jwt::header_alg(service_jwt)
794        .ok()
795        .flatten()
796        .is_some_and(|alg| alg == "ML-DSA-65-Ed25519");
797    if is_composite {
798        let dispatch =
799            hyprstream_rpc::auth::jwt::parse_composite_dispatch(service_jwt, &["wit+jwt"])
800                .map_err(|e| anyhow!("Invalid service JWT: {e}"))?;
801        let pair = key_source
802            .and_then(|ks| ks.composite_pair(dispatch.kid()))
803            .or_else(|| {
804                let pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk(
805                    &hyprstream_rpc::node_identity::derive_mesh_mldsa_key(ca_jwt_key),
806                );
807                let ed_vk = ca_jwt_key.verifying_key();
808                let kid = hyprstream_rpc::auth::composite_kid(&pq_vk, &ed_vk);
809                (kid == dispatch.kid()).then(|| {
810                    hyprstream_rpc::auth::CompositeKeyPair::verifying(
811                        kid,
812                        pq_vk,
813                        ed_vk,
814                        hyprstream_rpc::auth::CompositePairRole::Policy,
815                        hyprstream_rpc::auth::CompositePairState::Active,
816                        0,
817                        i64::MAX,
818                    )
819                })
820            })
821            .ok_or_else(|| anyhow!("Invalid service JWT: unknown composite kid"))?;
822        // Signing-domain separation: service certification is the Policy
823        // domain. The OAuth-role pair legitimately signs browser and workload
824        // WITs (`wit+jwt` too), so accepting its kid here would let anyone
825        // holding an OAuth-plane token mint an installable service identity
826        // with an arbitrary `cnf`. Only Policy-role pairs — the ledger's
827        // Policy slot and the derived CA pair, which is constructed with the
828        // Policy role — may certify service keys.
829        anyhow::ensure!(
830            pair.role() == hyprstream_rpc::auth::CompositePairRole::Policy,
831            "Invalid service JWT: composite pair role is not authorized for service certification"
832        );
833        hyprstream_rpc::auth::jwt::decode_composite(
834            service_jwt,
835            pair.ml_dsa(),
836            pair.ed25519(),
837            None,
838            &dispatch,
839        )
840        .map_err(|e| anyhow!("Invalid service JWT: {e}"))
841    } else {
842        anyhow::ensure!(
843            !policy.uses_pq(),
844            "Invalid service JWT: Hybrid crypto policy requires a post-quantum alg; \
845             classical-only token rejected"
846        );
847        hyprstream_rpc::auth::jwt::decode_with_key(service_jwt, &ca_jwt_key.verifying_key(), None)
848            .map_err(|e| anyhow!("Invalid service JWT: {e}"))
849    }
850}
851
852fn validate_service_key_registration(
853    claims: &hyprstream_rpc::auth::Claims,
854    service_name: &str,
855    verifying_key: &[u8; 32],
856) -> Result<()> {
857    let expected_sub = format!("service:{service_name}");
858    if claims.sub != expected_sub {
859        anyhow::bail!(
860            "JWT subject '{}' does not match service name '{}'",
861            claims.sub,
862            service_name
863        );
864    }
865    let cnf_bytes = claims
866        .cnf_key_bytes()
867        .ok_or_else(|| anyhow!("service JWT must contain a well-formed cnf.jwk"))?;
868    if cnf_bytes != *verifying_key {
869        anyhow::bail!("JWT cnf.jwk does not match provided verifying key");
870    }
871    Ok(())
872}
873
874/// The credential profile of a verified source credential (v16 typ contract).
875#[derive(Clone, Copy, PartialEq, Eq)]
876enum SourceProfile {
877    /// User access token (`at+jwt`).
878    AtJwt,
879    /// Service credential (`wit+jwt`).
880    WitJwt,
881}
882
883/// A verified source credential and the provenance the derived mint requires:
884/// the profile (typ) and the crypto assurance derived from the ACTUAL verified
885/// algorithm (never fabricated).
886struct VerifiedSourceCredential {
887    claims: hyprstream_rpc::auth::Claims,
888    profile: SourceProfile,
889    key_material: hyprstream_rpc::auth::mac::VerifiedKeyMaterial,
890}
891
892/// Verify a presented source credential for the delegated-exchange authority
893/// path (RFC 8693 §4 on-behalf-of). **JWT-only:** this Text seam carries a JWT
894/// `at+jwt`/`wit+jwt`; a CWT source is out of scope and is not handled here (it
895/// would be a separate typed seam). Both the hybrid (composite) and classical
896/// (Ed25519) credential profiles the frozen A profile permits are accepted; the
897/// derived Classical/PqHybrid assurance is taken from the ACTUAL verified
898/// algorithm and the clearance meet/target dominance decides authority.
899///
900/// Trust rule (frozen A profile: trust the issuer key, NOT an internal
901/// typ→role mapping — production signs both `at+jwt` and `wit+jwt` with the
902/// Policy role): the exact `kid` must resolve to an issuer-authorized composite
903/// pair in the trusted key source / ledger and that pair must be within its
904/// validity window; for the classical path the verifying key(s) resolve
905/// strictly from the trusted key source keyed by `expected_issuer` and the
906/// exact `kid`. An untrusted issuer or an unknown/wrong `kid`/key denies. The
907/// JOSE `typ` selects the profile exactly. Issuer-claim equality, revocation,
908/// session, tenant, subject↔profile coherence, and clearance are enforced by
909/// the caller.
910async fn verify_presented_credential(
911    token: &str,
912    key_source: Option<&dyn hyprstream_rpc::auth::JwtKeySource>,
913    expected_issuer: &str,
914) -> Result<VerifiedSourceCredential> {
915    use hyprstream_rpc::auth::mac::VerifiedKeyMaterial;
916
917    let header = hyprstream_rpc::auth::jwt::parse_protected_header(token)
918        .map_err(|e| anyhow!("invalid source credential header: {e}"))?;
919    let profile = match header.typ.as_str() {
920        "at+jwt" => SourceProfile::AtJwt,
921        "wit+jwt" => SourceProfile::WitJwt,
922        other => {
923            anyhow::bail!("invalid source credential typ '{other}' (expected at+jwt or wit+jwt)")
924        }
925    };
926
927    match header.alg.as_str() {
928        "ML-DSA-65-Ed25519" => {
929            // Re-parse for dispatch with the EXACT typ, so the signed header typ
930            // must equal what gated the profile above.
931            let dispatch =
932                hyprstream_rpc::auth::jwt::parse_composite_dispatch(token, &[header.typ.as_str()])
933                    .map_err(|e| anyhow!("invalid source credential: {e}"))?;
934            // Resolve the exact kid to an issuer-AUTHORIZED composite pair via
935            // the configured key source. `ClusterKeySource::composite_pair`
936            // resolves this node's exact-pair ledger AND its out-of-ledger
937            // CA-derived composite pair (which the bootstrap/service-WIT path
938            // signs with, and which is NOT in the global ledger — a global-only
939            // lookup would wrongly reject a legitimate local service WIT).
940            // `FederatedKeySource::composite_pair` delegates only to its local
941            // source, so it never exposes a foreign issuer's pair. The key
942            // source is bound to `expected_issuer`, so a resolved pair is
943            // authorized for it; a kid outside that authority denies.
944            let ks = key_source.ok_or_else(|| {
945                anyhow!("composite source credential requires a trusted key source")
946            })?;
947            anyhow::ensure!(
948                ks.is_trusted(expected_issuer),
949                "source credential issuer is not trusted by this authority"
950            );
951            let pair = ks.composite_pair(dispatch.kid()).ok_or_else(|| {
952                anyhow!("invalid source credential: composite kid is not an issuer-authorized pair")
953            })?;
954            // Pair lifecycle: the signing pair must be within its validity
955            // window AND in a verify-valid state. Active and Drain are both
956            // verify-valid (a Drain pair is rotating out, but tokens it signed
957            // remain valid until expiry); the explicit match fails closed if the
958            // ledger ever grows a non-verifying state.
959            let now = chrono::Utc::now().timestamp();
960            anyhow::ensure!(
961                pair.not_before() <= now && now < pair.expires_at(),
962                "source credential signing pair is outside its validity window"
963            );
964            match pair.state() {
965                hyprstream_rpc::auth::CompositePairState::Active
966                | hyprstream_rpc::auth::CompositePairState::Drain => {}
967            }
968            let claims = hyprstream_rpc::auth::jwt::decode_composite(
969                token,
970                pair.ml_dsa(),
971                pair.ed25519(),
972                None,
973                &dispatch,
974            )
975            .map_err(|e| anyhow!("invalid source credential: {e}"))?;
976            Ok(VerifiedSourceCredential {
977                claims,
978                profile,
979                key_material: VerifiedKeyMaterial::PqHybrid,
980            })
981        }
982        "EdDSA" => {
983            // Classical profile: resolve the verifying key(s) STRICTLY from the
984            // trusted key source keyed by the expected issuer and the exact kid.
985            let ks = key_source.ok_or_else(|| {
986                anyhow!("classical source credential requires a trusted key source")
987            })?;
988            anyhow::ensure!(
989                ks.is_trusted(expected_issuer),
990                "source credential issuer is not trusted by this authority"
991            );
992            // `kid` is a strict selector (present and non-empty per the parsed
993            // header); an unknown/wrong kid resolves to no key and denies.
994            let candidates = ks
995                .get_keys(expected_issuer, Some(&header.kid))
996                .await
997                .map_err(|e| anyhow!("no verifying key for source credential: {e}"))?;
998            anyhow::ensure!(
999                !candidates.is_empty(),
1000                "no verifying key resolved for the source credential kid"
1001            );
1002            let claims = hyprstream_rpc::auth::jwt::decode_with_any_key(token, &candidates, None)
1003                .map_err(|e| anyhow!("invalid source credential: {e}"))?;
1004            Ok(VerifiedSourceCredential {
1005                claims,
1006                profile,
1007                key_material: VerifiedKeyMaterial::Classical,
1008            })
1009        }
1010        other => anyhow::bail!("unsupported source credential alg '{other}'"),
1011    }
1012}
1013
1014/// Parse a canonical `ability@resource` capability token into the reviewed
1015/// typed [`hyprstream_rpc::auth::ucan::Capability`]. `None` for a malformed
1016/// token (empty ability/resource, or no `@`).
1017fn parse_capability(token: &str) -> Option<hyprstream_rpc::auth::ucan::Capability> {
1018    use hyprstream_rpc::auth::ucan::{Ability, Capability, Resource};
1019    let (ability, resource) = token.split_once('@')?;
1020    if ability.is_empty() || resource.is_empty() {
1021        return None;
1022    }
1023    Some(Capability::new(
1024        Resource::new(resource),
1025        Ability::new(ability),
1026    ))
1027}
1028
1029/// Attenuate an OAuth scope axis for a delegated hop. v16 §8.1 requires an
1030/// EXPLICIT attenuation at every hop: a scope-bearing source never silently
1031/// inherits its full scope into the derived credential. Equality is allowed
1032/// only when the full subset is explicitly requested. A source with no scope
1033/// cannot grant any — a non-empty request against it denies.
1034fn attenuate_delegated_scope(
1035    source_scope: Option<&str>,
1036    requested: Option<&str>,
1037) -> std::result::Result<Option<String>, String> {
1038    let source_set: std::collections::BTreeSet<&str> =
1039        source_scope.unwrap_or("").split_whitespace().collect();
1040    let requested_scopes: Vec<&str> = requested.unwrap_or("").split_whitespace().collect();
1041    if source_set.is_empty() {
1042        if !requested_scopes.is_empty() {
1043            return Err(
1044                "source credential carries no scope; requested scope cannot be granted".to_owned(),
1045            );
1046        }
1047        return Ok(None);
1048    }
1049    if requested_scopes.is_empty() {
1050        return Err(
1051            "scope-bearing source requires an explicit requested scope subset (no silent inheritance)"
1052                .to_owned(),
1053        );
1054    }
1055    for scope in &requested_scopes {
1056        if !source_set.contains(scope) {
1057            return Err(format!(
1058                "requested scope '{scope}' is not held by the source credential (broadening denied)"
1059            ));
1060        }
1061    }
1062    Ok(Some(requested_scopes.join(" ")))
1063}
1064
1065/// Attenuate the MAC/UCAN capability axis for a delegated hop using the reviewed
1066/// [`hyprstream_rpc::auth::ucan::set_attenuates`] relation — never a second,
1067/// ad-hoc capability algebra. v16 §8.1 requires explicit attenuation: a
1068/// cap-bearing source never silently inherits its full `cap`; a source with no
1069/// `cap` cannot grant any (a non-empty request denies, output stays `None`).
1070/// Malformed tokens and any capability the source does not `cover` are rejected.
1071fn attenuate_delegated_capabilities(
1072    source_cap: Option<&str>,
1073    requested: Option<&str>,
1074) -> std::result::Result<Option<String>, String> {
1075    let parse_set =
1076        |s: &str| -> std::result::Result<Vec<hyprstream_rpc::auth::ucan::Capability>, String> {
1077            s.split_whitespace()
1078                .map(|tok| {
1079                    parse_capability(tok).ok_or_else(|| {
1080                        format!("malformed capability '{tok}' (expected ability@resource)")
1081                    })
1082                })
1083                .collect()
1084        };
1085    let held = parse_set(source_cap.unwrap_or(""))?;
1086    let requested_str = requested.unwrap_or("").trim();
1087    if held.is_empty() {
1088        if !requested_str.is_empty() {
1089            return Err(
1090                "source credential carries no capability; requested capability cannot be granted"
1091                    .to_owned(),
1092            );
1093        }
1094        return Ok(None);
1095    }
1096    if requested_str.is_empty() {
1097        return Err(
1098            "capability-bearing source requires an explicit requested capability subset (no silent inheritance)"
1099                .to_owned(),
1100        );
1101    }
1102    let claimed = parse_set(requested_str)?;
1103    if !hyprstream_rpc::auth::ucan::set_attenuates(&held, &claimed) {
1104        return Err(
1105            "requested capability broadens the source authority (not covered by the source cap)"
1106                .to_owned(),
1107        );
1108    }
1109    // Stamp the requested canonical `ability@resource` form.
1110    Ok(Some(
1111        claimed
1112            .iter()
1113            .map(ToString::to_string)
1114            .collect::<Vec<_>>()
1115            .join(" "),
1116    ))
1117}
1118
1119/// The authenticated delegation edge presented to a [`DelegationEdgeAuthorizer`].
1120/// Every field is AUTHORITY-DERIVED, never caller-asserted: the actor is the
1121/// verified RPC envelope subject/tenant, the source audience is the verified
1122/// source credential's `aud`, and the target is the validated requested
1123/// audience. It carries no clearance, scope, or key — only the identity edge.
1124pub struct DelegationEdge<'a> {
1125    /// Bare terminal-actor service name (e.g. `"mcp"`), from the verified envelope.
1126    pub actor_service: &'a str,
1127    /// The terminal actor's verified tenant/Casbin domain.
1128    pub actor_tenant: &'a str,
1129    /// The verified source credential's `aud` — the resource the source was
1130    /// minted FOR. The authorizer proves this names the CURRENT terminal actor
1131    /// (the confused-deputy control): a source credential minted for service A
1132    /// cannot be rebound to service B, even with B's valid enrollment/scope.
1133    pub source_audience: Option<&'a str>,
1134    /// The verified originator subject (the source credential's `sub`).
1135    pub originator: &'a str,
1136    /// The requested derived-call target audience (validated non-empty).
1137    pub target_audience: &'a str,
1138    /// The generated target method id, when the typed dispatch call carries one
1139    /// (WS-E populates it from the reviewed inventory). `None` until then.
1140    pub target_method_id: Option<&'a str>,
1141}
1142
1143/// Fail-closed authority deciding whether a derived `AsOriginator` delegation
1144/// edge is a declared/allowed call edge (v16 §8.1). WS-E installs the generated,
1145/// reviewed `DispatchCallManifest` implementation before E-ready / F activation;
1146/// **an uninstalled authorizer DENIES every edge** — the exchange cannot mint.
1147///
1148/// It proves BOTH that the source credential was valid for the current terminal
1149/// actor (source audience ↔ actor binding — NOT the outbound
1150/// `allowed_audiences` ceiling, which is a distinct control) AND that the
1151/// requested target is a declared edge. It is never a caller boolean and never
1152/// defaults to allow: a generic `manage`-scoped service credential is not, by
1153/// itself, the confused-deputy control.
1154pub trait DelegationEdgeAuthorizer: Send + Sync {
1155    /// `true` iff this exact edge is an authorized derived call.
1156    fn authorize(&self, edge: &DelegationEdge<'_>) -> bool;
1157}
1158
1159/// A principal's ACTIVE primary signer-suite record (frozen A §5): the EXPLICIT
1160/// suite ID owned by the authoritative record plus its ordered raw component
1161/// public keys, in suite-plan order. B recomputes the confirmation thumbprint
1162/// over exactly `[suite_id, ordered_component_keys]` — it never infers the suite
1163/// ID from the key count, so a wrong-suite enrollment B would accept but C would
1164/// reject is caught here. Component 0 is the Ed25519 key (the `cnf.jwk` key).
1165pub struct PrimaryGroup {
1166    /// The record's explicit suite ID (validated against the frozen registry).
1167    pub suite_id: String,
1168    /// Ordered raw component public keys (Ed25519 = 32 bytes; ML-DSA-65 = 1952).
1169    pub ordered_component_keys: Vec<Vec<u8>>,
1170}
1171
1172/// Fail-closed resolver of a principal's AUTHORITATIVE, off-wire PRIMARY signer
1173/// enrollment (frozen A §5/T1: principal/tenant/role/keys/epoch — never the wire
1174/// `cnf`). A **user/classical** source credential's `cnf`/`hs_signer_suite` is
1175/// confirmed against THIS resolver, never self-derived from the same wire key it
1176/// claims to bind. **Uninstalled ⇒ every user primary denies** (WS-C installs
1177/// the real resolver over its enrollment store). Service primaries resolve
1178/// against the enrollment manifest instead, so this seam governs only the
1179/// user/classical case.
1180pub trait PrimaryEnrollmentResolver: Send + Sync {
1181    /// The ACTIVE primary signer group of `principal` in `tenant`, or `None`
1182    /// when unknown, inactive, or tenant-mismatched (all deny).
1183    fn primary_group(&self, principal: &str, tenant: &str) -> Option<PrimaryGroup>;
1184}
1185
1186/// Resolve the authoritative v16 `cnf.hs_signer_suite` thumbprint (base64url,
1187/// unpadded) for an enrolled SERVICE from the enrollment manifest, binding it to
1188/// the verified envelope signer key. The suite is chosen by the exact enrolled
1189/// key material — classical (Ed25519 only) or hybrid (Ed25519 + ML-DSA-65) — and
1190/// never fabricated. Fail closed on an absent manifest/enrollment, a signer key
1191/// that does not equal the enrolled Ed25519 key, or a malformed PQ half.
1192fn enrolled_service_signer_suite(
1193    manifest: Option<&crate::auth::service_enrollment::ServiceEnrollmentManifest>,
1194    service_name: &str,
1195    verified_ed_key: &[u8; 32],
1196) -> Result<String> {
1197    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
1198    let manifest =
1199        manifest.ok_or_else(|| anyhow!("service-enrollment manifest is not installed"))?;
1200    let entry = manifest
1201        .services
1202        .get(service_name)
1203        .ok_or_else(|| anyhow!("service '{service_name}' has no enrollment entry"))?;
1204    let enrolled_ed: [u8; 32] = URL_SAFE_NO_PAD
1205        .decode(&entry.ed25519_pubkey)
1206        .ok()
1207        .and_then(|b| <[u8; 32]>::try_from(b).ok())
1208        .ok_or_else(|| anyhow!("service '{service_name}' has a malformed enrolled ed25519 key"))?;
1209    anyhow::ensure!(
1210        &enrolled_ed == verified_ed_key,
1211        "verified signer key does not match the enrolled ed25519 key for '{service_name}'"
1212    );
1213    let pq = match &entry.ml_dsa_pubkey {
1214        Some(pq_b64) => Some(
1215            URL_SAFE_NO_PAD
1216                .decode(pq_b64)
1217                .ok()
1218                .filter(|b| b.len() == 1952)
1219                .ok_or_else(|| anyhow!("service '{service_name}' has a malformed ml_dsa key"))?,
1220        ),
1221        None => None,
1222    };
1223    Ok(hyprstream_rpc::auth::service_signer_suite_b64(
1224        &enrolled_ed,
1225        pq.as_deref(),
1226    ))
1227}
1228
1229/// Outcome of the workload-session narrowing decision on a service-credential
1230/// renewal (v16 §3.3). Extracted from the renewal handler so the check-BEFORE-
1231/// narrowing invariant is unit-testable WITHOUT provisioning the signing /
1232/// disk-persistence boundary: the decision is a pure function of the session
1233/// registry state and the authoritative family policy.
1234#[derive(Debug)]
1235enum RenewalWorkloadSession {
1236    /// Deny the renewal with this error code + message (fail-closed: a revoked,
1237    /// expired, or unresolvable session never renews).
1238    Deny { code: &'static str, message: String },
1239    /// The `workload_session_id` to stamp into the renewed credential, or `None`
1240    /// to OMIT it — either a deliberate family narrowing (the policy was removed
1241    /// from a live family) or a standalone service that carries no session.
1242    Stamp(Option<String>),
1243}
1244
1245/// A v16 dispatch credential MUST carry a `cnf.hs_signer_suite` that equals the
1246/// AUTHORITATIVE signer suite of its PRIMARY signer group — signature
1247/// verification alone never checks the confirmation claim (frozen WS-A §5/T1),
1248/// and the suite is NEVER self-derived from the same wire `cnf.jwk` it claims to
1249/// bind.
1250///
1251/// **Primary selection (multi-hop §8.1):** for a source that carries an `act`
1252/// chain, `sub` stays the originator but the `cnf` belongs to the OUTERMOST
1253/// (current) terminal actor — so the primary principal is `act.sub` when an
1254/// `act` is present, else `sub`. A correct first-hop delegated token is thus a
1255/// valid second-hop source (its `cnf` resolves to its terminal actor).
1256///
1257/// **Resolution:** a SERVICE primary resolves against the enrollment manifest
1258/// (key-bound); a USER/classical primary resolves against the fail-closed
1259/// authoritative [`PrimaryEnrollmentResolver`] (never the wire key) — an
1260/// uninstalled resolver or an unknown/mismatched primary denies. The presented
1261/// `cnf.jwk` key MUST equal the resolved primary's Ed25519 component, and the
1262/// `hs_signer_suite` MUST equal the suite over the resolved ordered keys.
1263fn validate_credential_hs_suite(
1264    manifest: Option<&crate::auth::service_enrollment::ServiceEnrollmentManifest>,
1265    primary_resolver: Option<&dyn PrimaryEnrollmentResolver>,
1266    claims: &hyprstream_rpc::auth::Claims,
1267) -> Result<()> {
1268    let cnf = claims
1269        .cnf
1270        .as_ref()
1271        .ok_or_else(|| anyhow!("credential has no cnf confirmation"))?;
1272    let present = cnf
1273        .hs_signer_suite
1274        .as_deref()
1275        .map(str::trim)
1276        .filter(|s| !s.is_empty())
1277        .ok_or_else(|| anyhow!("credential cnf lacks hs_signer_suite (not a v16 credential)"))?;
1278    let cnf_ed = claims
1279        .cnf_key_bytes()
1280        .ok_or_else(|| anyhow!("credential cnf lacks a well-formed ed25519 primary key"))?;
1281
1282    // §8.1: the primary is the OUTERMOST/current terminal actor when delegated.
1283    let primary_principal = claims
1284        .act
1285        .as_ref()
1286        .map_or(claims.sub.as_str(), |a| a.sub.as_str());
1287
1288    let expected = if let Some(svc) = primary_principal.strip_prefix("service:") {
1289        // Service primary: the enrollment manifest is authoritative; the helper
1290        // key-binds the presented Ed key to the enrolled Ed key and computes the
1291        // suite over the enrolled ordered keys.
1292        enrolled_service_signer_suite(manifest, svc, &cnf_ed)?
1293    } else {
1294        // User/classical primary: the AUTHORITATIVE off-wire resolver is the
1295        // only source of truth — never the wire `cnf.jwk`.
1296        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
1297        let resolver = primary_resolver.ok_or_else(|| {
1298            anyhow!("primary-enrollment resolver is not installed; user primary denied")
1299        })?;
1300        let tenant = claims.tenant.as_deref().unwrap_or_default();
1301        let group = resolver
1302            .primary_group(primary_principal, tenant)
1303            .ok_or_else(|| anyhow!("no active primary enrollment for the credential principal"))?;
1304        // Validate the record's EXPLICIT suite ID + component shape against the
1305        // frozen registry — never infer the suite from the key count, so a
1306        // wrong-suite enrollment cannot be blessed here and rejected by C.
1307        let keys = &group.ordered_component_keys;
1308        let shape_ok = if group.suite_id == hyprstream_rpc::auth::SUITE_CLASSICAL_ED25519 {
1309            keys.len() == 1 && keys[0].len() == 32
1310        } else if group.suite_id == hyprstream_rpc::auth::SUITE_HYBRID_ED25519_MLDSA65 {
1311            keys.len() == 2 && keys[0].len() == 32 && keys[1].len() == 1952
1312        } else {
1313            false
1314        };
1315        anyhow::ensure!(
1316            shape_ok,
1317            "primary enrollment suite id/shape is not a frozen-registry signer suite"
1318        );
1319        // The presented `cnf.jwk` MUST equal the enrolled Ed25519 component 0.
1320        anyhow::ensure!(
1321            keys[0].as_slice() == cnf_ed,
1322            "credential cnf.jwk does not equal the enrolled primary Ed25519 key"
1323        );
1324        // Recompute the thumbprint over the EXACT record value.
1325        let refs: Vec<&[u8]> = keys.iter().map(Vec::as_slice).collect();
1326        URL_SAFE_NO_PAD.encode(hyprstream_rpc::auth::signer_suite_thumbprint(
1327            &group.suite_id,
1328            &refs,
1329        ))
1330    };
1331    anyhow::ensure!(
1332        present == expected,
1333        "credential cnf.hs_signer_suite does not equal its authoritative primary signer suite"
1334    );
1335    Ok(())
1336}
1337
1338#[cfg(feature = "postgres")]
1339fn federate_verified_source(
1340    data: &hyprstream_rpc_std::policy_client::FederateVerifiedSource,
1341) -> Result<hyprstream_session_store::Source> {
1342    anyhow::ensure!(
1343        !data.issuer.is_empty()
1344            && data.issuer.len() <= 2048
1345            && !data.subject.is_empty()
1346            && data.subject.len() <= 256
1347            && !data.atproto_did.is_empty()
1348            && data.atproto_did.len() <= 255
1349            && !data.jti.is_empty()
1350            && data.jti.len() <= 256
1351            && !data.nonce.is_empty()
1352            && data.nonce.len() <= 256,
1353        "invalid Federate source metadata"
1354    );
1355    Ok(hyprstream_session_store::Source {
1356        issuer: data.issuer.clone(),
1357        subject: data.subject.clone(),
1358        atproto_did: data.atproto_did.clone(),
1359        jti: data.jti.clone(),
1360        nonce: data.nonce.clone(),
1361        token_hash: data.token_hash.as_slice().try_into()?,
1362        issued_at: data.issued_at,
1363        expires_at: data.expires_at,
1364    })
1365}
1366
1367#[async_trait::async_trait(?Send)]
1368impl PolicyHandler for PolicyService {
1369    async fn handle_prepare_federate_session(
1370        &self,
1371        ctx: &EnvelopeContext,
1372        _request_id: u64,
1373        data: &hyprstream_rpc_std::policy_client::PrepareFederateSession,
1374    ) -> Result<PolicyResponseVariant> {
1375        #[cfg(feature = "postgres")]
1376        if let Some(reader) = &self.federate_admission {
1377            let result = async {
1378                anyhow::ensure!(
1379                    !data.client.is_empty() && data.client.len() <= 256,
1380                    "invalid Federate client selector"
1381                );
1382                let prepared = reader
1383                    .prepare_rpc(
1384                        ctx,
1385                        &data.client,
1386                        federate_verified_source(&data.source)?,
1387                        data.source.device_flow,
1388                        data.requested.clone(),
1389                        data.challenge_id.as_slice().try_into()?,
1390                        data.challenge_created_at,
1391                        data.ed_public.as_slice().try_into()?,
1392                        data.pq_public.clone(),
1393                    )
1394                    .await?;
1395                Ok::<_, anyhow::Error>(prepared)
1396            }
1397            .await;
1398            if let Ok(prepared) = result {
1399                return Ok(PolicyResponseVariant::PrepareFederateSessionResult(
1400                    hyprstream_rpc_std::policy_client::PreparedFederateSession {
1401                        account_id: prepared.account_id,
1402                        subject: prepared.subject,
1403                        tenant: prepared.tenant,
1404                        requested: prepared.requested,
1405                        granted: prepared.granted,
1406                        revision: prepared.revision,
1407                        policy_handle: prepared.handle.to_vec(),
1408                    },
1409                ));
1410            }
1411        }
1412        let _ = (ctx, data);
1413        Ok(PolicyResponseVariant::Error(ErrorInfo {
1414            code: "FEDERATE_PREPARE_DENIED".into(),
1415            message: "Federate prepare unavailable or denied".into(),
1416            details: String::new(),
1417        }))
1418    }
1419
1420    async fn handle_commit_federate_session(
1421        &self,
1422        ctx: &EnvelopeContext,
1423        _request_id: u64,
1424        data: &hyprstream_rpc_std::policy_client::CommitFederateSession,
1425    ) -> Result<PolicyResponseVariant> {
1426        #[cfg(feature = "postgres")]
1427        if let Some(reader) = &self.federate_admission {
1428            let result = async {
1429                anyhow::ensure!(
1430                    !data.client.is_empty() && data.client.len() <= 256,
1431                    "invalid Federate client selector"
1432                );
1433                reader
1434                    .commit_rpc(
1435                        ctx,
1436                        data.policy_handle.as_slice().try_into()?,
1437                        &data.client,
1438                        federate_verified_source(&data.source)?,
1439                        data.source.device_flow,
1440                        data.challenge_id.as_slice().try_into()?,
1441                        data.challenge_created_at,
1442                        data.challenge_expires_at,
1443                        data.ed_public.as_slice().try_into()?,
1444                        data.pq_public.clone(),
1445                    )
1446                    .await
1447            }
1448            .await;
1449            if let Err(error) = &result {
1450                // Keep the RPC response generic. The Policy-only,
1451                // redacted error journal retains the internal failure.
1452                tracing::error!(error = %error, "Federate session commit failed");
1453            }
1454            if let Ok(session) = result {
1455                return Ok(PolicyResponseVariant::CommitFederateSessionResult(
1456                    hyprstream_rpc_std::policy_client::FederateCommittedSession {
1457                        host: session.host,
1458                        sid: session.sid,
1459                        account_id: session.account_id,
1460                        subject: session.subject,
1461                        tenant: session.tenant,
1462                        client: session.client_id,
1463                        resource: session.resource,
1464                        scopes: session.scopes,
1465                        grant_revision: session.grant_revision,
1466                        ed_public: session.ed_public.to_vec(),
1467                        pq_public: session.pq_public,
1468                        generation: session.generation.to_vec(),
1469                        collision_inventory_id: session.collision_inventory_id.to_vec(),
1470                        proof_epoch: session.proof_epoch,
1471                        expires_at: session.expires_at,
1472                    },
1473                ));
1474            }
1475        }
1476        let _ = (ctx, data);
1477        Ok(PolicyResponseVariant::Error(ErrorInfo {
1478            code: "FEDERATE_COMMIT_DENIED".into(),
1479            message: "Federate commit unavailable or denied".into(),
1480            details: String::new(),
1481        }))
1482    }
1483
1484    async fn handle_admit_federate_request(
1485        &self,
1486        ctx: &EnvelopeContext,
1487        _request_id: u64,
1488        data: &hyprstream_rpc_std::policy_client::AdmitFederateRequest,
1489    ) -> Result<PolicyResponseVariant> {
1490        #[cfg(feature = "postgres")]
1491        if let Some(reader) = &self.federate_request_use {
1492            if reader.admit(ctx, data).await.is_ok() {
1493                return Ok(PolicyResponseVariant::AdmitFederateRequestResult(true));
1494            }
1495        }
1496        let _ = (ctx, data);
1497        Ok(PolicyResponseVariant::AdmitFederateRequestResult(false))
1498    }
1499
1500    async fn handle_resolve_session_primary(
1501        &self,
1502        ctx: &EnvelopeContext,
1503        _request_id: u64,
1504        data: &hyprstream_rpc_std::policy_client::ResolveSessionPrimary,
1505    ) -> Result<PolicyResponseVariant> {
1506        let _ = (ctx, data);
1507        Ok(PolicyResponseVariant::Error(ErrorInfo {
1508            code: "SESSION_PRIMARY_DENIED".into(),
1509            message: "session primary unavailable or denied".into(),
1510            details: String::new(),
1511        }))
1512    }
1513
1514    async fn authorize(
1515        &self,
1516        ctx: &EnvelopeContext,
1517        resource: &str,
1518        operation: &str,
1519    ) -> Result<()> {
1520        let subject = ctx.subject();
1521        let domain = self.request_domain(ctx)?;
1522        let allowed = self
1523            .policy_manager
1524            .check_with_domain(&subject.to_string(), &domain, resource, operation)
1525            .await;
1526        if allowed {
1527            Ok(())
1528        } else {
1529            anyhow::bail!(
1530                "Unauthorized: {} cannot {} on {}",
1531                subject,
1532                operation,
1533                resource
1534            )
1535        }
1536    }
1537
1538    async fn handle_check_batch(
1539        &self,
1540        ctx: &EnvelopeContext,
1541        request_id: u64,
1542        data: &PolicyCheckBatch,
1543    ) -> Result<PolicyResponseVariant> {
1544        anyhow::ensure!(data.checks.len() <= 256, "policy check batch exceeds 256");
1545        let mut allowed = Vec::with_capacity(data.checks.len());
1546        for check in &data.checks {
1547            // Reuse the exact single-check subject/tenant/audit boundary.
1548            let result = self.handle_check(ctx, request_id, check).await?;
1549            allowed.push(matches!(result, PolicyResponseVariant::CheckResult(true)));
1550        }
1551        Ok(PolicyResponseVariant::CheckBatchResult(
1552            PolicyCheckBatchResult { allowed },
1553        ))
1554    }
1555
1556    async fn handle_check_mediated(
1557        &self,
1558        ctx: &EnvelopeContext,
1559        _request_id: u64,
1560        data: &MediatedPolicyCheck,
1561    ) -> Result<PolicyResponseVariant> {
1562        let mediator = ctx.subject();
1563        anyhow::ensure!(
1564            ctx.claims().is_some() && !mediator.is_federated(),
1565            "authenticated local mediator required"
1566        );
1567        let service = mediator
1568            .name()
1569            .and_then(|name| name.strip_prefix("service:"))
1570            .ok_or_else(|| anyhow!("service mediator required"))?;
1571        anyhow::ensure!(
1572            self.accept_delegated_bearer(&ctx.cnf),
1573            "mediator is not admitted for policy queries"
1574        );
1575        // The original request is not a local transport call to Policy. Use
1576        // the network provenance constructor, then the normal credential
1577        // verifier; never grant the empty-issuer/local system shortcuts.
1578        let mut holder =
1579            EnvelopeContext::from_mediated_evidence(&data.evidence, service, &data.operation)?;
1580        self.verify_claims(&mut holder).await?;
1581        let holder_subject = holder.subject();
1582        anyhow::ensure!(
1583            holder.claims().is_some()
1584                && !holder_subject.is_federated()
1585                && holder_subject
1586                    .name()
1587                    .is_some_and(|name| name.starts_with("service:")),
1588            "mediated evidence must identify a verified service holder"
1589        );
1590        holder.admit_mediated_query(service, &data.resource, &data.operation)?;
1591        let domain = self.request_domain(&holder)?;
1592        let allowed = self
1593            .policy_manager
1594            .check_with_domain(
1595                &holder_subject.to_string(),
1596                &domain,
1597                &data.resource,
1598                &data.operation,
1599            )
1600            .await;
1601        holder.audit_authz(&data.resource, &data.operation, allowed);
1602        Ok(PolicyResponseVariant::CheckMediatedResult(allowed))
1603    }
1604
1605    async fn handle_check(
1606        &self,
1607        ctx: &EnvelopeContext,
1608        _request_id: u64,
1609        data: &PolicyCheck,
1610    ) -> Result<PolicyResponseVariant> {
1611        let subject = ctx.subject();
1612        if !ctx.is_authenticated() {
1613            warn!(
1614                requested_subject = %data.subject,
1615                requested_domain = %data.domain,
1616                resource = %data.resource,
1617                operation = %data.operation,
1618                "policy check denied: unauthenticated envelope context"
1619            );
1620            ctx.audit_authz(&data.resource, &data.operation, false);
1621            return Ok(PolicyResponseVariant::CheckResult(false));
1622        }
1623        let domain = match self.request_domain(ctx) {
1624            Ok(domain) => domain,
1625            Err(error) => {
1626                warn!(
1627                    caller = %subject,
1628                    requested_subject = %data.subject,
1629                    requested_domain = %data.domain,
1630                    resource = %data.resource,
1631                    operation = %data.operation,
1632                    %error,
1633                    "policy check denied: no verified authorization domain"
1634                );
1635                ctx.audit_authz(&data.resource, &data.operation, false);
1636                return Ok(PolicyResponseVariant::CheckResult(false));
1637            }
1638        };
1639
1640        trace!(
1641            "Policy check: verified_subject={}, verified_domain={}, resource={}, operation={}",
1642            subject,
1643            domain,
1644            data.resource,
1645            data.operation
1646        );
1647
1648        // An HTTP resource token relayed by an enrolled service remains bound
1649        // to its signed scope. Casbin alone must not expand a read-only grant
1650        // into inference (or into a different model); native-issuer calls keep
1651        // their existing policy path.
1652        if ctx.has_delegated_resource_audience()
1653            && !ctx.claims().is_some_and(|claims| {
1654                delegated_resource_scope_allows(claims, &data.resource, &data.operation)
1655            })
1656        {
1657            ctx.audit_authz(&data.resource, &data.operation, false);
1658            return Ok(PolicyResponseVariant::CheckResult(false));
1659        }
1660
1661        // Subject and domain are derived exclusively from the verified envelope.
1662        // The request fields remain on the wire for compatibility, but cannot
1663        // select another identity or tenant. Pass the operation string directly
1664        // so dot-namespaced actions are forwarded verbatim to Casbin.
1665        let allowed = self
1666            .policy_manager
1667            .check_with_domain(
1668                &subject.to_string(),
1669                &domain,
1670                &data.resource,
1671                &data.operation,
1672            )
1673            .await;
1674
1675        if allowed {
1676            debug!(caller = %subject, %domain, "policy check allowed");
1677        } else {
1678            warn!(
1679                caller = %subject,
1680                %domain,
1681                resource = %data.resource,
1682                operation = %data.operation,
1683                "policy check denied by policy"
1684            );
1685        }
1686        ctx.audit_authz(&data.resource, &data.operation, allowed);
1687        Ok(PolicyResponseVariant::CheckResult(allowed))
1688    }
1689
1690    async fn handle_issue_token(
1691        &self,
1692        ctx: &EnvelopeContext,
1693        _request_id: u64,
1694        data: &IssueToken,
1695    ) -> Result<PolicyResponseVariant> {
1696        trace!("Issuing JWT token");
1697
1698        // Determine subject: explicit subject (if provided and authorized) or envelope identity.
1699        // JWT sub must contain a bare username (e.g. "randy", "birdetta") — the identity
1700        // system adds the namespace prefix ("token:randy") when the JWT is decoded.
1701        // For service tokens: sub = "service:{name}", e.g. "service:model".
1702        let caller_domain = self.request_domain(ctx)?;
1703        let requested_tenant = data
1704            .tenant
1705            .as_ref()
1706            .filter(|tenant| !tenant.is_empty())
1707            .cloned();
1708        if requested_tenant.as_deref() == Some("*") {
1709            return Ok(PolicyResponseVariant::Error(ErrorInfo {
1710                message: "Wildcard is not a valid token tenant".to_owned(),
1711                code: "INVALID_TENANT".to_owned(),
1712                details: String::new(),
1713            }));
1714        }
1715        let target_domain = requested_tenant.unwrap_or_else(|| caller_domain.clone());
1716
1717        let requested_subject = data.subject.as_ref().filter(|subject| !subject.is_empty());
1718        if requested_subject.is_some() || target_domain != caller_domain {
1719            // Explicit-subject and cross-tenant issuance are authorized in the
1720            // TARGET tenant. This permits deliberate delegation only when the
1721            // caller has policy:IssueToken/manage there.
1722            let caller = ctx.subject().to_string();
1723            let allowed = self
1724                .policy_manager
1725                .check_with_domain(&caller, &target_domain, "policy:IssueToken", "manage")
1726                .await;
1727            if !allowed {
1728                let target_subject =
1729                    requested_subject.map_or_else(|| ctx.user().to_owned(), Clone::clone);
1730                return Ok(PolicyResponseVariant::Error(ErrorInfo {
1731                    message: format!(
1732                        "Subject '{}' is not authorized to issue tokens on behalf of '{}' in tenant '{}'",
1733                        caller, target_subject, target_domain
1734                    ),
1735                    code: "UNAUTHORIZED_SUBJECT".to_owned(),
1736                    details: "Requires 'manage' permission on 'policy:IssueToken' in the target tenant".to_owned(),
1737                }));
1738            }
1739        }
1740        let subject = if let Some(subj) = requested_subject {
1741            subj.clone()
1742        } else {
1743            // Use bare username from the envelope identity.
1744            ctx.user().to_owned()
1745        };
1746        let is_service_token = subject.starts_with("service:");
1747
1748        // `IssueToken` is the shared signing boundary. Its zero/default wire
1749        // value is deliberately `InteractiveSession`, so a caller that omits
1750        // the profile cannot silently mint an unsessioned user credential.
1751        // The only sid-less user profiles are the separately typed RFC 8693
1752        // and RFC 7523 exchanges; service credentials have their own profile
1753        // and are never allowed to carry an interactive sid.
1754        match data.issuance_profile {
1755            IssueTokenProfile::InteractiveSession => {
1756                if is_service_token {
1757                    return Ok(PolicyResponseVariant::Error(ErrorInfo {
1758                        message: "service credentials must use the service issuance profile"
1759                            .to_owned(),
1760                        code: "INVALID_ISSUANCE_PROFILE".to_owned(),
1761                        details: String::new(),
1762                    }));
1763                }
1764                if data.session_id.as_deref().is_none_or(str::is_empty) {
1765                    return Ok(PolicyResponseVariant::Error(ErrorInfo {
1766                        message: "interactive user/OIDC issuance requires a session id".to_owned(),
1767                        code: "MISSING_SESSION".to_owned(),
1768                        details: String::new(),
1769                    }));
1770                }
1771            }
1772            IssueTokenProfile::Rfc8693 | IssueTokenProfile::Rfc7523 => {
1773                if is_service_token {
1774                    return Ok(PolicyResponseVariant::Error(ErrorInfo {
1775                        message: "service credentials must use the service issuance profile"
1776                            .to_owned(),
1777                        code: "INVALID_ISSUANCE_PROFILE".to_owned(),
1778                        details: String::new(),
1779                    }));
1780                }
1781                if data.session_id.is_some() {
1782                    return Ok(PolicyResponseVariant::Error(ErrorInfo {
1783                        message: "non-interactive RFC issuance cannot carry an OIDC session id"
1784                            .to_owned(),
1785                        code: "INVALID_SESSION".to_owned(),
1786                        details: String::new(),
1787                    }));
1788                }
1789            }
1790            IssueTokenProfile::Service => {
1791                if !is_service_token || data.session_id.is_some() {
1792                    return Ok(PolicyResponseVariant::Error(ErrorInfo {
1793                        message:
1794                            "service issuance requires a service subject and no OIDC session id"
1795                                .to_owned(),
1796                        code: "INVALID_ISSUANCE_PROFILE".to_owned(),
1797                        details: String::new(),
1798                    }));
1799                }
1800            }
1801        }
1802
1803        // RFC 9068 §2.2.1 `client_id` (v16 credential profile): the user
1804        // `at+jwt` profiles (interactive / RFC 8693 / RFC 7523) MUST carry a
1805        // non-empty `client_id`; the service profile mints a `wit+jwt` and MUST
1806        // NOT carry one. Stamped into the signed claims below so the emitted
1807        // credential is profile-compliant by construction.
1808        let client_id = data
1809            .client_id
1810            .as_deref()
1811            .map(str::trim)
1812            .filter(|s| !s.is_empty());
1813        match data.issuance_profile {
1814            IssueTokenProfile::InteractiveSession
1815            | IssueTokenProfile::Rfc8693
1816            | IssueTokenProfile::Rfc7523 => {
1817                if client_id.is_none() {
1818                    return Ok(PolicyResponseVariant::Error(ErrorInfo {
1819                        message: "at+jwt issuance requires a non-empty client_id (RFC 9068 §2.2.1)"
1820                            .to_owned(),
1821                        code: "MISSING_CLIENT_ID".to_owned(),
1822                        details: String::new(),
1823                    }));
1824                }
1825            }
1826            IssueTokenProfile::Service => {
1827                if client_id.is_some() {
1828                    return Ok(PolicyResponseVariant::Error(ErrorInfo {
1829                        message: "service (wit+jwt) issuance cannot carry a client_id".to_owned(),
1830                        code: "INVALID_CLIENT_ID".to_owned(),
1831                        details: String::new(),
1832                    }));
1833                }
1834            }
1835        }
1836
1837        // Interactive and RFC 8693 user tokens resolve only their
1838        // authority-owned, exact-subject compiled-policy enrollment. A
1839        // resource-bound child token must not lose the enrolled label; neither
1840        // the OAuth caller nor its source token supplies this label. Missing
1841        // enrollment stays unlabeled unless clearance is required.
1842        let mut subject_clearance = enrolled_user_clearance_for_issue(
1843            data.issuance_profile,
1844            data.require_clearance,
1845            &subject,
1846            self.token_clearance_resolver.as_ref(),
1847        );
1848        if data.require_clearance && subject_clearance.is_none() {
1849            return Ok(PolicyResponseVariant::Error(ErrorInfo {
1850                message: format!("Subject '{subject}' has no verified enrollment clearance"),
1851                code: "UNLABELED_SUBJECT".to_owned(),
1852                details: "MAC-enforcing token issuance fails closed for unenrolled subjects"
1853                    .to_owned(),
1854            }));
1855        }
1856
1857        // #1159 freeze: this is the shared signing boundary for every caller
1858        // using PolicyClient::issue_token, including RFC 8693 token exchange
1859        // and RFC 7523 JWT bearer. Check the resolved concrete subject, not
1860        // merely an optional request field, so an envelope-derived subject
1861        // cannot bypass the freeze either.
1862        if is_path_form_did_web(&subject) {
1863            return Ok(PolicyResponseVariant::Error(ErrorInfo {
1864                message: "path-form did:web account subjects are frozen; host-form account minting is not available yet (#1159)".to_owned(),
1865                code: "FROZEN_PATH_FORM_SUBJECT".to_owned(),
1866                details: String::new(),
1867            }));
1868        }
1869
1870        // Validate TTL — service tokens get a longer default (7 days)
1871        let default_ttl = if is_service_token {
1872            data.ttl.filter(|&t| t != 0).unwrap_or(604800) // 7 days for service tokens
1873        } else {
1874            data.ttl
1875                .filter(|&t| t != 0)
1876                .unwrap_or(self.token_config.default_ttl_seconds)
1877        };
1878        let requested_ttl = default_ttl;
1879
1880        const MIN_TTL_SECONDS: u32 = 60;
1881        if requested_ttl < MIN_TTL_SECONDS {
1882            return Ok(PolicyResponseVariant::Error(ErrorInfo {
1883                message: format!(
1884                    "TTL too short: {} < {} seconds minimum",
1885                    requested_ttl, MIN_TTL_SECONDS
1886                ),
1887                code: "TTL_TOO_SHORT".to_owned(),
1888                details: String::new(),
1889            }));
1890        }
1891
1892        if requested_ttl > self.token_config.max_ttl_seconds {
1893            return Ok(PolicyResponseVariant::Error(ErrorInfo {
1894                message: format!(
1895                    "TTL exceeds maximum: {} > {}",
1896                    requested_ttl, self.token_config.max_ttl_seconds
1897                ),
1898                code: "TTL_EXCEEDED".to_owned(),
1899                details: String::new(),
1900            }));
1901        }
1902
1903        // Create and sign JWT with audience (RFC 8707) and the OAuth grant's
1904        // scope ceiling. Casbin still supplies subject policy; verifiers must
1905        // intersect it with this signed per-grant authority (#1146 T2.1).
1906        let now = chrono::Utc::now().timestamp();
1907        let audience = data
1908            .audience
1909            .as_ref()
1910            .filter(|s| !s.is_empty())
1911            .cloned()
1912            .or_else(|| self.default_audience.clone());
1913
1914        // ServiceEnrollmentManifest (v16 §11): for service subjects the
1915        // manifest is the authoritative target-clearance and audience source.
1916        // Clearance is stamped from the manifest for every enrolled service
1917        // (issuance cannot gain, and renewal cannot preserve, authority the
1918        // manifest does not grant); a declared audience list is enforced
1919        // fail-closed.
1920        if let Some(service_name) = subject.strip_prefix("service:") {
1921            if let Some(manifest) = crate::auth::service_enrollment::global_service_enrollment() {
1922                let Some(clearance) = manifest.clearance_for_service(service_name) else {
1923                    return Ok(PolicyResponseVariant::Error(ErrorInfo {
1924                        message: format!("service '{service_name}' has no enrollment entry"),
1925                        code: "UNENROLLED_SERVICE".to_owned(),
1926                        details: String::new(),
1927                    }));
1928                };
1929                subject_clearance = Some(clearance);
1930                // A declared audience list requires the effective audience to
1931                // be present AND a member — an enrolled service cannot mint
1932                // without an exact allowed audience.
1933                if !manifest.allows_audience(service_name, audience.as_deref()) {
1934                    return Ok(PolicyResponseVariant::Error(ErrorInfo {
1935                        message: format!(
1936                            "audience '{}' is not enrolled for service '{service_name}'",
1937                            audience.as_deref().unwrap_or("<none>")
1938                        ),
1939                        code: "AUDIENCE_NOT_ENROLLED".to_owned(),
1940                        details: String::new(),
1941                    }));
1942                }
1943            }
1944        }
1945
1946        let granted_scope = data.requested_scopes.as_ref().map(|scopes| {
1947            scopes
1948                .iter()
1949                .map(String::as_str)
1950                .filter(|scope| !scope.is_empty())
1951                .collect::<Vec<_>>()
1952                .join(" ")
1953        });
1954
1955        // OAuth delegates for a service, so its envelope signer is OAuth's key,
1956        // not the service assertion signer. Bind `cnf` to the explicitly passed
1957        // assertion key. A registered service may attest a new sibling key.
1958        let service_key_bytes: Option<[u8; 32]> = if is_service_token {
1959            let svc_name = &subject["service:".len()..];
1960            let trust = hyprstream_service::global_trust_store();
1961            use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
1962            let invalid_assertion_key = |message: &str| {
1963                PolicyResponseVariant::Error(ErrorInfo {
1964                    message: message.to_owned(),
1965                    code: "INVALID_ASSERTION_KEY".to_owned(),
1966                    details: String::new(),
1967                })
1968            };
1969            let Some(encoded) = data.user_pub_key.as_deref() else {
1970                return Ok(invalid_assertion_key(
1971                    "service token issuance requires the assertion-verified Ed25519 public key",
1972                ));
1973            };
1974            let decoded = match URL_SAFE_NO_PAD.decode(encoded) {
1975                Ok(decoded) => decoded,
1976                Err(_) => {
1977                    return Ok(invalid_assertion_key(
1978                        "service token assertion key is not base64url",
1979                    ))
1980                }
1981            };
1982            let requested_bytes: [u8; 32] = match decoded.try_into() {
1983                Ok(bytes) => bytes,
1984                Err(_) => {
1985                    return Ok(invalid_assertion_key(
1986                        "service token assertion key must be 32 bytes",
1987                    ))
1988                }
1989            };
1990            let requested = match VerifyingKey::from_bytes(&requested_bytes) {
1991                Ok(requested) => requested,
1992                Err(_) => {
1993                    return Ok(invalid_assertion_key(
1994                        "service token assertion key is not a valid Ed25519 verifying key",
1995                    ))
1996                }
1997            };
1998            if trust.is_authorized(&requested, svc_name) {
1999                Some(requested_bytes)
2000            } else {
2001                let caller =
2002                    match VerifyingKey::from_bytes(&ctx.cnf) {
2003                        Ok(caller) => caller,
2004                        Err(_) => return Ok(PolicyResponseVariant::Error(ErrorInfo {
2005                            message:
2006                                "service key rotation caller has an invalid Ed25519 verifying key"
2007                                    .to_owned(),
2008                            code: "UNAUTHORIZED_SERVICE_KEY".to_owned(),
2009                            details: String::new(),
2010                        })),
2011                    };
2012                let expected_subject = format!("service:{svc_name}");
2013                if ctx.subject().name() != Some(expected_subject.as_str())
2014                    || !trust.is_authorized(&caller, svc_name)
2015                {
2016                    return Ok(PolicyResponseVariant::Error(ErrorInfo {
2017                        message: format!(
2018                            "unregistered service key for '{svc_name}' may only be attested by a registered sibling"
2019                        ),
2020                        code: "UNAUTHORIZED_SERVICE_KEY".to_owned(),
2021                        details: String::new(),
2022                    }));
2023                }
2024                Some(requested_bytes)
2025            }
2026        } else {
2027            use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
2028            data.user_pub_key
2029                .as_deref()
2030                .and_then(|s| URL_SAFE_NO_PAD.decode(s).ok()?.try_into().ok())
2031        };
2032
2033        // OAuth may override the issuer for a profile-specific token (atproto
2034        // requires an origin). Other callers retain the configured default.
2035        let issuer = data
2036            .issuer
2037            .as_ref()
2038            .filter(|issuer| !issuer.is_empty())
2039            .cloned()
2040            .or_else(|| self.default_audience.clone())
2041            .unwrap_or_default();
2042        let mut claims =
2043            hyprstream_rpc::auth::Claims::new(subject.clone(), now, now + requested_ttl as i64)
2044                .with_issuer(issuer.clone())
2045                .with_audience(audience)
2046                .with_scope(granted_scope);
2047        if target_domain != "*" {
2048            claims = claims.with_tenant(target_domain.clone());
2049        }
2050        if let Some(clearance) = subject_clearance {
2051            claims = claims.with_clearance(clearance);
2052        }
2053        // RFC 9068 §2.2.1: stamp the OAuth `client_id` on the user `at+jwt`
2054        // credential (validated non-empty above for those profiles; the service
2055        // profile carries none).
2056        if let Some(cid) = client_id {
2057            claims = claims.with_client_id(cid);
2058        }
2059        // Session binding (v16 §3.3): the OIDC `sid` profile is enforced at
2060        // the authority boundary. Service credentials NEVER carry an
2061        // interactive session (workload IDs enter only through the enrolled
2062        // renewal family, not this field). A user session ID is stamped only
2063        // when the canonical registry holds an ACTIVE record bound to this
2064        // exact subject and tenant — unknown, revoked, expired, cross-subject,
2065        // or cross-tenant sessions are rejected (no session fixation).
2066        if let Some(sid) = data.session_id.as_deref().filter(|s| !s.is_empty()) {
2067            if sid.len() > 1024 {
2068                return Ok(PolicyResponseVariant::Error(ErrorInfo {
2069                    message: "session id exceeds 1024 bytes".to_owned(),
2070                    code: "INVALID_ARGUMENT".to_owned(),
2071                    details: String::new(),
2072                }));
2073            }
2074            if subject.starts_with("service:") {
2075                return Ok(PolicyResponseVariant::Error(ErrorInfo {
2076                    message: "service credentials cannot carry an OIDC session id".to_owned(),
2077                    code: "INVALID_ARGUMENT".to_owned(),
2078                    details: String::new(),
2079                }));
2080            }
2081            let Some(registry) = hyprstream_rpc::auth::global_session_registry() else {
2082                return Ok(PolicyResponseVariant::Error(ErrorInfo {
2083                    message: "session registry is not initialized".to_owned(),
2084                    code: "UNAVAILABLE".to_owned(),
2085                    details: String::new(),
2086                }));
2087            };
2088            let session_key = hyprstream_rpc::auth::SessionKey::oidc(&issuer, sid);
2089            let bindable = match registry.session_state(&session_key).await {
2090                Some(state) => {
2091                    state.status == hyprstream_rpc::auth::ActiveOrRevoked::Active
2092                        && state.expires_at > now
2093                        && state.subject == subject
2094                        && state.tenant == target_domain
2095                }
2096                None => false,
2097            };
2098            if !bindable {
2099                return Ok(PolicyResponseVariant::Error(ErrorInfo {
2100                    message: "session is unknown, inactive, expired, or bound to a different subject/tenant".to_owned(),
2101                    code: "INVALID_SESSION".to_owned(),
2102                    details: String::new(),
2103                }));
2104            }
2105            claims = claims.with_sid(sid);
2106        }
2107
2108        // DPoP jkt takes priority over userPubKey (RFC 9449 § 6).
2109        if let Some(ref jkt) = data.dpop_jkt {
2110            claims = claims.with_cnf_jkt_thumbprint(jkt.clone());
2111        } else if let Some(key_bytes) = service_key_bytes {
2112            claims = claims.with_cnf_jwk(&key_bytes);
2113        }
2114
2115        // v16 confirmation (frozen A §5), by STRUCTURAL classification:
2116        //  - DISPATCH-CAPABLE credentials — a service `wit+jwt`, or a user
2117        //    `at+jwt` carrying a proof-of-possession `cnf.jwk` — MUST bind their
2118        //    AUTHORITATIVE Primary signer group's `cnf.hs_signer_suite`, or FAIL
2119        //    CLOSED (never mint a non-conformant dispatch credential C rejects).
2120        //  - NON-DISPATCH OAuth tokens — a no-cnf bearer, or a DPoP `cnf.jkt`-
2121        //    only token — are standards-valid access tokens with no proof key to
2122        //    bind a signer suite: issuance stays valid and no suite is stamped.
2123        //    Delegation SOURCE validation and C proof admission independently
2124        //    reject any hs-less credential presented for MAC dispatch.
2125        let issue_err = |code: &str, message: String| {
2126            PolicyResponseVariant::Error(ErrorInfo {
2127                message,
2128                code: code.to_owned(),
2129                details: String::new(),
2130            })
2131        };
2132        if is_service_token {
2133            // Service (`wit+jwt`): the enrolled suite (manifest-authoritative,
2134            // key-bound to the assertion key resolved above).
2135            let svc = &subject["service:".len()..];
2136            let Some(key) = service_key_bytes else {
2137                return Ok(issue_err(
2138                    "SIGNER_SUITE_UNAVAILABLE",
2139                    format!("service '{svc}' issuance has no assertion key to bind a signer suite"),
2140                ));
2141            };
2142            match enrolled_service_signer_suite(self.enrollment().as_deref(), svc, &key) {
2143                Ok(suite) => claims = claims.with_cnf_hs_signer_suite(suite),
2144                Err(e) => {
2145                    return Ok(issue_err(
2146                        "SIGNER_SUITE_UNAVAILABLE",
2147                        format!("v16 signer suite for service '{svc}': {e}"),
2148                    ))
2149                }
2150            }
2151        } else if data.dpop_jkt.is_none() {
2152            // A user `at+jwt` carrying a proof-of-possession `cnf.jwk` is
2153            // DISPATCH-CAPABLE — resolve the AUTHORITATIVE Primary record for the
2154            // subject/tenant, require the verified cnf key to equal its Ed
2155            // component, and stamp the record's suite; no resolver / no active
2156            // record / key mismatch all FAIL CLOSED (frozen A §5). A no-cnf
2157            // bearer (no `service_key_bytes`) is non-dispatch and stamps none.
2158            if let Some(key) = service_key_bytes {
2159                let Some(resolver) = self.primary_enrollment_resolver.as_deref() else {
2160                    return Ok(issue_err(
2161                    "PRIMARY_RESOLVER_UNAVAILABLE",
2162                    "primary-enrollment resolver is not installed; user issuance is fail-closed \
2163                     until the authoritative primary enrollment is available"
2164                        .to_owned(),
2165                ));
2166                };
2167                let Some(group) = resolver.primary_group(&subject, &target_domain) else {
2168                    return Ok(issue_err(
2169                        "PRIMARY_UNRESOLVABLE",
2170                        format!("no active authoritative primary enrollment for '{subject}'"),
2171                    ));
2172                };
2173                // Frozen-registry suite/shape + exact key binding.
2174                use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
2175                let keys = &group.ordered_component_keys;
2176                let shape_ok = if group.suite_id == hyprstream_rpc::auth::SUITE_CLASSICAL_ED25519 {
2177                    keys.len() == 1 && keys[0].len() == 32
2178                } else if group.suite_id == hyprstream_rpc::auth::SUITE_HYBRID_ED25519_MLDSA65 {
2179                    keys.len() == 2 && keys[0].len() == 32 && keys[1].len() == 1952
2180                } else {
2181                    false
2182                };
2183                if !shape_ok || keys[0].as_slice() != key {
2184                    return Ok(issue_err(
2185                        "PRIMARY_UNRESOLVABLE",
2186                        "user cnf key does not match the authoritative primary enrollment, or the \
2187                     enrolled suite/shape is not a frozen-registry signer suite"
2188                            .to_owned(),
2189                    ));
2190                }
2191                let refs: Vec<&[u8]> = keys.iter().map(Vec::as_slice).collect();
2192                claims = claims.with_cnf_hs_signer_suite(URL_SAFE_NO_PAD.encode(
2193                    hyprstream_rpc::auth::signer_suite_thumbprint(&group.suite_id, &refs),
2194                ));
2195            }
2196            // else: no-cnf bearer → non-dispatch OAuth token; no suite stamped.
2197        }
2198        // else: DPoP `cnf.jkt`-only → non-dispatch OAuth token; no suite stamped.
2199
2200        let token = match self.sign_token(&claims, is_service_token).await {
2201            Ok(t) => t,
2202            Err(e) => {
2203                return Ok(PolicyResponseVariant::Error(ErrorInfo {
2204                    message: "Failed to issue token".to_owned(),
2205                    code: "SIGNING_NOT_CONFIGURED".to_owned(),
2206                    details: e.to_string(),
2207                }));
2208            }
2209        };
2210
2211        Ok(PolicyResponseVariant::IssueTokenResult(TokenInfo {
2212            token,
2213            expires_at: claims.exp,
2214        }))
2215    }
2216
2217    async fn handle_list_scopes(
2218        &self,
2219        _ctx: &EnvelopeContext,
2220        _request_id: u64,
2221    ) -> Result<PolicyResponseVariant> {
2222        Ok(PolicyResponseVariant::ListScopesResult(ScopeList {
2223            scopes: self.supported_scopes.clone(),
2224        }))
2225    }
2226
2227    async fn handle_get_policy(
2228        &self,
2229        _ctx: &EnvelopeContext,
2230        _request_id: u64,
2231    ) -> Result<PolicyResponseVariant> {
2232        trace!("Getting current policy");
2233
2234        let policies = self.policy_manager.get_policy().await;
2235        let groupings = self.policy_manager.get_grouping_policy().await;
2236
2237        let rules: Vec<PolicyRule> = policies
2238            .into_iter()
2239            .map(|p| PolicyRule {
2240                subject: p.first().cloned().unwrap_or_default(),
2241                domain: p.get(1).cloned().unwrap_or_default(),
2242                resource: p.get(2).cloned().unwrap_or_default(),
2243                action: p.get(3).cloned().unwrap_or_default(),
2244                effect: p.get(4).cloned().unwrap_or_default(),
2245            })
2246            .collect();
2247
2248        let grouping_list: Vec<Grouping> = groupings
2249            .into_iter()
2250            .map(|g| Grouping {
2251                user: g.first().cloned().unwrap_or_default(),
2252                role: g.get(1).cloned().unwrap_or_default(),
2253            })
2254            .collect();
2255
2256        Ok(PolicyResponseVariant::GetPolicyResult(PolicyInfo {
2257            rules,
2258            groupings: grouping_list,
2259        }))
2260    }
2261
2262    async fn handle_apply_template(
2263        &self,
2264        ctx: &EnvelopeContext,
2265        _request_id: u64,
2266        data: &ApplyTemplate,
2267    ) -> Result<PolicyResponseVariant> {
2268        let caller = ctx.subject().to_string();
2269        // The colocated PolicyService authority bootstraps templates over the
2270        // local IPC plane without a tenant-bearing user token. Keep that
2271        // authority on the explicit global bootstrap domain, while ordinary
2272        // tenantless callers remain denied by `request_domain`.
2273        let domain = self.request_domain(ctx)?;
2274        let allowed = self
2275            .policy_manager
2276            .check_with_domain(&caller, &domain, "policy:*", "ttt.writeback")
2277            .await;
2278        if !allowed {
2279            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2280                message: format!("Unauthorized: {} cannot manage policy", caller),
2281                code: "UNAUTHORIZED".into(),
2282                details: String::new(),
2283            }));
2284        }
2285
2286        info!("Applying policy template: {}", data.name);
2287
2288        // Validate template exists
2289        let template = match policy_templates::get_template(&data.name) {
2290            Some(t) => t,
2291            None => {
2292                let available: Vec<&str> = policy_templates::get_templates()
2293                    .iter()
2294                    .map(|t| t.name)
2295                    .collect();
2296                return Ok(PolicyResponseVariant::Error(ErrorInfo {
2297                    message: format!(
2298                        "Unknown template: '{}'. Available: {}",
2299                        data.name,
2300                        available.join(", ")
2301                    ),
2302                    code: "UNKNOWN_TEMPLATE".to_owned(),
2303                    details: String::new(),
2304                }));
2305            }
2306        };
2307
2308        // All writers stage the same policies/ tree, so keep the mutation,
2309        // save, and commit together with role transactions.
2310        let _write_guard = self.policy_write_lock.lock().await;
2311
2312        // Apply template rules via the Casbin enforcer.
2313        // Base rules are always present (injected at init/reload), so templates
2314        // only add their own rules on top. The enforcer's save_policy() persists
2315        // everything (base + template) to disk via the FileAdapter.
2316        if let Err(e) = self.policy_manager.apply_template(template).await {
2317            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2318                message: format!("Failed to apply template: {}", e),
2319                code: "TEMPLATE_APPLY_FAILED".to_owned(),
2320                details: String::new(),
2321            }));
2322        }
2323
2324        // Stage and commit
2325        let commit_msg = format!("policy: apply {} template", data.name);
2326        match self.stage_and_commit_policies(&commit_msg).await {
2327            Ok(_) => {
2328                info!("Template '{}' applied and committed", data.name);
2329                Ok(PolicyResponseVariant::ApplyTemplateResult(commit_msg))
2330            }
2331            Err(e) => {
2332                // Policy is already reloaded and valid, just commit failed
2333                warn!("Template applied but commit failed: {}", e);
2334                Ok(PolicyResponseVariant::ApplyTemplateResult(format!(
2335                    "policy: apply {} template (commit failed: {})",
2336                    data.name, e
2337                )))
2338            }
2339        }
2340    }
2341
2342    async fn handle_apply_draft(
2343        &self,
2344        ctx: &EnvelopeContext,
2345        _request_id: u64,
2346        data: &ApplyDraft,
2347    ) -> Result<PolicyResponseVariant> {
2348        let caller = ctx.subject().to_string();
2349        let domain = self.request_domain(ctx)?;
2350        let allowed = self
2351            .policy_manager
2352            .check_with_domain(&caller, &domain, "policy:*", "ttt.writeback")
2353            .await;
2354        if !allowed {
2355            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2356                message: format!("Unauthorized: {} cannot manage policy", caller),
2357                code: "UNAUTHORIZED".into(),
2358                details: String::new(),
2359            }));
2360        }
2361
2362        // Serialize the disk reload and its commit with all other policy
2363        // writers, since they share one policies/ tree and Git index.
2364        let _write_guard = self.policy_write_lock.lock().await;
2365
2366        info!("Applying draft policy changes");
2367
2368        // Validate current disk state
2369        if let Err(e) = self.policy_manager.reload().await {
2370            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2371                message: format!("Policy validation failed: {}", e),
2372                code: "VALIDATION_FAILED".to_owned(),
2373                details: "Fix errors in policy.csv before applying.".to_owned(),
2374            }));
2375        }
2376
2377        // Generate commit message
2378        let commit_msg = data
2379            .message
2380            .as_ref()
2381            .filter(|s| !s.is_empty())
2382            .cloned()
2383            .unwrap_or_else(|| {
2384                let timestamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S");
2385                format!("policy: update access control rules ({timestamp})")
2386            });
2387
2388        // Stage and commit
2389        match self.stage_and_commit_policies(&commit_msg).await {
2390            Ok(_) => {
2391                info!("Draft policy applied: {}", commit_msg);
2392                Ok(PolicyResponseVariant::ApplyDraftResult(commit_msg))
2393            }
2394            Err(e) => Ok(PolicyResponseVariant::Error(ErrorInfo {
2395                message: format!("Commit failed: {}", e),
2396                code: "COMMIT_FAILED".to_owned(),
2397                details: String::new(),
2398            })),
2399        }
2400    }
2401
2402    async fn handle_rollback(
2403        &self,
2404        ctx: &EnvelopeContext,
2405        _request_id: u64,
2406        data: &RollbackPolicy,
2407    ) -> Result<PolicyResponseVariant> {
2408        let caller = ctx.subject().to_string();
2409        let domain = self.request_domain(ctx)?;
2410        let allowed = self
2411            .policy_manager
2412            .check_with_domain(&caller, &domain, "policy:*", "ttt.writeback")
2413            .await;
2414        if !allowed {
2415            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2416                message: format!("Unauthorized: {} cannot manage policy", caller),
2417                code: "UNAUTHORIZED".into(),
2418                details: String::new(),
2419            }));
2420        }
2421
2422        info!("Rolling back policy to: {}", data.git_ref);
2423
2424        // Validate git_ref to prevent shell injection or path traversal.
2425        // Accept: 40-hex SHA, short SHA (7+ hex chars), or simple branch/tag names.
2426        let git_ref = data.git_ref.trim().to_owned();
2427        {
2428            let valid = !git_ref.is_empty()
2429                && git_ref.len() <= 256
2430                && git_ref
2431                    .chars()
2432                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '/' | '.'));
2433            if !valid {
2434                return Ok(PolicyResponseVariant::Error(ErrorInfo {
2435                    message: format!(
2436                        "Invalid git ref '{}': only [a-zA-Z0-9._/-] allowed",
2437                        git_ref
2438                    ),
2439                    code: "INVALID_GIT_REF".into(),
2440                    details: String::new(),
2441                }));
2442            }
2443        }
2444
2445        // Checkout, reload, and commit must not race a role transaction or
2446        // another whole-tree policy writer.
2447        let _write_guard = self.policy_write_lock.lock().await;
2448
2449        // Use git2 escape hatch to checkout policies/ from the target ref
2450        let reg = self.git2db.read().await;
2451        let handle = reg.repo(&self.registry_repo_id)?;
2452        let repo = handle
2453            .open_repo()
2454            .map_err(|e| anyhow!("Failed to open repository: {}", e))?;
2455
2456        // Resolve ref and checkout policies/ from it
2457        let git_ref_clone = git_ref.clone();
2458        tokio::task::spawn_blocking(move || -> Result<()> {
2459            let obj = repo
2460                .revparse_single(&git_ref_clone)
2461                .map_err(|e| anyhow!("Invalid git ref '{}': {}", git_ref_clone, e))?;
2462            let commit = obj.peel_to_commit().map_err(|e| {
2463                anyhow!("Ref '{}' does not point to a commit: {}", git_ref_clone, e)
2464            })?;
2465            let tree = commit
2466                .tree()
2467                .map_err(|e| anyhow!("Failed to get tree: {}", e))?;
2468
2469            // Find the policies/ subtree
2470            let policies_entry = tree
2471                .get_path(std::path::Path::new("policies"))
2472                .map_err(|e| anyhow!("No policies/ directory in {}: {}", git_ref_clone, e))?;
2473            let policies_tree = repo
2474                .find_tree(policies_entry.id())
2475                .map_err(|e| anyhow!("Failed to read policies tree: {}", e))?;
2476
2477            // Checkout the policies tree to the workdir
2478            let mut checkout_opts = git2::build::CheckoutBuilder::new();
2479            checkout_opts.force();
2480            checkout_opts.path("policies");
2481            repo.checkout_tree(policies_tree.as_object(), Some(&mut checkout_opts))
2482                .map_err(|e| {
2483                    anyhow!("Failed to checkout policies/ from {}: {}", git_ref_clone, e)
2484                })?;
2485
2486            Ok(())
2487        })
2488        .await
2489        .map_err(|e| anyhow!("Checkout task failed: {}", e))??;
2490
2491        // Validate the restored policy
2492        if let Err(e) = self.policy_manager.reload().await {
2493            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2494                message: format!("Rollback validation failed: {}", e),
2495                code: "VALIDATION_FAILED".to_owned(),
2496                details: "The target version contains invalid policy.".to_owned(),
2497            }));
2498        }
2499
2500        // Stage and commit the rollback
2501        let commit_msg = format!("policy: rollback to {}", git_ref);
2502        match self.stage_and_commit_policies(&commit_msg).await {
2503            Ok(_) => {
2504                info!("Policy rolled back to {}", git_ref);
2505                Ok(PolicyResponseVariant::RollbackResult(commit_msg))
2506            }
2507            Err(e) => Ok(PolicyResponseVariant::Error(ErrorInfo {
2508                message: format!("Rollback commit failed: {}", e),
2509                code: "COMMIT_FAILED".to_owned(),
2510                details: String::new(),
2511            })),
2512        }
2513    }
2514
2515    async fn handle_get_history(
2516        &self,
2517        ctx: &EnvelopeContext,
2518        _request_id: u64,
2519        data: &GetHistory,
2520    ) -> Result<PolicyResponseVariant> {
2521        let caller = ctx.subject().to_string();
2522        let domain = self.request_domain(ctx)?;
2523        let allowed = self
2524            .policy_manager
2525            .check_with_domain(&caller, &domain, "policy:*", "ttt.writeback")
2526            .await;
2527        if !allowed {
2528            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2529                message: format!("Unauthorized: {} cannot manage policy", caller),
2530                code: "UNAUTHORIZED".into(),
2531                details: String::new(),
2532            }));
2533        }
2534
2535        let count = if data.count == 0 {
2536            10
2537        } else {
2538            data.count as usize
2539        };
2540
2541        trace!("Getting policy history (count={})", count);
2542
2543        let reg = self.git2db.read().await;
2544        let handle = reg.repo(&self.registry_repo_id)?;
2545        let repo = handle
2546            .open_repo()
2547            .map_err(|e| anyhow!("Failed to open repository: {}", e))?;
2548
2549        let entries = tokio::task::spawn_blocking(move || -> Result<Vec<PolicyHistoryEntry>> {
2550            let mut entries = Vec::new();
2551            let mut revwalk = repo
2552                .revwalk()
2553                .map_err(|e| anyhow!("Failed to create revwalk: {}", e))?;
2554            revwalk
2555                .push_head()
2556                .map_err(|e| anyhow!("Failed to push HEAD: {}", e))?;
2557
2558            for oid_result in revwalk {
2559                if entries.len() >= count {
2560                    break;
2561                }
2562
2563                let oid = oid_result.map_err(|e| anyhow!("Revwalk error: {}", e))?;
2564                let commit = repo
2565                    .find_commit(oid)
2566                    .map_err(|e| anyhow!("Failed to find commit: {}", e))?;
2567
2568                // Check if this commit touches policies/
2569                let dominated = if let Ok(parent) = commit.parent(0) {
2570                    let commit_tree = commit.tree().ok();
2571                    let parent_tree = parent.tree().ok();
2572                    if let (Some(ct), Some(pt)) = (commit_tree, parent_tree) {
2573                        let diff = repo.diff_tree_to_tree(Some(&pt), Some(&ct), None).ok();
2574                        diff.is_some_and(|d| {
2575                            d.deltas().any(|delta| {
2576                                let path =
2577                                    delta.new_file().path().or_else(|| delta.old_file().path());
2578                                path.is_some_and(|p| p.starts_with("policies"))
2579                            })
2580                        })
2581                    } else {
2582                        false
2583                    }
2584                } else {
2585                    // Root commit — check if it has policies/
2586                    commit
2587                        .tree()
2588                        .ok()
2589                        .and_then(|t| t.get_path(std::path::Path::new("policies")).ok())
2590                        .is_some()
2591                };
2592
2593                if dominated {
2594                    let time = commit.time();
2595                    let date = chrono::DateTime::from_timestamp(time.seconds(), 0)
2596                        .map(|dt| dt.format("%Y-%m-%d %H:%M:%S UTC").to_string())
2597                        .unwrap_or_else(|| "unknown".to_owned());
2598
2599                    entries.push(PolicyHistoryEntry {
2600                        hash: oid.to_string()[..8].to_owned(),
2601                        message: commit.message().unwrap_or("").trim().to_owned(),
2602                        date,
2603                    });
2604                }
2605            }
2606
2607            Ok(entries)
2608        })
2609        .await
2610        .map_err(|e| anyhow!("History task failed: {}", e))??;
2611
2612        Ok(PolicyResponseVariant::GetHistoryResult(PolicyHistory {
2613            entries,
2614        }))
2615    }
2616
2617    async fn handle_get_diff(
2618        &self,
2619        ctx: &EnvelopeContext,
2620        _request_id: u64,
2621        data: &GetDiff,
2622    ) -> Result<PolicyResponseVariant> {
2623        let caller = ctx.subject().to_string();
2624        let domain = self.request_domain(ctx)?;
2625        let allowed = self
2626            .policy_manager
2627            .check_with_domain(&caller, &domain, "policy:*", "ttt.writeback")
2628            .await;
2629        if !allowed {
2630            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2631                message: format!("Unauthorized: {} cannot manage policy", caller),
2632                code: "UNAUTHORIZED".into(),
2633                details: String::new(),
2634            }));
2635        }
2636
2637        let git_ref = data
2638            .git_ref
2639            .as_ref()
2640            .filter(|s| !s.is_empty())
2641            .cloned()
2642            .unwrap_or_else(|| "HEAD".to_owned());
2643
2644        let reg = self.git2db.read().await;
2645        let handle = reg.repo(&self.registry_repo_id)?;
2646        let repo = handle
2647            .open_repo()
2648            .map_err(|e| anyhow!("Failed to open repository: {}", e))?;
2649
2650        let output = tokio::task::spawn_blocking(move || -> Result<String> {
2651            let obj = repo
2652                .revparse_single(&git_ref)
2653                .map_err(|e| anyhow!("Invalid git ref '{}': {}", git_ref, e))?;
2654            let tree = obj
2655                .peel_to_tree()
2656                .map_err(|e| anyhow!("Could not peel {} to tree: {}", git_ref, e))?;
2657
2658            let mut diff_opts = git2::DiffOptions::new();
2659            diff_opts.pathspec("policies/");
2660
2661            let diff = repo
2662                .diff_tree_to_workdir_with_index(Some(&tree), Some(&mut diff_opts))
2663                .map_err(|e| anyhow!("Failed to compute diff: {}", e))?;
2664
2665            let mut result = String::new();
2666            diff.print(git2::DiffFormat::Patch, |_delta, _hunk, line| {
2667                let origin = line.origin();
2668                if origin == '+' || origin == '-' || origin == ' ' {
2669                    result.push(origin);
2670                }
2671                if let Ok(s) = std::str::from_utf8(line.content()) {
2672                    result.push_str(s);
2673                }
2674                true
2675            })?;
2676
2677            Ok(result)
2678        })
2679        .await
2680        .map_err(|e| anyhow!("Diff task failed: {}", e))??;
2681
2682        Ok(PolicyResponseVariant::GetDiffResult(output))
2683    }
2684
2685    async fn handle_get_draft_status(
2686        &self,
2687        ctx: &EnvelopeContext,
2688        _request_id: u64,
2689    ) -> Result<PolicyResponseVariant> {
2690        let caller = ctx.subject().to_string();
2691        let domain = self.request_domain(ctx)?;
2692        let allowed = self
2693            .policy_manager
2694            .check_with_domain(&caller, &domain, "policy:*", "ttt.writeback")
2695            .await;
2696        if !allowed {
2697            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2698                message: format!("Unauthorized: {} cannot manage policy", caller),
2699                code: "UNAUTHORIZED".into(),
2700                details: String::new(),
2701            }));
2702        }
2703
2704        let reg = self.git2db.read().await;
2705        let handle = reg.repo(&self.registry_repo_id)?;
2706        let repo = handle
2707            .open_repo()
2708            .map_err(|e| anyhow!("Failed to open repository: {}", e))?;
2709
2710        let (has_changes, summary) =
2711            tokio::task::spawn_blocking(move || -> Result<(bool, String)> {
2712                let mut opts = git2::StatusOptions::new();
2713                opts.pathspec("policies/");
2714                opts.include_untracked(true);
2715
2716                let statuses = repo
2717                    .statuses(Some(&mut opts))
2718                    .map_err(|e| anyhow!("Failed to get status: {}", e))?;
2719
2720                let count = statuses.len();
2721                let summary = if count == 0 {
2722                    "no changes".to_owned()
2723                } else {
2724                    format!("{} file(s) changed", count)
2725                };
2726
2727                Ok((count > 0, summary))
2728            })
2729            .await
2730            .map_err(|e| anyhow!("Status task failed: {}", e))??;
2731
2732        Ok(PolicyResponseVariant::GetDraftStatusResult(DraftStatus {
2733            has_changes,
2734            summary,
2735        }))
2736    }
2737
2738    async fn handle_add_grouping(
2739        &self,
2740        ctx: &EnvelopeContext,
2741        _request_id: u64,
2742        data: &AddGrouping,
2743    ) -> Result<PolicyResponseVariant> {
2744        let caller = ctx.subject().to_string();
2745        let domain = self.request_domain(ctx)?;
2746
2747        // Fine-grained permission check: caller must have ttt.writeback on policy:roles
2748        let allowed = self
2749            .policy_manager
2750            .check_with_domain(&caller, &domain, "policy:roles", "ttt.writeback")
2751            .await;
2752        if !allowed {
2753            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2754                message: format!(
2755                    "Subject '{}' is not authorized to manage role assignments",
2756                    caller
2757                ),
2758                code: "UNAUTHORIZED".to_owned(),
2759                details: "Requires 'ttt.writeback' permission on 'policy:roles'".to_owned(),
2760            }));
2761        }
2762
2763        // Validate inputs
2764        if data.user.is_empty() || data.role.is_empty() {
2765            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2766                message: "user and role must be non-empty".to_owned(),
2767                code: "INVALID_INPUT".to_owned(),
2768                details: String::new(),
2769            }));
2770        }
2771
2772        // Elevated roles can only be assigned by policy service.
2773        const ELEVATED_ROLES: &[&str] = &["ttt.privileged", "operator"];
2774        let caller_subject = ctx.subject().to_string();
2775        if ELEVATED_ROLES.contains(&data.role.as_str()) && caller_subject != "service:policy" {
2776            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2777                message: format!(
2778                    "Role '{}' is an elevated role and can only be assigned by policy service",
2779                    data.role
2780                ),
2781                code: "UNAUTHORIZED".to_owned(),
2782                details: "Elevated roles require service:policy identity".to_owned(),
2783            }));
2784        }
2785
2786        // Callers cannot assign roles to themselves
2787        if data.user == caller {
2788            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2789                message: "Cannot assign roles to yourself".to_owned(),
2790                code: "SELF_ASSIGNMENT".to_owned(),
2791                details: "Callers may not assign roles to themselves".to_owned(),
2792            }));
2793        }
2794
2795        let _write_guard = self.policy_write_lock.lock().await;
2796        // Global bootstrap policy stores memberships in Casbin's global `g`
2797        // relation; tenant-scoped memberships live in `g2`. Do not turn a
2798        // global authority domain into a literal `g2(..., "*")` row.
2799        let changed = if domain == "*" {
2800            self.policy_manager
2801                .add_role_for_user(&data.user, &data.role)
2802                .await
2803        } else {
2804            self.policy_manager
2805                .add_role_for_user_in_domain(&data.user, &data.role, &domain)
2806                .await
2807        }
2808        .map_err(|e| anyhow!("Failed to add role: {}", e))?;
2809
2810        if !changed {
2811            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2812                message: format!(
2813                    "Role '{}' is already assigned to '{}'",
2814                    data.role, data.user
2815                ),
2816                code: "NO_CHANGE".to_owned(),
2817                details: "No policy update was committed.".to_owned(),
2818            }));
2819        }
2820
2821        // Do not leave a failed persistence attempt active only in memory:
2822        // subsequent identical requests are legitimate retries and must still
2823        // reach the persistence boundary rather than becoming a false no-op.
2824        if let Err(error) = self.policy_manager.save().await {
2825            let rollback = if domain == "*" {
2826                self.policy_manager
2827                    .remove_role_for_user(&data.user, &data.role)
2828                    .await
2829            } else {
2830                self.policy_manager
2831                    .remove_role_for_user_in_domain(&data.user, &data.role, &domain)
2832                    .await
2833            };
2834            match rollback {
2835                Ok(true) => {
2836                    return Err(anyhow!("Failed to save policy after role grant: {}", error))
2837                }
2838                Ok(false) => {
2839                    return Err(anyhow!(
2840                        "Failed to save policy after role grant: {}; rollback was not applied",
2841                        error
2842                    ))
2843                }
2844                Err(rollback_error) => {
2845                    return Err(anyhow!(
2846                        "Failed to save policy after role grant: {}; rollback failed: {}",
2847                        error,
2848                        rollback_error
2849                    ))
2850                }
2851            }
2852        }
2853
2854        // Commit to git
2855        let commit_msg = format!(
2856            "policy: grant role {} to {} in {} [by {}]",
2857            data.role, data.user, domain, caller
2858        );
2859        let sha = match self.stage_and_commit_policies(&commit_msg).await {
2860            Ok(sha) => sha,
2861            Err(e) => {
2862                warn!("Role grant persisted but audit commit failed: {}", e);
2863                return Ok(PolicyResponseVariant::Error(ErrorInfo {
2864                    message: format!("Role grant persisted but audit commit failed: {e}"),
2865                    code: "COMMIT_FAILED".to_owned(),
2866                    details: "The role change was retained; investigate the audit repository."
2867                        .to_owned(),
2868                }));
2869            }
2870        };
2871
2872        info!(
2873            "Granted role '{}' to '{}' in domain '{}' (caller={})",
2874            data.role, data.user, domain, caller
2875        );
2876        Ok(PolicyResponseVariant::AddGroupingResult(sha))
2877    }
2878
2879    async fn handle_remove_grouping(
2880        &self,
2881        ctx: &EnvelopeContext,
2882        _request_id: u64,
2883        data: &RemoveGrouping,
2884    ) -> Result<PolicyResponseVariant> {
2885        let caller = ctx.subject().to_string();
2886        let domain = self.request_domain(ctx)?;
2887
2888        // Fine-grained permission check: caller must have ttt.writeback on policy:roles
2889        let allowed = self
2890            .policy_manager
2891            .check_with_domain(&caller, &domain, "policy:roles", "ttt.writeback")
2892            .await;
2893        if !allowed {
2894            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2895                message: format!(
2896                    "Subject '{}' is not authorized to manage role assignments",
2897                    caller
2898                ),
2899                code: "UNAUTHORIZED".to_owned(),
2900                details: "Requires 'ttt.writeback' permission on 'policy:roles'".to_owned(),
2901            }));
2902        }
2903
2904        // Validate inputs
2905        if data.user.is_empty() || data.role.is_empty() {
2906            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2907                message: "user and role must be non-empty".to_owned(),
2908                code: "INVALID_INPUT".to_owned(),
2909                details: String::new(),
2910            }));
2911        }
2912
2913        let _write_guard = self.policy_write_lock.lock().await;
2914        // Match the grouping relation selected by role grant above. A global
2915        // bootstrap membership is `g(user, role)`, not `g2(user, role, "*")`.
2916        let changed = if domain == "*" {
2917            self.policy_manager
2918                .remove_role_for_user(&data.user, &data.role)
2919                .await
2920        } else {
2921            self.policy_manager
2922                .remove_role_for_user_in_domain(&data.user, &data.role, &domain)
2923                .await
2924        }
2925        .map_err(|e| anyhow!("Failed to remove role: {}", e))?;
2926
2927        if !changed {
2928            return Ok(PolicyResponseVariant::Error(ErrorInfo {
2929                message: format!("Role '{}' is not assigned to '{}'", data.role, data.user),
2930                code: "NOT_FOUND".to_owned(),
2931                details: "No policy update was committed.".to_owned(),
2932            }));
2933        }
2934
2935        // Restore the in-memory edge when persistence fails so a later retry
2936        // remains a real mutation instead of silently reporting NOT_FOUND.
2937        if let Err(error) = self.policy_manager.save().await {
2938            let rollback = if domain == "*" {
2939                self.policy_manager
2940                    .add_role_for_user(&data.user, &data.role)
2941                    .await
2942            } else {
2943                self.policy_manager
2944                    .add_role_for_user_in_domain(&data.user, &data.role, &domain)
2945                    .await
2946            };
2947            match rollback {
2948                Ok(true) => {
2949                    return Err(anyhow!(
2950                        "Failed to save policy after role revoke: {}",
2951                        error
2952                    ))
2953                }
2954                Ok(false) => {
2955                    return Err(anyhow!(
2956                        "Failed to save policy after role revoke: {}; rollback was not applied",
2957                        error
2958                    ))
2959                }
2960                Err(rollback_error) => {
2961                    return Err(anyhow!(
2962                        "Failed to save policy after role revoke: {}; rollback failed: {}",
2963                        error,
2964                        rollback_error
2965                    ))
2966                }
2967            }
2968        }
2969
2970        // Commit to git
2971        let commit_msg = format!(
2972            "policy: revoke role {} from {} in {} [by {}]",
2973            data.role, data.user, domain, caller
2974        );
2975        let sha = match self.stage_and_commit_policies(&commit_msg).await {
2976            Ok(sha) => sha,
2977            Err(e) => {
2978                warn!("Role revoke persisted but audit commit failed: {}", e);
2979                return Ok(PolicyResponseVariant::Error(ErrorInfo {
2980                    message: format!("Role revoke persisted but audit commit failed: {e}"),
2981                    code: "COMMIT_FAILED".to_owned(),
2982                    details: "The role change was retained; investigate the audit repository."
2983                        .to_owned(),
2984                }));
2985            }
2986        };
2987
2988        info!(
2989            "Revoked role '{}' from '{}' in domain '{}' (caller={})",
2990            data.role, data.user, domain, caller
2991        );
2992        Ok(PolicyResponseVariant::RemoveGroupingResult(sha))
2993    }
2994
2995    async fn handle_set_branch_visibility(
2996        &self,
2997        ctx: &EnvelopeContext,
2998        _request_id: u64,
2999        data: &SetBranchVisibility,
3000    ) -> Result<PolicyResponseVariant> {
3001        let caller = ctx.subject().to_string();
3002        let domain = ctx.domain()?;
3003        let resource = format!("model:{}:{}", data.model_name, data.branch_name);
3004
3005        // Require manage (ttt.writeback) on the model resource
3006        let allowed = self
3007            .policy_manager
3008            .check_with_domain(&caller, &domain, &resource, "ttt.writeback")
3009            .await;
3010        if !allowed {
3011            return Ok(PolicyResponseVariant::Error(ErrorInfo {
3012                message: format!("Unauthorized: {} cannot manage {}", caller, resource),
3013                code: "UNAUTHORIZED".to_owned(),
3014                details: String::new(),
3015            }));
3016        }
3017
3018        // Visibility rules are persisted into the same policies/ tree as role
3019        // mutations, so keep this whole operation serialized through commit.
3020        let _write_guard = self.policy_write_lock.lock().await;
3021
3022        if data.public {
3023            // Make public: add wildcard infer+query rules
3024            let _ = self
3025                .policy_manager
3026                .add_policy_with_domain("*", "*", &resource, "infer.generate", "allow")
3027                .await;
3028            let _ = self
3029                .policy_manager
3030                .add_policy_with_domain("*", "*", &resource, "query.status", "allow")
3031                .await;
3032        } else {
3033            // Make private: remove wildcard rules
3034            let _ = self
3035                .policy_manager
3036                .remove_policy_with_domain("*", "*", &resource, "infer.generate", "allow")
3037                .await;
3038            let _ = self
3039                .policy_manager
3040                .remove_policy_with_domain("*", "*", &resource, "query.status", "allow")
3041                .await;
3042        }
3043
3044        // Persist in-memory Casbin state to disk before staging
3045        self.policy_manager
3046            .save()
3047            .await
3048            .map_err(|e| anyhow!("Failed to save policy after visibility change: {}", e))?;
3049
3050        let vis_str = if data.public { "public" } else { "private" };
3051        let msg = format!(
3052            "policy: set {}/{} visibility={} [by {}]",
3053            data.model_name, data.branch_name, vis_str, caller
3054        );
3055        let sha = match self.stage_and_commit_policies(&msg).await {
3056            Ok(sha) => sha,
3057            Err(e) => {
3058                warn!("Visibility set but commit failed: {}", e);
3059                format!("(commit failed: {})", e)
3060            }
3061        };
3062
3063        info!(
3064            "Set branch {}/{} to {} (caller={})",
3065            data.model_name, data.branch_name, vis_str, caller
3066        );
3067        Ok(PolicyResponseVariant::SetBranchVisibilityResult(sha))
3068    }
3069
3070    /// Publisher registers a topic prefix. No group key stored here — publisher holds it.
3071    async fn handle_register_event_prefix(
3072        &self,
3073        ctx: &EnvelopeContext,
3074        _request_id: u64,
3075        data: &RegisterEventPrefix,
3076    ) -> Result<PolicyResponseVariant> {
3077        // Validate prefix BEFORE constructing scope (prevents Casbin metacharacter injection)
3078        if let Err(e) = validate_event_prefix(&data.prefix) {
3079            return Ok(PolicyResponseVariant::Error(ErrorInfo {
3080                message: e,
3081                code: "INVALID_ARGUMENT".to_owned(),
3082                details: String::new(),
3083            }));
3084        }
3085
3086        // Authorization: publish:events:{prefix}.*
3087        let scope = format!("publish:events:{}.*", data.prefix);
3088        self.authorize(ctx, &scope, "register").await?;
3089        let key = EventPrefixKey::new(ctx.domain()?, &data.prefix);
3090        let owner = ctx.subject().to_string();
3091
3092        let mut pubkey = [0u8; 32];
3093        if data.publisher_ephemeral_pubkey.len() != 32 {
3094            return Ok(PolicyResponseVariant::Error(ErrorInfo {
3095                message: "publisher pubkey must be 32 bytes".to_owned(),
3096                code: "INVALID_ARGUMENT".to_owned(),
3097                details: String::new(),
3098            }));
3099        }
3100        pubkey.copy_from_slice(&data.publisher_ephemeral_pubkey);
3101
3102        let mut prefixes = self.event_prefixes.write().await;
3103        match validate_event_prefix_registration(&prefixes, &key, &owner) {
3104            Ok(()) => {}
3105            Err(EventPrefixRegistrationError::OwnedByAnotherSubject) => {
3106                return Ok(PolicyResponseVariant::Error(ErrorInfo {
3107                    message: format!(
3108                        "prefix '{}' is already registered by another subject in this tenant",
3109                        data.prefix
3110                    ),
3111                    code: "ALREADY_EXISTS".to_owned(),
3112                    details: String::new(),
3113                }))
3114            }
3115            Err(EventPrefixRegistrationError::CrossTenantShadow) => {
3116                return Ok(PolicyResponseVariant::Error(ErrorInfo {
3117                    message: format!(
3118                        "prefix '{}' conflicts with a cross-tenant prefix",
3119                        data.prefix
3120                    ),
3121                    code: "CONFLICT".to_owned(),
3122                    details: String::new(),
3123                }))
3124            }
3125        }
3126        prefixes.insert(
3127            key,
3128            EventPrefixState {
3129                owner,
3130                publisher_pubkey: pubkey,
3131                schema: data.schema.clone(),
3132                subscriber_pubkeys: HashMap::new(),
3133                wrapped_keys: HashMap::new(),
3134            },
3135        );
3136
3137        tracing::info!(prefix = %data.prefix, "Registered event prefix");
3138        Ok(PolicyResponseVariant::RegisterEventPrefixResult)
3139    }
3140
3141    /// Subscriber requests access. Checks scope, stores subscriber pubkey,
3142    /// returns publisher pubkey + any pre-wrapped key blob.
3143    async fn handle_subscribe_event_prefix(
3144        &self,
3145        ctx: &EnvelopeContext,
3146        _request_id: u64,
3147        data: &SubscribeEventPrefix,
3148    ) -> Result<PolicyResponseVariant> {
3149        // Validate prefix BEFORE constructing scope
3150        if let Err(e) = validate_event_prefix(&data.prefix) {
3151            return Ok(PolicyResponseVariant::Error(ErrorInfo {
3152                message: e,
3153                code: "INVALID_ARGUMENT".to_owned(),
3154                details: String::new(),
3155            }));
3156        }
3157
3158        // Authorization: subscribe:events:{prefix}.*
3159        let scope = format!("subscribe:events:{}.*", data.prefix);
3160        self.authorize(ctx, &scope, "subscribe").await?;
3161        let key = EventPrefixKey::new(ctx.domain()?, &data.prefix);
3162
3163        let mut sub_pubkey = [0u8; 32];
3164        if data.subscriber_ephemeral_pubkey.len() != 32 {
3165            return Ok(PolicyResponseVariant::Error(ErrorInfo {
3166                message: "subscriber pubkey must be 32 bytes".to_owned(),
3167                code: "INVALID_ARGUMENT".to_owned(),
3168                details: String::new(),
3169            }));
3170        }
3171        sub_pubkey.copy_from_slice(&data.subscriber_ephemeral_pubkey);
3172
3173        let sub_hash = blake3::hash(&sub_pubkey);
3174        let mut hash_bytes = [0u8; 32];
3175        hash_bytes.copy_from_slice(sub_hash.as_bytes());
3176
3177        let mut prefixes = self.event_prefixes.write().await;
3178        let state = match prefixes.get_mut(&key) {
3179            Some(s) => s,
3180            None => {
3181                return Ok(PolicyResponseVariant::Error(ErrorInfo {
3182                    message: format!("prefix '{}' not registered", data.prefix),
3183                    code: "NOT_FOUND".to_owned(),
3184                    details: String::new(),
3185                }))
3186            }
3187        };
3188
3189        state.subscriber_pubkeys.insert(hash_bytes, sub_pubkey);
3190
3191        // If publisher has already wrapped a key for this subscriber, return it.
3192        let wrapped = state
3193            .wrapped_keys
3194            .get(&hash_bytes)
3195            .cloned()
3196            .unwrap_or_default();
3197
3198        Ok(PolicyResponseVariant::SubscribeEventPrefixResult(
3199            EventPrefixAccess {
3200                publisher_ephemeral_pubkey: state.publisher_pubkey.to_vec(),
3201                wrapped_group_key: wrapped,
3202                schema: state.schema.clone(),
3203            },
3204        ))
3205    }
3206
3207    /// Publisher fetches new subscriber pubkeys that need wrapping.
3208    async fn handle_get_pending_subscribers(
3209        &self,
3210        ctx: &EnvelopeContext,
3211        _request_id: u64,
3212        data: &GetPendingSubscribers,
3213    ) -> Result<PolicyResponseVariant> {
3214        // Validate prefix BEFORE constructing scope
3215        if let Err(e) = validate_event_prefix(&data.prefix) {
3216            return Ok(PolicyResponseVariant::Error(ErrorInfo {
3217                message: e,
3218                code: "INVALID_ARGUMENT".to_owned(),
3219                details: String::new(),
3220            }));
3221        }
3222
3223        // Authorization: publish:events:{prefix}.*
3224        let scope = format!("publish:events:{}.*", data.prefix);
3225        self.authorize(ctx, &scope, "get_subscribers").await?;
3226        let key = EventPrefixKey::new(ctx.domain()?, &data.prefix);
3227
3228        let prefixes = self.event_prefixes.read().await;
3229        let state = match prefixes.get(&key) {
3230            Some(s) => s,
3231            None => {
3232                return Ok(PolicyResponseVariant::Error(ErrorInfo {
3233                    message: format!("prefix '{}' not registered", data.prefix),
3234                    code: "NOT_FOUND".to_owned(),
3235                    details: String::new(),
3236                }))
3237            }
3238        };
3239
3240        // Return pubkeys that don't have wrapped keys yet.
3241        let pending: Vec<Vec<u8>> = state
3242            .subscriber_pubkeys
3243            .iter()
3244            .filter(|(hash, _)| !state.wrapped_keys.contains_key(*hash))
3245            .map(|(_, pubkey)| pubkey.to_vec())
3246            .collect();
3247
3248        Ok(PolicyResponseVariant::GetPendingSubscribersResult(
3249            PendingSubscribers { pubkeys: pending },
3250        ))
3251    }
3252
3253    /// Publisher deposits wrapped group key blobs (opaque to PolicyService).
3254    async fn handle_deposit_wrapped_keys(
3255        &self,
3256        ctx: &EnvelopeContext,
3257        _request_id: u64,
3258        data: &DepositWrappedKeys,
3259    ) -> Result<PolicyResponseVariant> {
3260        // Validate prefix BEFORE constructing scope
3261        if let Err(e) = validate_event_prefix(&data.prefix) {
3262            return Ok(PolicyResponseVariant::Error(ErrorInfo {
3263                message: e,
3264                code: "INVALID_ARGUMENT".to_owned(),
3265                details: String::new(),
3266            }));
3267        }
3268
3269        // Authorization: publish:events:{prefix}.*
3270        let scope = format!("publish:events:{}.*", data.prefix);
3271        self.authorize(ctx, &scope, "deposit_keys").await?;
3272        let key = EventPrefixKey::new(ctx.domain()?, &data.prefix);
3273
3274        let mut prefixes = self.event_prefixes.write().await;
3275        let state = match prefixes.get_mut(&key) {
3276            Some(s) => s,
3277            None => {
3278                return Ok(PolicyResponseVariant::Error(ErrorInfo {
3279                    message: format!("prefix '{}' not registered", data.prefix),
3280                    code: "NOT_FOUND".to_owned(),
3281                    details: String::new(),
3282                }))
3283            }
3284        };
3285
3286        let mut deposited = 0u32;
3287        for entry in &data.entries {
3288            if entry.sub_pubkey_hash.len() != 32 {
3289                warn!(
3290                    prefix = %data.prefix,
3291                    hash_len = entry.sub_pubkey_hash.len(),
3292                    "Rejecting malformed wrapped key entry: sub_pubkey_hash must be 32 bytes"
3293                );
3294                continue;
3295            }
3296            let mut hash = [0u8; 32];
3297            hash.copy_from_slice(&entry.sub_pubkey_hash);
3298            state.wrapped_keys.insert(hash, entry.wrapped_blob.clone());
3299            deposited += 1;
3300        }
3301
3302        tracing::debug!(
3303            prefix = %data.prefix,
3304            deposited,
3305            submitted = data.entries.len(),
3306            "Deposited wrapped keys"
3307        );
3308        Ok(PolicyResponseVariant::DepositWrappedKeysResult)
3309    }
3310
3311    async fn handle_resolve_service_key(
3312        &self,
3313        _ctx: &EnvelopeContext,
3314        _request_id: u64,
3315        data: &ResolveServiceKey,
3316    ) -> Result<PolicyResponseVariant> {
3317        // #441: authoritative resolution — return the REGISTERED key or ERROR.
3318        // We never derive an "expected" key from the root CA as a fallback: a
3319        // consumer must never receive a key the signer didn't actually register,
3320        // because a guessed key produces a silent mis-verify ("Response signed by
3321        // unexpected key") three layers away at the envelope check. Registered-or-
3322        // error converts that into a clear, early failure.
3323        let response = published_service_key_response(
3324            hyprstream_service::global_trust_store(),
3325            &data.service_name,
3326        )?;
3327        debug!(
3328            key_count = response.keys.len(),
3329            "Resolved service key set for '{}'", data.service_name
3330        );
3331        Ok(PolicyResponseVariant::ResolveServiceKeyResult(response))
3332    }
3333
3334    async fn handle_register_service_key(
3335        &self,
3336        ctx: &EnvelopeContext,
3337        _request_id: u64,
3338        data: &RegisterServiceKey,
3339    ) -> Result<PolicyResponseVariant> {
3340        let caller = ctx.subject().to_string();
3341
3342        // Verify the caller is who they claim to be.
3343        // The service JWT must be signed by the CA (our jwt_signing_key) and
3344        // its subject must match "service:{serviceName}".
3345        let claims = verify_service_registration_jwt(
3346            &data.service_jwt,
3347            self.jwt_key_source.as_deref(),
3348            &self.jwt_signing_key,
3349            hyprstream_rpc::envelope::global_verify_policy(),
3350        )?;
3351
3352        // Verify the provided verifying key matches the JWT's cnf.jwk claim.
3353        let vk_bytes: [u8; 32] = data
3354            .verifying_key
3355            .as_slice()
3356            .try_into()
3357            .map_err(|_| anyhow!("verifying_key must be 32 bytes"))?;
3358        let vk = VerifyingKey::from_bytes(&vk_bytes)
3359            .map_err(|e| anyhow!("Invalid Ed25519 verifying key: {e}"))?;
3360
3361        validate_service_key_registration(&claims, &data.service_name, &vk_bytes)?;
3362
3363        // Store in trust store (key-centric: the key IS the identity)
3364        {
3365            let trust = hyprstream_service::global_trust_store();
3366            trust.publish_service_registration(
3367                vk,
3368                &data.service_name,
3369                hyprstream_service::Attestation {
3370                    scopes: std::iter::once(data.service_name.clone()).collect(),
3371                    subject: None,
3372                    jwt: Some(data.service_jwt.clone()),
3373                    expires_at: claims.exp,
3374                    attested_by: Some(self.signing_key.verifying_key().to_bytes()),
3375                },
3376            )?;
3377        }
3378
3379        info!(service = %data.service_name, caller = %caller, "Registered service verifying key");
3380
3381        Ok(PolicyResponseVariant::RegisterServiceKeyResult)
3382    }
3383
3384    async fn handle_refresh_service_token(
3385        &self,
3386        ctx: &EnvelopeContext,
3387        _request_id: u64,
3388        data: &RefreshServiceTokenRequest,
3389    ) -> Result<PolicyResponseVariant> {
3390        const MAX_TTL: i64 = 2_592_000; // 30 days
3391        const MIN_TTL: i64 = 3_600; // 1 hour
3392
3393        let subject = match ctx.subject().name() {
3394            Some(s) if s.starts_with("service:") => s.to_owned(),
3395            Some(s) => {
3396                return Ok(PolicyResponseVariant::Error(ErrorInfo {
3397                    message: format!(
3398                        "Subject '{s}' is not a service identity; only services may self-renew"
3399                    ),
3400                    code: "NOT_A_SERVICE".to_owned(),
3401                    details: String::new(),
3402                }));
3403            }
3404            None => {
3405                return Ok(PolicyResponseVariant::Error(ErrorInfo {
3406                    message: "Anonymous callers cannot refresh service tokens".to_owned(),
3407                    code: "ANONYMOUS".to_owned(),
3408                    details: String::new(),
3409                }));
3410            }
3411        };
3412
3413        let ttl = data.ttl_seconds.clamp(MIN_TTL, MAX_TTL);
3414        let svc_name = &subject["service:".len()..];
3415
3416        let now = chrono::Utc::now().timestamp();
3417        let expires_at = now + ttl;
3418
3419        // Bind the renewed JWT to the verified caller key, not an arbitrary
3420        // sibling which happens to be published during overlap.
3421        let trust = hyprstream_service::global_trust_store();
3422        let vk = VerifyingKey::from_bytes(&ctx.cnf)
3423            .map_err(|_| anyhow!("refresh caller has an invalid Ed25519 verifying key"))?;
3424        if !trust.is_authorized(&vk, svc_name) {
3425            anyhow::bail!("service key '{svc_name}' is not registered for the renewing caller; refusing to fabricate cnf.jwk");
3426        }
3427
3428        let issuer = self.default_audience.clone().unwrap_or_default();
3429        // Provisioned native service credentials are authenticated against the
3430        // global Policy domain and intentionally carry no tenant claim. Keep
3431        // that path tenantless while using the explicit global domain for the
3432        // workload-session policy checks below. Tenant-bearing callers retain
3433        // their verified tenant binding.
3434        let policy_domain = self.request_domain(ctx)?;
3435        let tenant = if ctx.verified_tenant().is_some() {
3436            Some(ctx.domain()?)
3437        } else {
3438            None
3439        };
3440        let mut claims = renewed_service_claims(
3441            subject.clone(),
3442            now,
3443            expires_at,
3444            &issuer,
3445            tenant.as_deref(),
3446            &ctx.cnf,
3447        );
3448
3449        // ServiceEnrollmentManifest (v16 §11): renewal re-derives clearance
3450        // from the manifest — authority removed from enrollment never
3451        // survives a renewal, and renewal never gains authority. Resolve the
3452        // manifest ONCE through the injected-or-global authority (`enrollment`)
3453        // so clearance, signer-suite, and the workload-family policy below all
3454        // read the SAME authoritative source (and an isolated test can inject a
3455        // `workload_session=false` family without mutating process globals).
3456        let enrollment_manifest = self.enrollment();
3457        if let Some(manifest) = enrollment_manifest.as_ref() {
3458            let Some(clearance) = manifest.clearance_for_service(svc_name) else {
3459                return Ok(PolicyResponseVariant::Error(ErrorInfo {
3460                    message: format!("service '{svc_name}' has no enrollment entry"),
3461                    code: "UNENROLLED_SERVICE".to_owned(),
3462                    details: String::new(),
3463                }));
3464            };
3465            claims = claims.with_clearance(clearance);
3466            // v16 confirmation: the renewed service WIT stamps the SAME
3467            // authoritative signer suite (enrolled Ed + optional ML-DSA), so a
3468            // renewed credential stays a v16 dispatch credential (never drops to
3469            // legacy `cnf.jwk`-only). Fail closed if it cannot be resolved.
3470            match enrolled_service_signer_suite(Some(&**manifest), svc_name, &ctx.cnf) {
3471                Ok(suite) => claims = claims.with_cnf_hs_signer_suite(suite),
3472                Err(e) => {
3473                    return Ok(PolicyResponseVariant::Error(ErrorInfo {
3474                        message: format!("v16 signer suite unavailable for '{svc_name}': {e}"),
3475                        code: "SIGNER_SUITE_UNAVAILABLE".to_owned(),
3476                        details: String::new(),
3477                    }));
3478                }
3479            }
3480        }
3481
3482        // Workload credential family (v16 §3.3): only an enrolled workload
3483        // family carries `workload_session_id`. The disposition — deny, stamp,
3484        // or omit — is resolved by `resolve_renewal_workload_session` (pure over
3485        // the canonical session registry + the authoritative family policy),
3486        // which enforces the check-BEFORE-narrowing ordering: a revoked/expired
3487        // carried session denies regardless of whether the family policy would
3488        // otherwise narrow it away.
3489        let old_wsid = ctx
3490            .claims()
3491            .and_then(|c| c.workload_session_id.as_deref())
3492            .map(str::to_owned);
3493        let family_policy = enrollment_manifest
3494            .as_ref()
3495            .map(|m| m.workload_session_policy(svc_name));
3496        match self
3497            .resolve_renewal_workload_session(
3498                &issuer,
3499                &subject,
3500                &policy_domain,
3501                now,
3502                family_policy,
3503                old_wsid.as_deref(),
3504            )
3505            .await
3506        {
3507            RenewalWorkloadSession::Deny { code, message } => {
3508                return Ok(PolicyResponseVariant::Error(ErrorInfo {
3509                    message,
3510                    code: code.to_owned(),
3511                    details: String::new(),
3512                }));
3513            }
3514            RenewalWorkloadSession::Stamp(Some(wsid)) => {
3515                claims = claims.with_workload_session_id(wsid);
3516            }
3517            RenewalWorkloadSession::Stamp(None) => {}
3518        }
3519
3520        let token = match self.sign_token(&claims, true).await {
3521            Ok(t) => t,
3522            Err(e) => {
3523                return Ok(PolicyResponseVariant::Error(ErrorInfo {
3524                    message: "Failed to refresh service token".to_owned(),
3525                    code: "SIGNING_NOT_CONFIGURED".to_owned(),
3526                    details: e.to_string(),
3527                }));
3528            }
3529        };
3530
3531        // Persist renewed JWT to disk so it survives a server restart
3532        let credentials_dir = crate::auth::identity_store::credentials_dir()?;
3533        let secrets_profile = crate::auth::identity_store::SecretsProfile::from_env()?;
3534        if let Err(e) = crate::auth::identity_store::write_service_jwt_for_profile(
3535            &credentials_dir,
3536            svc_name,
3537            secrets_profile,
3538            &token,
3539        ) {
3540            warn!(
3541                service = svc_name,
3542                "Failed to persist renewed JWT to disk: {e}"
3543            );
3544        }
3545
3546        info!(service = svc_name, expires_at, "Renewed service JWT");
3547        Ok(PolicyResponseVariant::RefreshServiceTokenResult(
3548            TokenInfo { token, expires_at },
3549        ))
3550    }
3551    async fn handle_exchange_wit(
3552        &self,
3553        ctx: &EnvelopeContext,
3554        _request_id: u64,
3555        data: &ExchangeWit,
3556    ) -> Result<PolicyResponseVariant> {
3557        // Identity is read from the already-verified envelope WIT — no credential submission.
3558        let sub = match ctx.subject().name() {
3559            Some(s) => s.to_owned(),
3560            None => {
3561                return Ok(PolicyResponseVariant::Error(ErrorInfo {
3562                    message: "Anonymous callers cannot exchange WIT for access token".to_owned(),
3563                    code: "ANONYMOUS".to_owned(),
3564                    details: String::new(),
3565                }));
3566            }
3567        };
3568        let domain = ctx.domain()?;
3569
3570        // ExchangeWit signs directly rather than through `handle_issue_token`.
3571        // Keep its authenticated-envelope subject under the same account-DID
3572        // freeze before it can reach the direct signing boundary.
3573        if is_path_form_did_web(&sub) {
3574            return Ok(PolicyResponseVariant::Error(ErrorInfo {
3575                message: "path-form did:web account subjects are frozen; host-form account minting is not available yet (#1159)".to_owned(),
3576                code: "FROZEN_PATH_FORM_SUBJECT".to_owned(),
3577                details: String::new(),
3578            }));
3579        }
3580
3581        // cnf.jwk from the verified WIT — carried through into the issued at+jwt.
3582        let cnf_key_bytes = ctx
3583            .claims()
3584            .and_then(hyprstream_rpc::auth::Claims::cnf_key_bytes);
3585        if cnf_key_bytes.is_none() {
3586            return Ok(PolicyResponseVariant::Error(ErrorInfo {
3587                message: "Caller WIT missing cnf.jwk — key binding required for ExchangeWit"
3588                    .to_owned(),
3589                code: "NO_CNF_JWK".to_owned(),
3590                details: String::new(),
3591            }));
3592        }
3593
3594        // Casbin: caller must have 'exchange' on 'policy:exchange-wit'.
3595        let allowed = self
3596            .policy_manager
3597            .check_with_domain(&sub, &domain, "policy:exchange-wit", "exchange")
3598            .await;
3599        if !allowed {
3600            return Ok(PolicyResponseVariant::Error(ErrorInfo {
3601                message: format!(
3602                    "Subject '{sub}' is not authorized to exchange WIT for access token"
3603                ),
3604                code: "UNAUTHORIZED".to_owned(),
3605                details: "Requires 'exchange' permission on 'policy:exchange-wit'".to_owned(),
3606            }));
3607        }
3608
3609        let _ = data;
3610        // v16 disposition (frozen A): this path minted an `at+jwt` with NO
3611        // RFC 9068 `client_id`, NO authoritative interactive/non-interactive
3612        // session classification, and NO authoritative primary-suite
3613        // `cnf.hs_signer_suite` — a non-conformant v16 dispatch credential that
3614        // every current admission boundary (svc.rs client_id gate, C's §5
3615        // confirmation) would reject downstream. Rather than mint an invalid
3616        // shape and rely on a later reject, this dormant path now fails CLOSED:
3617        // a conformant user access token is minted only through the typed OAuth
3618        // issuance profiles (`handle_issue_token`), never a WIT→at+jwt bridge
3619        // that cannot supply an OAuth client identity. Retype through those
3620        // authoritative profiles if this bridge is ever revived.
3621        Ok(PolicyResponseVariant::Error(ErrorInfo {
3622            message: "WIT→at+jwt exchange cannot produce a v16-conformant access token \
3623                      (no OAuth client_id / session classification / authoritative \
3624                      signer-suite confirmation); use the typed OAuth issuance profiles"
3625                .to_owned(),
3626            code: "V16_PROFILE_UNAVAILABLE".to_owned(),
3627            details: String::new(),
3628        }))
3629    }
3630
3631    /// RFC 8693 §4 on-behalf-of delegated mint (v16 §8.1 `AsOriginator`).
3632    ///
3633    /// The authenticated RPC caller IS the terminal actor: actor subject, cnf,
3634    /// and tenant are derived from the verified policy envelope (never from a
3635    /// request field), and originator/scope/capability/session/clearance are
3636    /// derived from the authority-verified source credential. The authority
3637    /// mints a NEW delegated credential — fresh `jti`, originator `sub`, nested
3638    /// terminal `act`, terminal-actor `cnf`, fail-closed `meet(originator,
3639    /// terminal actor)` clearance (the source's own clearance is already the
3640    /// prior-hop meet), explicitly-attenuated scope AND capability, a
3641    /// manifest-bound audience, and conditional `sid`/`workload_session_id`
3642    /// retention — never a bearer relay. The source credential is reusable.
3643    async fn handle_exchange_delegated(
3644        &self,
3645        ctx: &EnvelopeContext,
3646        _request_id: u64,
3647        data: &ExchangeDelegated,
3648    ) -> Result<PolicyResponseVariant> {
3649        use hyprstream_rpc::auth::mac::{SecurityContext, SubjectContextClaims as _};
3650
3651        let deny = |code: &str, message: &str| {
3652            PolicyResponseVariant::Error(ErrorInfo {
3653                message: message.to_owned(),
3654                code: code.to_owned(),
3655                details: String::new(),
3656            })
3657        };
3658        // The effective enrollment manifest (injected override or process
3659        // global) — the authoritative source of the actor's signer suite,
3660        // outbound audience ceiling, and workload-family policy.
3661        let manifest = self.enrollment();
3662        let manifest = manifest.as_deref();
3663
3664        // ── 1. Terminal actor = the AUTHENTICATED RPC caller (never a field) ──
3665        let Some(actor_sub) = ctx.subject().name().map(str::to_owned) else {
3666            return Ok(deny(
3667                "ANONYMOUS",
3668                "delegated exchange requires an authenticated terminal actor",
3669            ));
3670        };
3671        // AsOriginator derived dispatch is service→service: only a service
3672        // identity holds standing authority to act on another principal's
3673        // behalf. A caller that cannot become a terminal actor is rejected.
3674        let Some(actor_svc) = actor_sub.strip_prefix("service:") else {
3675            return Ok(deny(
3676                "NOT_A_TERMINAL_ACTOR",
3677                "only a service identity can become a delegated terminal actor",
3678            ));
3679        };
3680        let actor_domain = ctx.domain()?;
3681        // The terminal actor's cnf = the verified Ed25519 key that signed THIS
3682        // request. Binding the new credential to it forces the downstream
3683        // envelope signer to equal the terminal actor (#680 confused-deputy).
3684        let actor_cnf = ctx.cnf;
3685        if actor_cnf == [0u8; 32] {
3686            return Ok(deny(
3687                "NO_TERMINAL_CNF",
3688                "terminal actor request carried no verified signing key",
3689            ));
3690        }
3691        // The terminal actor's OWN verified context: authority-asserted
3692        // clearance clamped to its verified crypto assurance. Never wire-supplied.
3693        let Some(actor_ctx) = ctx.security_context() else {
3694            return Ok(deny(
3695                "UNLABELED_ACTOR",
3696                "terminal actor has no resolvable clearance",
3697            ));
3698        };
3699
3700        // ── 2. This authority's configured issuer is the trust anchor for the
3701        // source credential (key possession alone is not issuer trust). It is
3702        // resolved BEFORE verification so the classical key lookup is keyed by
3703        // the trusted issuer; the requested `aud` is a separate validated
3704        // target and never sets `iss`. ──
3705        let expected_issuer = match self.default_audience.as_deref() {
3706            Some(i) if !i.is_empty() => i.to_owned(),
3707            _ => {
3708                return Ok(deny(
3709                    "ISSUER_NOT_CONFIGURED",
3710                    "delegated exchange requires a configured authorization-server issuer",
3711                ))
3712            }
3713        };
3714
3715        // ── 3. Verify the presented source credential (originator authority) ──
3716        let VerifiedSourceCredential {
3717            claims: source,
3718            profile,
3719            key_material: source_key_material,
3720        } = match verify_presented_credential(
3721            &data.source_credential,
3722            self.jwt_key_source.as_deref(),
3723            &expected_issuer,
3724        )
3725        .await
3726        {
3727            Ok(c) => c,
3728            Err(e) => {
3729                return Ok(deny(
3730                    "INVALID_SOURCE",
3731                    &format!("source credential rejected: {e}"),
3732                ))
3733            }
3734        };
3735        let now = chrono::Utc::now().timestamp();
3736        if source.exp <= now {
3737            return Ok(deny("SOURCE_EXPIRED", "source credential has expired"));
3738        }
3739        // Issuer-claim exact-equality (again) after decode: the verified `iss`
3740        // MUST equal the trusted issuer the keys were resolved under.
3741        if source.iss != expected_issuer {
3742            return Ok(deny(
3743                "UNTRUSTED_ISSUER",
3744                "source credential issuer is not this authority's trusted issuer",
3745            ));
3746        }
3747        let originator = source.sub.clone();
3748        if originator.is_empty() {
3749            return Ok(deny("INVALID_SOURCE", "source credential has no subject"));
3750        }
3751        if is_path_form_did_web(&originator) {
3752            return Ok(deny(
3753                "FROZEN_PATH_FORM_SUBJECT",
3754                "path-form did:web account subjects are frozen (#1159)",
3755            ));
3756        }
3757        // Profile ↔ subject coherence: at+jwt is a user credential, wit+jwt a
3758        // service one. A typ that disagrees with the subject spelling is rejected.
3759        let originator_is_service = originator.starts_with("service:");
3760        match profile {
3761            SourceProfile::AtJwt if originator_is_service => {
3762                return Ok(deny(
3763                    "PROFILE_MISMATCH",
3764                    "at+jwt source credential carries a service subject",
3765                ))
3766            }
3767            SourceProfile::WitJwt if !originator_is_service => {
3768                return Ok(deny(
3769                    "PROFILE_MISMATCH",
3770                    "wit+jwt source credential carries a non-service subject",
3771                ))
3772            }
3773            _ => {}
3774        }
3775
3776        // Frozen-A profile coherence on the SOURCE (rejected before mint):
3777        //  - a user `at+jwt` MUST carry a non-empty client_id AND a non-empty
3778        //    OIDC `sid`, and MUST NOT carry a `workload_session_id`;
3779        //  - a service `wit+jwt` MUST NOT carry `sid` or `client_id`; a
3780        //    `workload_session_id` is permitted ONLY for a service the
3781        //    enrollment manifest marks as an authoritative workload family.
3782        let source_client_id = source
3783            .client_id
3784            .as_deref()
3785            .map(str::trim)
3786            .filter(|s| !s.is_empty());
3787        let source_sid = source.sid.as_deref().filter(|s| !s.is_empty());
3788        let source_wsid = source
3789            .workload_session_id
3790            .as_deref()
3791            .filter(|s| !s.is_empty());
3792        match profile {
3793            SourceProfile::AtJwt => {
3794                // Malformations of a user at+jwt (frozen A): client_id is always
3795                // required; a user credential never carries a workload id.
3796                if source_client_id.is_none() {
3797                    return Ok(deny(
3798                        "MALFORMED_SOURCE_PROFILE",
3799                        "user at+jwt source requires a non-empty client_id",
3800                    ));
3801                }
3802                if source_wsid.is_some() {
3803                    return Ok(deny(
3804                        "MALFORMED_SOURCE_PROFILE",
3805                        "user at+jwt source must not carry a workload_session_id",
3806                    ));
3807                }
3808                // JOSE typ alone cannot distinguish an interactive session
3809                // at+jwt (sid REQUIRED) from a separately-typed non-interactive
3810                // RFC 8693/7523 at+jwt (sid ABSENT), and the credential carries
3811                // no off-wire discriminator for that split. Rather than guess or
3812                // invent a claim, the supported unambiguous delegation-source
3813                // subset is the interactive session credential: an at+jwt source
3814                // MUST present a non-empty OIDC sid (validated active below). A
3815                // sid-less at+jwt is a valid credential but an UNSUPPORTED
3816                // delegation source here (fail closed), not a malformed one.
3817                if source_sid.is_none() {
3818                    return Ok(deny(
3819                        "UNSUPPORTED_SOURCE",
3820                        "a delegatable at+jwt source must be an interactive session credential (active sid); a non-interactive/sid-less at+jwt is not a supported delegation source",
3821                    ));
3822                }
3823            }
3824            SourceProfile::WitJwt => {
3825                if source_sid.is_some() {
3826                    return Ok(deny(
3827                        "MALFORMED_SOURCE_PROFILE",
3828                        "service wit+jwt source must not carry an OIDC sid",
3829                    ));
3830                }
3831                if source_client_id.is_some() {
3832                    return Ok(deny(
3833                        "MALFORMED_SOURCE_PROFILE",
3834                        "service wit+jwt source must not carry a client_id",
3835                    ));
3836                }
3837                if source_wsid.is_some() {
3838                    let svc = &originator["service:".len()..];
3839                    let enrolled_family = manifest
3840                        .map(|m| m.workload_session_policy(svc))
3841                        .unwrap_or(false);
3842                    if !enrolled_family {
3843                        return Ok(deny(
3844                            "MALFORMED_SOURCE_PROFILE",
3845                            "service source carries a workload_session_id but is not an enrolled workload family",
3846                        ));
3847                    }
3848                }
3849            }
3850        }
3851
3852        // The source MUST be a v16 credential: its `cnf.hs_signer_suite` present
3853        // and equal to its own subject's authoritative signer suite. Signature
3854        // verification alone does not check the confirmation claim.
3855        if let Err(e) = validate_credential_hs_suite(
3856            manifest,
3857            self.primary_enrollment_resolver.as_deref(),
3858            &source,
3859        ) {
3860            return Ok(deny(
3861                "INVALID_SOURCE_CNF",
3862                &format!("source credential confirmation rejected: {e}"),
3863            ));
3864        }
3865
3866        // Issuer-scoped source credentials must be revocable and not revoked.
3867        let Some(jti) = source.jti.as_deref().filter(|s| !s.is_empty()) else {
3868            return Ok(deny(
3869                "SOURCE_NOT_REVOCABLE",
3870                "source credential carries no jti (not revocable)",
3871            ));
3872        };
3873        let id = hyprstream_rpc::auth::CredentialId::jwt(expected_issuer.clone(), jti.to_owned());
3874        let revoked = match hyprstream_rpc::auth::global_credential_revocation_store() {
3875            Some(store) => store.is_revoked(&id).await,
3876            None => true, // fail closed: liveness cannot be proven
3877        };
3878        if revoked {
3879            return Ok(deny(
3880                "SOURCE_REVOKED",
3881                "source credential is revoked or its liveness cannot be proven",
3882            ));
3883        }
3884
3885        // ── 4. Coherence: originator and terminal actor MUST share a tenant ──
3886        // Tenant comes from the verified envelope (the actor's); the source's
3887        // tenant must equal it — no cross-tenant delegation.
3888        match source.tenant.as_deref() {
3889            Some(t) if t == actor_domain => {}
3890            _ => {
3891                return Ok(deny(
3892                    "TENANT_MISMATCH",
3893                    "source credential tenant does not match the terminal actor's verified tenant",
3894                ))
3895            }
3896        }
3897
3898        // ── 5. Existing delegation chain must be bounded and fully labeled ──
3899        // Reserve one hop for the terminal actor appended by this exchange.
3900        // Every existing actor must be labeled; step 6 folds their clearances.
3901        const MAX_DELEGATION_HOPS: usize = 8;
3902        {
3903            let mut hop = source.act.as_ref();
3904            let mut depth = 0usize;
3905            while let Some(actor) = hop {
3906                if actor.clearance.is_none() {
3907                    return Ok(deny(
3908                        "MALFORMED_ACTOR_CHAIN",
3909                        "an actor in the source delegation chain carries no clearance",
3910                    ));
3911                }
3912                depth += 1;
3913                if depth >= MAX_DELEGATION_HOPS {
3914                    return Ok(deny(
3915                        "MALFORMED_ACTOR_CHAIN",
3916                        "delegation chain has no room for the terminal actor",
3917                    ));
3918                }
3919                hop = actor.act.as_deref();
3920            }
3921        }
3922
3923        // ── 6. Clearance = fail-closed meet(originator, EVERY intermediate
3924        // actor, terminal actor). We do NOT assume the source's top-level
3925        // clearance already folds its prior act-chain hops — that induction is
3926        // unsafe for a foreign/older accepted source — so every intermediate
3927        // `act.clearance` is folded in explicitly (the meet only ever lowers the
3928        // level and shrinks compartments, so folding is always safe). The
3929        // originator's assurance is the ACTUAL verified source algorithm; the
3930        // effective assurance is the terminal signer's (the final fold). ──
3931        let Some(mut met) = source.security_context(source_key_material) else {
3932            return Ok(deny(
3933                "UNLABELED_ORIGINATOR",
3934                "source credential has no resolvable clearance",
3935            ));
3936        };
3937        {
3938            let mut hop = source.act.as_ref();
3939            while let Some(actor) = hop {
3940                let Some(cc) = actor.clearance else {
3941                    // Already rejected by the well-formedness walk above, but
3942                    // fail closed here too rather than silently skipping a hop.
3943                    return Ok(deny(
3944                        "UNLABELED_ORIGINATOR",
3945                        "a source delegation-chain actor is unlabeled",
3946                    ));
3947                };
3948                // Assurance here is transient (overwritten by the terminal fold);
3949                // only the level/compartments of this hop enter the meet.
3950                let hop_ctx = SecurityContext::new(
3951                    cc.level,
3952                    cc.compartments,
3953                    hyprstream_rpc::auth::mac::VerifiedKeyMaterial::Classical,
3954                );
3955                met = SecurityContext::delegated_meet(&met, &hop_ctx);
3956                hop = actor.act.as_deref();
3957            }
3958        }
3959        // Terminal actor folds last, so the effective assurance is its verified
3960        // signer's crypto floor.
3961        let met = SecurityContext::delegated_meet(&met, &actor_ctx);
3962
3963        // ── 7. Explicit attenuation of BOTH authority axes (v16 §8.1) ──
3964        let granted_scope = match attenuate_delegated_scope(
3965            source.scope.as_deref(),
3966            data.requested_scopes.as_deref(),
3967        ) {
3968            Ok(s) => s,
3969            Err(msg) => return Ok(deny("SCOPE_ATTENUATION", &msg)),
3970        };
3971        let granted_cap = match attenuate_delegated_capabilities(
3972            source.cap.as_deref(),
3973            data.requested_capabilities.as_deref(),
3974        ) {
3975            Ok(c) => c,
3976            Err(msg) => return Ok(deny("CAPABILITY_ATTENUATION", &msg)),
3977        };
3978
3979        // ── 8. Audience: REQUIRED, non-empty, and bound to the reviewed
3980        // derived-call contract — the terminal actor's enrollment-manifest
3981        // allowed audiences, or (no manifest) the source credential's own
3982        // audience. Never an arbitrary string; never defaulted to the issuer. ──
3983        let Some(audience) = data
3984            .audience
3985            .as_deref()
3986            .map(str::trim)
3987            .filter(|s| !s.is_empty())
3988        else {
3989            return Ok(deny(
3990                "AUDIENCE_REQUIRED",
3991                "delegated exchange requires an explicit non-empty audience",
3992            ));
3993        };
3994        // Outbound target ceiling (manifest `allowed_audiences`) — a DISTINCT
3995        // control from the edge authority: it bounds what a service may mint
3996        // for, never proof that the source named this actor. Kept as
3997        // defense-in-depth for an enrolled actor.
3998        if let Some(m) = manifest {
3999            if !m.allows_audience(actor_svc, Some(audience)) {
4000                return Ok(deny(
4001                    "AUDIENCE_NOT_ENROLLED",
4002                    "requested audience exceeds the terminal actor's outbound audience ceiling",
4003                ));
4004            }
4005        }
4006        // The derived-call target method is REQUIRED and non-empty: the
4007        // authorizer enforces the exact reviewed DispatchCallManifest method
4008        // edge, and no authorizer may treat an absent method as a wildcard.
4009        let Some(target_method_id) = data
4010            .target_method_id
4011            .as_deref()
4012            .map(str::trim)
4013            .filter(|s| !s.is_empty())
4014        else {
4015            return Ok(deny(
4016                "TARGET_METHOD_REQUIRED",
4017                "delegated exchange requires a non-empty target method id",
4018            ));
4019        };
4020        // Authoritative confused-deputy control: an edge authorizer must prove
4021        // BOTH that the source credential was valid FOR this terminal actor
4022        // (source `aud` ↔ actor) AND that the requested (target audience, target
4023        // method) is a declared call edge. An UNINSTALLED authorizer denies — a
4024        // generic manage-scoped service credential is never, by itself, the
4025        // delegation control.
4026        let Some(authorizer) = self.delegation_edge_authorizer.as_deref() else {
4027            return Ok(deny(
4028                "EDGE_AUTHORIZER_UNAVAILABLE",
4029                "delegation-edge authorizer is not installed; derived dispatch denied",
4030            ));
4031        };
4032        let edge = DelegationEdge {
4033            actor_service: actor_svc,
4034            actor_tenant: &actor_domain,
4035            source_audience: source.aud.as_deref(),
4036            originator: &originator,
4037            target_audience: audience,
4038            target_method_id: Some(target_method_id),
4039        };
4040        if !authorizer.authorize(&edge) {
4041            return Ok(deny(
4042                "EDGE_DENIED",
4043                "the delegation edge is not an authorized derived call (source audience / actor / target / method)",
4044            ));
4045        }
4046
4047        // ── 9. Lifetime: never outlives the source, the terminal actor's
4048        // authority, a retained session, or the configured issuance maximum ──
4049        let mut expires_at = source.exp;
4050        if let Some(actor_claims) = ctx.claims() {
4051            expires_at = expires_at.min(actor_claims.exp);
4052        }
4053        let ttl_override = data
4054            .ttl
4055            .map(i64::from)
4056            .unwrap_or(self.token_config.default_ttl_seconds as i64);
4057        expires_at = expires_at.min(now + ttl_override);
4058        expires_at = expires_at.min(now + self.token_config.max_ttl_seconds as i64);
4059
4060        // ── 10. Session retention. A source's OIDC `sid` and workload
4061        // `workload_session_id` are DISJOINT namespaces (never cross-mapped);
4062        // each, when present, must be ACTIVE and exact before the mint, else the
4063        // whole exchange denies. A credential carrying both is malformed. ──
4064        if source.sid.is_some() && source.workload_session_id.is_some() {
4065            return Ok(deny(
4066                "MALFORMED_SESSION",
4067                "source credential carries both an OIDC sid and a workload session id",
4068            ));
4069        }
4070        let mut retained_sid: Option<String> = None;
4071        let mut retained_wsid: Option<String> = None;
4072        if let Some(sid) = source.sid.as_deref().filter(|s| !s.is_empty()) {
4073            let Some(registry) = hyprstream_rpc::auth::global_session_registry() else {
4074                return Ok(deny("UNAVAILABLE", "session registry is not initialized"));
4075            };
4076            let key = hyprstream_rpc::auth::SessionKey::oidc(&expected_issuer, sid);
4077            let state = registry.session_state(&key).await;
4078            let bindable = matches!(&state, Some(s)
4079                if s.status == hyprstream_rpc::auth::ActiveOrRevoked::Active
4080                    && s.expires_at > now
4081                    && s.subject == originator
4082                    && s.tenant == actor_domain);
4083            if !bindable {
4084                return Ok(deny(
4085                    "SESSION_INVALID",
4086                    "source OIDC session is revoked, expired, unknown, or mismatched",
4087                ));
4088            }
4089            if let Some(s) = state {
4090                expires_at = expires_at.min(s.expires_at);
4091            }
4092            retained_sid = Some(sid.to_owned());
4093        }
4094        if let Some(wsid) = source
4095            .workload_session_id
4096            .as_deref()
4097            .filter(|s| !s.is_empty())
4098        {
4099            let Some(registry) = hyprstream_rpc::auth::global_session_registry() else {
4100                return Ok(deny("UNAVAILABLE", "session registry is not initialized"));
4101            };
4102            let key = hyprstream_rpc::auth::SessionKey::workload(&expected_issuer, wsid);
4103            let state = registry.session_state(&key).await;
4104            let bindable = matches!(&state, Some(s)
4105                if s.status == hyprstream_rpc::auth::ActiveOrRevoked::Active
4106                    && s.expires_at > now
4107                    && s.subject == originator
4108                    && s.tenant == actor_domain);
4109            if !bindable {
4110                return Ok(deny(
4111                    "SESSION_INVALID",
4112                    "source workload session is revoked, expired, unknown, or mismatched",
4113                ));
4114            }
4115            if let Some(s) = state {
4116                expires_at = expires_at.min(s.expires_at);
4117            }
4118            retained_wsid = Some(wsid.to_owned());
4119        }
4120
4121        // The derived credential must retain a usable lifetime after every clamp.
4122        const MIN_TTL_SECONDS: i64 = 60;
4123        if expires_at - now < MIN_TTL_SECONDS {
4124            return Ok(deny(
4125                "SOURCE_TOO_SHORT",
4126                "source/actor/session lifetime leaves no usable delegated TTL",
4127            ));
4128        }
4129
4130        // ── 11. RFC 9068 client_id provenance. A user-originator delegated
4131        // credential is an `at+jwt` and inherits the originator's OAuth
4132        // client_id (validated present by the profile-coherence gate above); a
4133        // service-originator mints a `wit+jwt` and carries NO client_id (a
4134        // service source's client_id was already rejected). Never stamp a
4135        // client_id onto a service output. ──
4136        let client_id = if originator_is_service {
4137            None
4138        } else {
4139            source_client_id
4140        };
4141
4142        // ── 12. Resolve the TERMINAL ACTOR's authoritative v16 signer suite from
4143        // its enrollment (classical or hybrid by exact enrolled key material),
4144        // key-bound to the verified envelope signer. The delegated credential's
4145        // `cnf` binds the terminal actor (it signs the downstream envelope), so
4146        // its confirmation is the actor's suite — a bare Ed25519 `cnf.jwk`
4147        // cannot represent a hybrid actor. Fail closed if unresolvable. ──
4148        let actor_suite = match enrolled_service_signer_suite(manifest, actor_svc, &actor_cnf) {
4149            Ok(s) => s,
4150            Err(e) => {
4151                return Ok(deny(
4152                    "ACTOR_SUITE_UNRESOLVABLE",
4153                    &format!("terminal actor v16 signer suite could not be resolved: {e}"),
4154                ))
4155            }
4156        };
4157
4158        // ── 13. Build and sign the fresh delegated credential ──
4159        let met_label = *met.clearance();
4160        let terminal_actor = hyprstream_rpc::auth::ActClaim {
4161            sub: actor_sub.clone(),
4162            clearance: Some(hyprstream_rpc::auth::mac::CredentialClearance::from_label(
4163                *actor_ctx.clearance(),
4164            )),
4165            // Nest the source's existing delegation chain beneath the new
4166            // terminal actor (RFC 8693 §4.1 outermost-is-current ordering).
4167            act: source.act.clone().map(Box::new),
4168        };
4169        let mut claims = hyprstream_rpc::auth::Claims::new(originator.clone(), now, expires_at)
4170            .with_issuer(expected_issuer)
4171            .with_tenant(actor_domain)
4172            .with_audience(Some(audience.to_owned()))
4173            .with_scope(granted_scope)
4174            // Stamp the already-met clearance so even a reader that ignores the
4175            // `act` chain sees the lowest (meet) authority; a downstream
4176            // delegated_meet re-take is idempotent (meet ≤ every input).
4177            .with_clearance(met_label)
4178            .with_act(terminal_actor)
4179            // v16 confirmation = the terminal actor's authoritative signer suite;
4180            // the legacy `cnf.jwk` (actor Ed key) is preserved alongside it.
4181            .with_cnf_jwk(&actor_cnf)
4182            .with_cnf_hs_signer_suite(actor_suite);
4183        if let Some(cap) = granted_cap {
4184            claims = claims.with_cap(cap);
4185        }
4186        if let Some(cid) = client_id {
4187            claims = claims.with_client_id(cid);
4188        }
4189        if let Some(sid) = retained_sid {
4190            claims = claims.with_sid(sid);
4191        }
4192        if let Some(wsid) = retained_wsid {
4193            claims = claims.with_workload_session_id(wsid);
4194        }
4195
4196        // `sign_token` injects a fresh `jti` (the encoder mints one when absent),
4197        // so the delegated credential's id is always distinct from the source.
4198        let token = match self.sign_token(&claims, originator_is_service).await {
4199            Ok(t) => t,
4200            Err(e) => {
4201                return Ok(deny(
4202                    "SIGNING_NOT_CONFIGURED",
4203                    &format!("failed to mint delegated credential: {e}"),
4204                ))
4205            }
4206        };
4207
4208        info!(
4209            originator = %originator,
4210            actor = %actor_sub,
4211            expires_at = claims.exp,
4212            "ExchangeDelegated: minted delegated credential"
4213        );
4214        Ok(PolicyResponseVariant::ExchangeDelegatedResult(TokenInfo {
4215            token,
4216            expires_at: claims.exp,
4217        }))
4218    }
4219
4220    /// Publish a credential revocation into the canonical store this service
4221    /// owns. Fail-closed: an uninitialized store or a failed durable write is
4222    /// reported as an error, never as a silent success.
4223    async fn handle_revoke_credential(
4224        &self,
4225        _ctx: &EnvelopeContext,
4226        _request_id: u64,
4227        data: &RevokeCredential,
4228    ) -> Result<PolicyResponseVariant> {
4229        let Some(id) = crate::services::revocation::credential_id_from_ref(&data.credential) else {
4230            return Ok(PolicyResponseVariant::Error(ErrorInfo {
4231                message: "malformed credential id (empty issuer or value)".to_owned(),
4232                code: "INVALID_ARGUMENT".to_owned(),
4233                details: String::new(),
4234            }));
4235        };
4236        // Server-side publication bounds. The retention horizon is derived
4237        // from the configured issuance maxima at construction (default 45
4238        // days covers the hard 30-day service-JWT clamp with margin), so no
4239        // issuable credential can outlive its revocability. A
4240        // caller-controlled far-future exp would otherwise make an entry
4241        // effectively permanent (never GC'd, never dropped on load), and
4242        // unbounded issuer/value sizes would fill the authority's durable
4243        // log. Reject, never clamp: a clamped exp would silently un-revoke a
4244        // still-live token after reload.
4245        const MAX_ID_FIELD_BYTES: usize = 1024;
4246        let now = chrono::Utc::now().timestamp();
4247        if data.expires_at <= 0 || data.expires_at > now + self.revocation_max_ttl_secs {
4248            return Ok(PolicyResponseVariant::Error(ErrorInfo {
4249                message: format!(
4250                    "expires_at out of bounds (must be 0 < exp <= now + {}s)",
4251                    self.revocation_max_ttl_secs
4252                ),
4253                code: "INVALID_ARGUMENT".to_owned(),
4254                details: String::new(),
4255            }));
4256        }
4257        let value_len = match &id.value {
4258            hyprstream_rpc::auth::CredentialValue::Jwt(jti) => jti.len(),
4259            hyprstream_rpc::auth::CredentialValue::Cwt(cti) => cti.len(),
4260        };
4261        if id.issuer.len() > MAX_ID_FIELD_BYTES || value_len > MAX_ID_FIELD_BYTES {
4262            return Ok(PolicyResponseVariant::Error(ErrorInfo {
4263                message: "credential id field exceeds 1024 bytes".to_owned(),
4264                code: "INVALID_ARGUMENT".to_owned(),
4265                details: String::new(),
4266            }));
4267        }
4268        let Some(store) = hyprstream_rpc::auth::global_credential_revocation_store() else {
4269            return Ok(PolicyResponseVariant::Error(ErrorInfo {
4270                message: "revocation authority store is not initialized".to_owned(),
4271                code: "UNAVAILABLE".to_owned(),
4272                details: String::new(),
4273            }));
4274        };
4275        if let Err(e) = store.revoke_credential(id.clone(), data.expires_at).await {
4276            return Ok(PolicyResponseVariant::Error(ErrorInfo {
4277                message: "revocation publication was not durably accepted".to_owned(),
4278                code: "UNAVAILABLE".to_owned(),
4279                details: e.to_string(),
4280            }));
4281        }
4282        info!(credential = %id, "Credential revocation published");
4283        Ok(PolicyResponseVariant::RevokeCredentialResult)
4284    }
4285
4286    /// Answer a revocation check from the canonical store. Fail-closed twice
4287    /// over: a malformed credential ID reports revoked, and an uninitialized
4288    /// store reports revoked — a credential whose status cannot be checked is
4289    /// never reported live.
4290    async fn handle_check_credential_revocation(
4291        &self,
4292        _ctx: &EnvelopeContext,
4293        _request_id: u64,
4294        data: &CheckCredentialRevocation,
4295    ) -> Result<PolicyResponseVariant> {
4296        let revoked = match crate::services::revocation::credential_id_from_ref(&data.credential) {
4297            Some(id) => match hyprstream_rpc::auth::global_credential_revocation_store() {
4298                Some(store) => store.is_revoked(&id).await,
4299                None => true,
4300            },
4301            None => true,
4302        };
4303        Ok(PolicyResponseVariant::CheckCredentialRevocationResult(
4304            revoked,
4305        ))
4306    }
4307
4308    /// Register a session with the canonical registry this service owns.
4309    /// Fail-closed: a malformed record, an out-of-horizon expiry, an
4310    /// uninitialized registry, or a failed durable write is an error, never
4311    /// a silent success. Issuance callers own the session lifecycle; the
4312    /// registry never mints session IDs.
4313    async fn handle_register_session(
4314        &self,
4315        _ctx: &EnvelopeContext,
4316        _request_id: u64,
4317        data: &RegisterSession,
4318    ) -> Result<PolicyResponseVariant> {
4319        const MAX_FIELD_BYTES: usize = 1024;
4320        let invalid = |message: &str| {
4321            Ok(PolicyResponseVariant::Error(ErrorInfo {
4322                message: message.to_owned(),
4323                code: "INVALID_ARGUMENT".to_owned(),
4324                details: String::new(),
4325            }))
4326        };
4327        let Some(key) = crate::services::revocation::session_key_from_ref(&data.session) else {
4328            return invalid("malformed session key (empty issuer or identifier)");
4329        };
4330        let now = chrono::Utc::now().timestamp();
4331        if data.subject.is_empty()
4332            || data.tenant.is_empty()
4333            || data.subject.len() > MAX_FIELD_BYTES
4334            || data.tenant.len() > MAX_FIELD_BYTES
4335        {
4336            return invalid("session subject/tenant empty or over 1024 bytes");
4337        }
4338        if data.expires_at <= 0 || data.expires_at > now + self.revocation_max_ttl_secs {
4339            return Ok(PolicyResponseVariant::Error(ErrorInfo {
4340                message: format!(
4341                    "expires_at out of bounds (must be 0 < exp <= now + {}s)",
4342                    self.revocation_max_ttl_secs
4343                ),
4344                code: "INVALID_ARGUMENT".to_owned(),
4345                details: String::new(),
4346            }));
4347        }
4348        let Some(registry) = hyprstream_rpc::auth::global_session_registry() else {
4349            return Ok(PolicyResponseVariant::Error(ErrorInfo {
4350                message: "session registry is not initialized".to_owned(),
4351                code: "UNAVAILABLE".to_owned(),
4352                details: String::new(),
4353            }));
4354        };
4355        let kind = match &key.id {
4356            hyprstream_rpc::auth::SessionIdentifier::OidcSid(_) => {
4357                hyprstream_rpc::auth::SessionKind::Interactive
4358            }
4359            hyprstream_rpc::auth::SessionIdentifier::WorkloadSessionId(_) => {
4360                hyprstream_rpc::auth::SessionKind::Workload
4361            }
4362        };
4363        let state = hyprstream_rpc::auth::SessionState {
4364            subject: data.subject.clone(),
4365            tenant: data.tenant.clone(),
4366            kind,
4367            created_at: now,
4368            expires_at: data.expires_at,
4369            status: hyprstream_rpc::auth::ActiveOrRevoked::Active,
4370            clearance_epoch: data.clearance_epoch,
4371        };
4372        match registry.register_session(key, state).await {
4373            Ok(()) => Ok(PolicyResponseVariant::RegisterSessionResult),
4374            Err(e) => {
4375                let code = match &e {
4376                    hyprstream_rpc::auth::SessionRegisterError::Exists(_) => "ALREADY_EXISTS",
4377                    hyprstream_rpc::auth::SessionRegisterError::PublicationFailed(_) => {
4378                        "UNAVAILABLE"
4379                    }
4380                    _ => "INVALID_ARGUMENT",
4381                };
4382                Ok(PolicyResponseVariant::Error(ErrorInfo {
4383                    message: e.to_string(),
4384                    code: code.to_owned(),
4385                    details: String::new(),
4386                }))
4387            }
4388        }
4389    }
4390
4391    /// Revoke a session: every credential carrying it is then rejected.
4392    /// Fail-closed: an uninitialized registry or a failed durable write is an
4393    /// error, never a silent success.
4394    async fn handle_revoke_session(
4395        &self,
4396        _ctx: &EnvelopeContext,
4397        _request_id: u64,
4398        data: &RevokeSession,
4399    ) -> Result<PolicyResponseVariant> {
4400        let Some(key) = crate::services::revocation::session_key_from_ref(&data.session) else {
4401            return Ok(PolicyResponseVariant::Error(ErrorInfo {
4402                message: "malformed session key (empty issuer or identifier)".to_owned(),
4403                code: "INVALID_ARGUMENT".to_owned(),
4404                details: String::new(),
4405            }));
4406        };
4407        let Some(registry) = hyprstream_rpc::auth::global_session_registry() else {
4408            return Ok(PolicyResponseVariant::Error(ErrorInfo {
4409                message: "session registry is not initialized".to_owned(),
4410                code: "UNAVAILABLE".to_owned(),
4411                details: String::new(),
4412            }));
4413        };
4414        if let Err(e) = registry.revoke_session(&key).await {
4415            return Ok(PolicyResponseVariant::Error(ErrorInfo {
4416                message: "session revocation was not durably accepted".to_owned(),
4417                code: "UNAVAILABLE".to_owned(),
4418                details: e.to_string(),
4419            }));
4420        }
4421        Ok(PolicyResponseVariant::RevokeSessionResult)
4422    }
4423
4424    /// Answer a session check from the canonical registry. True means ACTIVE
4425    /// and known; revoked, expired, unknown, malformed, or an uninitialized
4426    /// registry all read false — a session whose state cannot be checked is
4427    /// never reported active.
4428    async fn handle_check_session(
4429        &self,
4430        _ctx: &EnvelopeContext,
4431        _request_id: u64,
4432        data: &CheckSession,
4433    ) -> Result<PolicyResponseVariant> {
4434        let active = match crate::services::revocation::session_key_from_ref(&data.session) {
4435            Some(key) => match hyprstream_rpc::auth::global_session_registry() {
4436                Some(registry) => !registry.is_revoked(&key).await,
4437                None => false,
4438            },
4439            None => false,
4440        };
4441        Ok(PolicyResponseVariant::CheckSessionResult(active))
4442    }
4443}
4444
4445#[async_trait(?Send)]
4446impl RequestService for PolicyService {
4447    fn decode_request_body(
4448        &self,
4449        signed_body: &[u8],
4450    ) -> anyhow::Result<hyprstream_rpc::service::DecodedRequestBody> {
4451        // The ONE bounded decode (v16 §5.2): the generated decoder derives
4452        // the full method leaf and returns the decoded message that policy,
4453        // MAC, and dispatch below all consume.
4454        crate::services::generated::policy_client::decode_policy_request_body(signed_body)
4455    }
4456
4457    async fn handle_request(
4458        &self,
4459        ctx: &EnvelopeContext,
4460        body: &hyprstream_rpc::service::DecodedRequestBody,
4461    ) -> Result<(Vec<u8>, Option<crate::services::Continuation>)> {
4462        trace!(
4463            "Policy request from {} (id={})",
4464            ctx.subject(),
4465            ctx.request_id
4466        );
4467        dispatch_policy(self, ctx, body).await
4468    }
4469
4470    fn name(&self) -> &str {
4471        "policy"
4472    }
4473
4474    fn transport(&self) -> &TransportConfig {
4475        &self.transport
4476    }
4477
4478    fn signing_key(&self) -> SigningKey {
4479        (*self.signing_key).clone()
4480    }
4481
4482    fn expected_audience(&self) -> Option<&str> {
4483        self.default_audience.as_deref()
4484    }
4485
4486    fn delegated_user_audience(
4487        &self,
4488        signer_pubkey: &[u8; 32],
4489        untrusted_aud: Option<&str>,
4490    ) -> Option<&str> {
4491        let Some((mcp, oai)) = self.delegated_resource_audiences.as_ref() else {
4492            return self.expected_audience();
4493        };
4494        let Ok(key) = ed25519_dalek::VerifyingKey::from_bytes(signer_pubkey) else {
4495            return self.expected_audience();
4496        };
4497        let trust = hyprstream_service::global_trust_store();
4498        if untrusted_aud == Some(mcp.as_str())
4499            && (trust.is_authorized(&key, "mcp") || trust.is_authorized(&key, "model"))
4500        {
4501            return Some(mcp);
4502        }
4503        if untrusted_aud == Some(oai.as_str())
4504            && (trust.is_authorized(&key, "oai") || trust.is_authorized(&key, "model"))
4505        {
4506            return Some(oai);
4507        }
4508        self.expected_audience()
4509    }
4510
4511    fn accept_delegated_resource_leaf(
4512        &self,
4513        ctx: &EnvelopeContext,
4514        body: &hyprstream_rpc::service::DecodedRequestBody,
4515    ) -> bool {
4516        ctx.is_delegated_bearer()
4517            && ctx.has_delegated_resource_audience()
4518            && body.leaf_path() == Some(&[0u16][..])
4519    }
4520
4521    fn jwt_key_source(&self) -> Option<std::sync::Arc<dyn hyprstream_rpc::auth::JwtKeySource>> {
4522        self.jwt_key_source.clone()
4523    }
4524
4525    fn resolve_key_subject(
4526        &self,
4527        signer_pubkey: &[u8; 32],
4528    ) -> Option<hyprstream_rpc::envelope::Subject> {
4529        hyprstream_service::global_trust_store().resolve_subject(signer_pubkey)
4530    }
4531
4532    // credential_revocation_store() uses the default trait impl, which
4533    // returns the process-global store. No override needed.
4534
4535    fn cache_key_binding(
4536        &self,
4537        verifying_key: ed25519_dalek::VerifyingKey,
4538        subject: &str,
4539        jwt: &str,
4540        expires_at: i64,
4541    ) {
4542        hyprstream_service::global_trust_store().insert(
4543            verifying_key,
4544            hyprstream_service::Attestation {
4545                scopes: std::collections::HashSet::new(),
4546                subject: Some(subject.to_owned()),
4547                jwt: Some(jwt.to_owned()),
4548                expires_at,
4549                attested_by: Some(self.signing_key.verifying_key().to_bytes()),
4550            },
4551        );
4552    }
4553
4554    fn accept_delegated_bearer(&self, signer_pubkey: &[u8; 32]) -> bool {
4555        let Some(actor) = hyprstream_service::global_trust_store().resolve_subject(signer_pubkey)
4556        else {
4557            return false;
4558        };
4559        let Some(actor_name) = actor.name() else {
4560            return false;
4561        };
4562        if actor.is_federated() || !actor_name.starts_with("service:") {
4563            return false;
4564        }
4565
4566        policy_templates::SERVICE_BASE_POLICIES.iter().any(|rule| {
4567            (rule.subject == actor_name || rule.subject == "service:*")
4568                && rule.domain == "*"
4569                && matches!(rule.resource, "policy:*" | "policy:PolicyCheck")
4570                && matches!(rule.action, "*" | "check")
4571                && rule.effect == "allow"
4572        })
4573    }
4574
4575    fn build_error_payload(&self, request_id: u64, error: &str) -> Vec<u8> {
4576        let variant = PolicyResponseVariant::Error(ErrorInfo {
4577            message: error.to_owned(),
4578            code: "INTERNAL".to_owned(),
4579            details: String::new(),
4580        });
4581        serialize_response(request_id, &variant).unwrap_or_default()
4582    }
4583}
4584
4585// ============================================================================
4586// Policy file watcher (hot-reload)
4587// ============================================================================
4588
4589/// Watch policy.csv for changes and reload PolicyManager automatically.
4590///
4591/// Watches the parent directory (not the file directly) to handle atomic
4592/// rename patterns used by editors like vim and emacs.
4593pub(crate) async fn watch_policy_file(
4594    policy_manager: Arc<PolicyManager>,
4595    policy_csv: std::path::PathBuf,
4596) {
4597    use notify::{Event, EventKind, RecursiveMode, Watcher};
4598    use tracing::{info, warn};
4599
4600    let (tx, mut rx) = tokio::sync::mpsc::channel::<()>(16);
4601
4602    let csv_path = policy_csv.clone();
4603    let mut watcher = match notify::recommended_watcher(move |res: Result<Event, notify::Error>| {
4604        if let Ok(event) = res {
4605            match event.kind {
4606                EventKind::Modify(_) | EventKind::Create(_)
4607                    if event.paths.iter().any(|p| p.ends_with("policy.csv")) =>
4608                {
4609                    let _ = tx.blocking_send(());
4610                }
4611                _ => {}
4612            }
4613        }
4614    }) {
4615        Ok(w) => w,
4616        Err(e) => {
4617            warn!("Failed to create policy file watcher: {}", e);
4618            return;
4619        }
4620    };
4621
4622    // Watch parent directory to catch atomic renames
4623    let watch_dir = match policy_csv.parent() {
4624        Some(dir) => dir,
4625        None => {
4626            warn!("policy.csv has no parent directory, cannot watch");
4627            return;
4628        }
4629    };
4630
4631    if let Err(e) = watcher.watch(watch_dir, RecursiveMode::NonRecursive) {
4632        warn!("Failed to watch {}: {}", watch_dir.display(), e);
4633        return;
4634    }
4635
4636    info!("Watching {} for policy changes", csv_path.display());
4637
4638    loop {
4639        // Wait for first event
4640        if rx.recv().await.is_none() {
4641            break; // Channel closed
4642        }
4643
4644        // Debounce: wait 500ms then drain remaining events
4645        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
4646        while rx.try_recv().is_ok() {}
4647
4648        // Reload policy
4649        match policy_manager.reload().await {
4650            Ok(()) => info!("Policy reloaded from disk"),
4651            Err(e) => warn!("Failed to reload policy: {}", e),
4652        }
4653    }
4654}
4655
4656#[cfg(test)]
4657#[allow(clippy::unwrap_used, clippy::expect_used)]
4658mod tests {
4659    use super::*;
4660    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
4661
4662    /// Mint the exact hybrid service JWT a fresh bootstrap produces for
4663    /// `service:{name}`: composite-signed by the CA pair derived from
4664    /// `ca_jwt_key`.
4665    fn bootstrap_hybrid_service_jwt(ca_jwt_key: &SigningKey, name: &str) -> String {
4666        let now = chrono::Utc::now().timestamp();
4667        let claims = hyprstream_rpc::auth::Claims::new(format!("service:{name}"), now, now + 3600);
4668        let ca_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(ca_jwt_key);
4669        let ca_pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk(&ca_pq);
4670        hyprstream_rpc::auth::jwt::encode_service_jwt_hybrid(&claims, ca_jwt_key, &ca_pq, &ca_pq_vk)
4671    }
4672
4673    /// A freshly bootstrapped hybrid service JWT passes the registration
4674    /// verification under a Hybrid policy — through the dispatch-style
4675    /// key-source resolution when the source carries the CA composite pair,
4676    /// and through the CA's own derived pair when no key source is wired.
4677    #[test]
4678    fn registration_accepts_hybrid_service_jwt_under_hybrid_policy() {
4679        let ca = SigningKey::from_bytes(&[0x2A; 32]);
4680        let jwt = bootstrap_hybrid_service_jwt(&ca, "discovery");
4681
4682        // Key-source path: the same composite resolution the dispatch plane uses.
4683        let ca_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&ca);
4684        let key_source = hyprstream_rpc::auth::ClusterKeySource::new(
4685            ca.verifying_key(),
4686            "http://localhost:9080".to_owned(),
4687        )
4688        .with_ca_composite_key(hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk(&ca_pq));
4689        let claims = verify_service_registration_jwt(
4690            &jwt,
4691            Some(&key_source),
4692            &ca,
4693            hyprstream_rpc::crypto::CryptoPolicy::Hybrid,
4694        )
4695        .unwrap();
4696        assert_eq!(claims.sub, "service:discovery");
4697
4698        // CA-fallback path: no key source wired, PolicyService derives the pair.
4699        let claims = verify_service_registration_jwt(
4700            &jwt,
4701            None,
4702            &ca,
4703            hyprstream_rpc::crypto::CryptoPolicy::Hybrid,
4704        )
4705        .unwrap();
4706        assert_eq!(claims.sub, "service:discovery");
4707    }
4708
4709    /// A classical EdDSA service JWT is rejected at registration under a
4710    /// Hybrid policy (matching the dispatch alg gate), and accepted only
4711    /// under Classical.
4712    #[test]
4713    fn registration_rejects_classical_service_jwt_under_hybrid_policy() {
4714        let ca = SigningKey::from_bytes(&[0x2B; 32]);
4715        let now = chrono::Utc::now().timestamp();
4716        let claims =
4717            hyprstream_rpc::auth::Claims::new("service:discovery".to_owned(), now, now + 3600);
4718        let jwt = hyprstream_rpc::auth::jwt::encode_service_jwt(&claims, &ca);
4719
4720        assert!(verify_service_registration_jwt(
4721            &jwt,
4722            None,
4723            &ca,
4724            hyprstream_rpc::crypto::CryptoPolicy::Hybrid,
4725        )
4726        .is_err());
4727        assert!(verify_service_registration_jwt(
4728            &jwt,
4729            None,
4730            &ca,
4731            hyprstream_rpc::crypto::CryptoPolicy::Classical,
4732        )
4733        .is_ok());
4734    }
4735
4736    /// A renewed service JWT binds the issuer URL in BOTH `iss` and `aud`
4737    /// (matching the provisioning mint, which strict composite audience
4738    /// validation requires); with no issuer configured, neither is stamped.
4739    #[test]
4740    fn renewed_service_claims_bind_issuer_and_audience() {
4741        let cnf = [7u8; 32];
4742        let claims = renewed_service_claims(
4743            "service:model".to_owned(),
4744            100,
4745            200,
4746            "http://localhost:9080",
4747            Some("tenant-a.example"),
4748            &cnf,
4749        );
4750        assert_eq!(claims.iss, "http://localhost:9080");
4751        assert_eq!(claims.aud.as_deref(), Some("http://localhost:9080"));
4752        assert_eq!(claims.sub, "service:model");
4753
4754        let bare = renewed_service_claims(
4755            "service:model".to_owned(),
4756            100,
4757            200,
4758            "",
4759            Some("tenant-a.example"),
4760            &cnf,
4761        );
4762        assert!(bare.iss.is_empty());
4763        assert!(bare.aud.is_none());
4764    }
4765
4766    /// Signing-domain separation: a `wit+jwt` composite-signed by the ACTIVE
4767    /// OAUTH-role pair — the pair that legitimately signs browser/workload
4768    /// WITs — must be rejected by the registration verification even though
4769    /// its kid resolves, while the same token signed by a Policy-role pair
4770    /// is accepted. Otherwise a compromised OAuth signing key could mint an
4771    /// installable service identity with an arbitrary `cnf`.
4772    #[test]
4773    fn registration_rejects_oauth_role_pair_and_accepts_policy_role_pair() {
4774        use hyprstream_rpc::auth::{
4775            CompositeKeyPair, CompositeKeySet, CompositePairRole, CompositePairState,
4776        };
4777        use std::sync::Arc;
4778
4779        let ca = SigningKey::from_bytes(&[0x2E; 32]);
4780        let now = chrono::Utc::now().timestamp();
4781        let claims =
4782            hyprstream_rpc::auth::Claims::new("service:discovery".to_owned(), now, now + 3600);
4783
4784        let mut role_pairs = Vec::new();
4785        for (seed, role) in [
4786            (0x2Fu8, CompositePairRole::OAuth),
4787            (0x30u8, CompositePairRole::Policy),
4788        ] {
4789            let ed = SigningKey::from_bytes(&[seed; 32]);
4790            let (pq, pq_vk) = hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair();
4791            let jwt = crate::auth::jwt::encode_composite_service_jwt(&claims, &pq, &ed);
4792            let kid = crate::auth::jwt::composite_kid(&pq_vk, &ed.verifying_key());
4793            role_pairs.push((
4794                jwt,
4795                CompositeKeyPair::signing(
4796                    kid,
4797                    Arc::new(pq),
4798                    Arc::new(ed),
4799                    role,
4800                    CompositePairState::Active,
4801                    0,
4802                    i64::MAX,
4803                ),
4804            ));
4805        }
4806
4807        let key_set = Arc::new(CompositeKeySet::default());
4808        key_set
4809            .publish(
4810                1,
4811                "role-separation".to_owned(),
4812                role_pairs.iter().map(|(_, pair)| pair.clone()).collect(),
4813            )
4814            .unwrap();
4815        let key_source = hyprstream_rpc::auth::ClusterKeySource::new(
4816            ca.verifying_key(),
4817            "http://localhost:9080".to_owned(),
4818        )
4819        .with_composite_key_set(key_set);
4820
4821        let (oauth_jwt, _) = &role_pairs[0];
4822        assert!(
4823            verify_service_registration_jwt(
4824                oauth_jwt,
4825                Some(&key_source),
4826                &ca,
4827                hyprstream_rpc::crypto::CryptoPolicy::Hybrid,
4828            )
4829            .is_err(),
4830            "an OAuth-role pair must not certify a service identity"
4831        );
4832
4833        let (policy_jwt, _) = &role_pairs[1];
4834        let verified = verify_service_registration_jwt(
4835            policy_jwt,
4836            Some(&key_source),
4837            &ca,
4838            hyprstream_rpc::crypto::CryptoPolicy::Hybrid,
4839        )
4840        .unwrap();
4841        assert_eq!(verified.sub, "service:discovery");
4842    }
4843
4844    /// A composite service JWT signed by a DIFFERENT pair (unknown kid)
4845    /// fails closed — neither the key source nor the CA fallback resolves it.
4846    #[test]
4847    fn registration_rejects_unknown_composite_kid() {
4848        let ca = SigningKey::from_bytes(&[0x2C; 32]);
4849        let other = SigningKey::from_bytes(&[0x2D; 32]);
4850        let jwt = bootstrap_hybrid_service_jwt(&other, "discovery");
4851
4852        let result = verify_service_registration_jwt(
4853            &jwt,
4854            None,
4855            &ca,
4856            hyprstream_rpc::crypto::CryptoPolicy::Hybrid,
4857        );
4858        assert!(
4859            result.is_err(),
4860            "a composite kid the CA did not sign for must fail closed"
4861        );
4862    }
4863
4864    async fn test_service_with_manager(
4865        manager: Arc<PolicyManager>,
4866    ) -> (PolicyService, tempfile::TempDir) {
4867        let root = tempfile::tempdir().expect("test: create policy git directory");
4868        let git2db = Arc::new(RwLock::new(
4869            Git2DB::open(root.path())
4870                .await
4871                .expect("test: open policy git database"),
4872        ));
4873        let service = PolicyService::new(
4874            manager,
4875            Arc::new(SigningKey::from_bytes(&[0x51; 32])),
4876            crate::config::TokenConfig::default(),
4877            git2db,
4878            TransportConfig::inproc("policy-path-form-subject-test"),
4879        );
4880        (service, root)
4881    }
4882
4883    async fn test_service() -> (PolicyService, tempfile::TempDir) {
4884        let manager = Arc::new(
4885            PolicyManager::permissive()
4886                .await
4887                .expect("test: policy manager"),
4888        );
4889        test_service_with_manager(manager).await
4890    }
4891
4892    #[tokio::test]
4893    async fn policy_commit_stages_only_policy_files() {
4894        let (service, root) = test_service().await;
4895        let registry_path = root.path().join(".registry");
4896        std::fs::create_dir_all(registry_path.join("policies")).unwrap();
4897        std::fs::create_dir_all(registry_path.join("pds")).unwrap();
4898        std::fs::write(registry_path.join("policies/model.conf"), "model fixture").unwrap();
4899        std::fs::write(registry_path.join("policies/policy.csv"), "policy fixture").unwrap();
4900        std::fs::write(
4901            registry_path.join("pds/atproto-signing-key"),
4902            "private fixture",
4903        )
4904        .unwrap();
4905        std::fs::write(registry_path.join("sessions.jsonl"), "private fixture").unwrap();
4906        std::fs::write(registry_path.join("unrelated.txt"), "unrelated fixture").unwrap();
4907
4908        service
4909            .stage_and_commit_policies("policy fixture")
4910            .await
4911            .unwrap();
4912        let reg = service.git2db.read().await;
4913        let handle = reg.repo(&service.registry_repo_id).unwrap();
4914        let repo = git2::Repository::open(handle.worktree().unwrap()).unwrap();
4915        let tree = repo.head().unwrap().peel_to_tree().unwrap();
4916        assert!(tree
4917            .get_path(std::path::Path::new("policies/policy.csv"))
4918            .is_ok());
4919        assert!(tree
4920            .get_path(std::path::Path::new("policies/model.conf"))
4921            .is_ok());
4922        assert!(tree
4923            .get_path(std::path::Path::new("pds/atproto-signing-key"))
4924            .is_err());
4925        assert!(tree
4926            .get_path(std::path::Path::new("sessions.jsonl"))
4927            .is_err());
4928        assert!(tree
4929            .get_path(std::path::Path::new("unrelated.txt"))
4930            .is_err());
4931
4932        // An index entry staged elsewhere must not hitchhike on a policy commit.
4933        let head = repo.head().unwrap().target().unwrap();
4934        handle
4935            .staging()
4936            .add("pds/atproto-signing-key")
4937            .await
4938            .unwrap();
4939        drop(reg);
4940        assert!(service
4941            .stage_and_commit_policies("another policy fixture")
4942            .await
4943            .is_err());
4944        assert_eq!(repo.head().unwrap().target().unwrap(), head);
4945    }
4946
4947    #[tokio::test]
4948    async fn h3a_primary_lookup_has_no_default_provider() {
4949        let (service, _root) = test_service().await;
4950        let ctx = EnvelopeContext::for_test_authenticated_subject(
4951            Subject::new("service:model"),
4952            SigningKey::from_bytes(&[77; 32]).verifying_key(),
4953        );
4954        let data = hyprstream_rpc_std::policy_client::ResolveSessionPrimary {
4955            issuer: "https://host.test".into(),
4956            profile: "federate-session-v1".into(),
4957            sid: "sid".into(),
4958            subject: "alice".into(),
4959            tenant: "tenant".into(),
4960            client: "client".into(),
4961            audience: "https://host.test".into(),
4962            scopes: vec!["model:query".into()],
4963            ed_public: vec![1; 32],
4964            suite_thumbprint: vec![2; 32],
4965            generation: vec![3; 32],
4966            expires_at: 1,
4967        };
4968        assert!(
4969            matches!(service.handle_resolve_session_primary(&ctx, 1, &data).await,
4970            Ok(PolicyResponseVariant::Error(ref error)) if error.code == "SESSION_PRIMARY_DENIED")
4971        );
4972    }
4973
4974    #[tokio::test]
4975    async fn h2_request_use_rpc_has_no_default_provider_or_replay_write() {
4976        let (service, _root) = test_service().await;
4977        let ctx = EnvelopeContext::for_test_authenticated_subject(
4978            Subject::new("service:model"),
4979            SigningKey::from_bytes(&[77; 32]).verifying_key(),
4980        );
4981        let data = hyprstream_rpc_std::policy_client::AdmitFederateRequest {
4982            issuer: "https://host.test".into(),
4983            profile: "federate-session-v1".into(),
4984            sid: "sid".into(),
4985            subject: "alice".into(),
4986            tenant: "tenant".into(),
4987            client: "client".into(),
4988            audience: "https://host.test".into(),
4989            scopes: vec!["query:model:test".into()],
4990            ed_public: vec![1; 32],
4991            suite_thumbprint: vec![2; 32],
4992            generation: vec![3; 32],
4993            collision_inventory_id: vec![4; 32],
4994            expires_at: 1,
4995            proof_epoch: 1,
4996            verified_namespace: vec![5; 32],
4997            request_id: vec![6; 16],
4998            resource: "model:test".into(),
4999            operation: "query".into(),
5000        };
5001        assert!(matches!(
5002            service.handle_admit_federate_request(&ctx, 1, &data).await,
5003            Ok(PolicyResponseVariant::AdmitFederateRequestResult(false))
5004        ));
5005    }
5006
5007    #[tokio::test]
5008    async fn federate_prepare_and_commit_rpc_have_no_default_provider() {
5009        let (service, _root) = test_service().await;
5010        let ctx = EnvelopeContext::for_test_authenticated_subject(
5011            Subject::new("service:oauth"),
5012            SigningKey::from_bytes(&[77; 32]).verifying_key(),
5013        );
5014        let source = hyprstream_rpc_std::policy_client::FederateVerifiedSource {
5015            issuer: "https://issuer.test".into(),
5016            subject: "source-user".into(),
5017            atproto_did: "did:plc:abcdefghijklmnopqrstuvwx".into(),
5018            jti: "jti".into(),
5019            nonce: "nonce".into(),
5020            token_hash: vec![1; 32],
5021            issued_at: 1,
5022            expires_at: 2,
5023            device_flow: false,
5024        };
5025        let prepare = hyprstream_rpc_std::policy_client::PrepareFederateSession {
5026            source: source.clone(),
5027            requested: vec!["infer:model:test".into()],
5028            challenge_id: vec![9; 32],
5029            challenge_created_at: 1,
5030            ed_public: vec![1; 32],
5031            pq_public: vec![2; 1952],
5032            client: "unconfigured-client".into(),
5033        };
5034        assert!(matches!(
5035            service.handle_prepare_federate_session(&ctx, 1, &prepare).await,
5036            Ok(PolicyResponseVariant::Error(ref error)) if error.code == "FEDERATE_PREPARE_DENIED"
5037        ));
5038        let commit = hyprstream_rpc_std::policy_client::CommitFederateSession {
5039            source,
5040            policy_handle: vec![3; 32],
5041            challenge_id: vec![9; 32],
5042            challenge_created_at: 1,
5043            challenge_expires_at: 2,
5044            ed_public: vec![1; 32],
5045            pq_public: vec![2; 1952],
5046            client: "unconfigured-client".into(),
5047        };
5048        assert!(matches!(
5049            service.handle_commit_federate_session(&ctx, 1, &commit).await,
5050            Ok(PolicyResponseVariant::Error(ref error)) if error.code == "FEDERATE_COMMIT_DENIED"
5051        ));
5052    }
5053
5054    #[tokio::test]
5055    async fn external_delegated_check_intersects_casbin_with_signed_scope() {
5056        let manager = PolicyManager::permissive().await.unwrap();
5057        assert!(
5058            manager
5059                .check_with_domain("alice", "did:web:lab.example", "model:Status", "query")
5060                .await
5061        );
5062        let unscoped = hyprstream_rpc::auth::Claims::new("alice".into(), 1, 61);
5063        assert!(!delegated_resource_scope_allows(
5064            &unscoped,
5065            "model:Status",
5066            "query"
5067        ));
5068        let read = unscoped.clone().with_scope(Some("read:*:*".into()));
5069        assert!(delegated_resource_scope_allows(
5070            &read,
5071            "model:Status",
5072            "query"
5073        ));
5074        assert!(!delegated_resource_scope_allows(
5075            &read,
5076            "model:qwen:main",
5077            "infer"
5078        ));
5079        assert!(!delegated_resource_scope_allows(
5080            &read,
5081            "model:Load",
5082            "write"
5083        ));
5084        let exact = unscoped.with_scope(Some("infer:model:qwen:main".into()));
5085        assert!(delegated_resource_scope_allows(
5086            &exact,
5087            "model:qwen:main",
5088            "infer"
5089        ));
5090        assert!(!delegated_resource_scope_allows(
5091            &exact,
5092            "model:qwen:other",
5093            "infer"
5094        ));
5095        // Model.applyChatTemplate checks query before inference. Model's leaf
5096        // gate separately requires read for scoped status at the same resource.
5097        assert!(delegated_resource_scope_allows(
5098            &exact,
5099            "model:qwen:main",
5100            "query"
5101        ));
5102        assert!(!delegated_resource_scope_allows(
5103            &exact,
5104            "model:Status",
5105            "query"
5106        ));
5107        assert!(!delegated_resource_scope_allows(
5108            &exact,
5109            "model:qwen:other",
5110            "query"
5111        ));
5112
5113        let infer = crate::auth::Operation::Infer.as_str();
5114        let query = crate::auth::Operation::Query.as_str();
5115        let approved = read
5116            .clone()
5117            .with_scope(Some("read:model:* infer:model:*".into()));
5118        assert!(delegated_resource_scope_allows(
5119            &approved,
5120            "model:qwen:main",
5121            infer
5122        ));
5123        assert!(delegated_resource_scope_allows(
5124            &approved,
5125            "model:qwen:main",
5126            query
5127        ));
5128        assert!(delegated_resource_scope_allows(
5129            &read,
5130            "model:Status",
5131            query
5132        ));
5133        assert!(!delegated_resource_scope_allows(
5134            &read,
5135            "model:qwen:main",
5136            infer
5137        ));
5138        assert!(delegated_resource_scope_allows(
5139            &exact,
5140            "model:qwen:main",
5141            query
5142        ));
5143        assert!(!delegated_resource_scope_allows(
5144            &exact,
5145            "model:Status",
5146            query
5147        ));
5148        for operation in [
5149            "infer.stage",
5150            "infer.generate.extra",
5151            "query.other",
5152            "ttt.writeback",
5153        ] {
5154            assert!(!delegated_resource_scope_allows(
5155                &approved,
5156                "model:qwen:main",
5157                operation
5158            ));
5159        }
5160    }
5161
5162    fn issue(subject: &str) -> IssueToken {
5163        IssueToken {
5164            requested_scopes: Some(vec!["read".to_owned()]),
5165            ttl: Some(60),
5166            audience: None,
5167            subject: Some(subject.to_owned()),
5168            user_pub_key: None,
5169            dpop_jkt: None,
5170            issuer: None,
5171            tenant: None,
5172            require_clearance: false,
5173            session_id: None,
5174            issuance_profile: IssueTokenProfile::Rfc8693,
5175            // The user at+jwt profiles require a non-empty RFC 9068 client_id.
5176            client_id: Some("hyprstream-oauth-client-1".to_owned()),
5177        }
5178    }
5179
5180    /// A classical single-Ed authoritative Primary resolver for `subject` bound
5181    /// to `ed_key` — the isolated fixture equivalent of WS-C's enrollment store,
5182    /// so v16 user-issuance can stamp `cnf.hs_signer_suite`.
5183    fn v16_primary_resolver(subject: &str, ed_key: [u8; 32]) -> Arc<dyn PrimaryEnrollmentResolver> {
5184        struct R {
5185            subject: String,
5186            key: [u8; 32],
5187        }
5188        impl PrimaryEnrollmentResolver for R {
5189            fn primary_group(&self, principal: &str, _tenant: &str) -> Option<PrimaryGroup> {
5190                (principal == self.subject).then(|| PrimaryGroup {
5191                    suite_id: hyprstream_rpc::auth::SUITE_CLASSICAL_ED25519.to_owned(),
5192                    ordered_component_keys: vec![self.key.to_vec()],
5193                })
5194            }
5195        }
5196        Arc::new(R {
5197            subject: subject.to_owned(),
5198            key: ed_key,
5199        })
5200    }
5201
5202    /// A single-service classical enrollment manifest for `service` bound to
5203    /// `ed_key`, so v16 service-issuance can stamp the enrolled signer suite.
5204    fn v16_service_manifest(
5205        service: &str,
5206        ed_key: [u8; 32],
5207    ) -> Arc<crate::auth::service_enrollment::ServiceEnrollmentManifest> {
5208        use crate::auth::service_enrollment::{
5209            ServiceEnrollment, ServiceEnrollmentManifest, SERVICE_ENROLLMENT_VERSION,
5210        };
5211        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
5212        use hyprstream_rpc::auth::mac::{Assurance, CompartmentSet, Level, SecurityLabel};
5213        let mut services = std::collections::BTreeMap::new();
5214        services.insert(
5215            service.to_owned(),
5216            ServiceEnrollment {
5217                ed25519_pubkey: URL_SAFE_NO_PAD.encode(ed_key),
5218                ml_dsa_pubkey: None,
5219                clearance: SecurityLabel::new(
5220                    Level::Internal,
5221                    Assurance::Classical,
5222                    CompartmentSet::EMPTY,
5223                ),
5224                allowed_audiences: None,
5225                workload_session: false,
5226            },
5227        );
5228        Arc::new(ServiceEnrollmentManifest {
5229            version: SERVICE_ENROLLMENT_VERSION,
5230            services,
5231        })
5232    }
5233
5234    #[tokio::test]
5235    async fn request_domain_keeps_only_global_authorities_outside_tenant_domains() {
5236        let (service, _root) = test_service().await;
5237        let service_signer = SigningKey::from_bytes(&[0x50; 32]).verifying_key();
5238
5239        let oauth = EnvelopeContext::for_test_authenticated_subject(
5240            Subject::new("service:oauth"),
5241            service_signer,
5242        );
5243        assert_eq!(
5244            service.request_domain(&oauth).expect("global OAuth domain"),
5245            "*"
5246        );
5247
5248        let tenant_user = EnvelopeContext::for_test_authenticated_subject_in_tenant(
5249            Subject::new("alice"),
5250            "tenant-a",
5251            service_signer,
5252        );
5253        assert_eq!(
5254            service
5255                .request_domain(&tenant_user)
5256                .expect("verified tenant domain"),
5257            "tenant-a"
5258        );
5259
5260        let tenantless_user =
5261            EnvelopeContext::for_test_authenticated_subject(Subject::new("alice"), service_signer);
5262        assert!(service.request_domain(&tenantless_user).is_err());
5263
5264        let federated_service = EnvelopeContext::for_test_authenticated_subject(
5265            Subject::federated("https://peer.example", "service:oauth"),
5266            service_signer,
5267        );
5268        assert!(
5269            service.request_domain(&federated_service).is_err(),
5270            "a federated subject cannot claim local global-service authority by name"
5271        );
5272
5273        let wildcard_service = EnvelopeContext::for_test_authenticated_subject_in_tenant(
5274            Subject::new("service:oauth"),
5275            "*",
5276            service_signer,
5277        );
5278        assert!(service.request_domain(&wildcard_service).is_err());
5279
5280        let policy_authority = EnvelopeContext::for_test_authenticated_subject(
5281            Subject::anonymous(),
5282            service.signing_key.verifying_key(),
5283        );
5284        assert_eq!(
5285            service
5286                .request_domain(&policy_authority)
5287                .expect("PolicyService bootstrap authority domain"),
5288            "*"
5289        );
5290    }
5291
5292    #[tokio::test]
5293    async fn tokenless_local_policy_authority_can_apply_a_template() {
5294        let (service, _root) = test_service().await;
5295        let context = EnvelopeContext::for_test_authenticated_subject(
5296            Subject::new("service:policy"),
5297            service.signing_key.verifying_key(),
5298        );
5299
5300        let response = service
5301            .handle_apply_template(
5302                &context,
5303                1,
5304                &ApplyTemplate {
5305                    name: "public-read".to_owned(),
5306                },
5307            )
5308            .await
5309            .expect("PolicyService must return a template response");
5310
5311        assert!(matches!(
5312            response,
5313            PolicyResponseVariant::ApplyTemplateResult(_)
5314        ));
5315    }
5316
5317    #[tokio::test]
5318    async fn tokenless_local_policy_authority_uses_global_domain_for_policy_control_plane() {
5319        let (service, _root) = test_service().await;
5320        let context = EnvelopeContext::for_test_authenticated_subject(
5321            Subject::new("service:policy"),
5322            service.signing_key.verifying_key(),
5323        );
5324
5325        let assert_not_missing_tenant = |operation: &str, result: Result<PolicyResponseVariant>| {
5326            if let Err(error) = result {
5327                assert!(
5328                    !error.to_string().contains("no verified tenant domain"),
5329                    "{operation} reached a tenant-only handler path: {error}"
5330                );
5331            }
5332        };
5333
5334        assert_not_missing_tenant(
5335            "apply draft",
5336            service
5337                .handle_apply_draft(&context, 1, &ApplyDraft { message: None })
5338                .await,
5339        );
5340        assert_not_missing_tenant(
5341            "rollback",
5342            service
5343                .handle_rollback(
5344                    &context,
5345                    2,
5346                    &RollbackPolicy {
5347                        git_ref: "HEAD".to_owned(),
5348                    },
5349                )
5350                .await,
5351        );
5352        assert_not_missing_tenant(
5353            "history",
5354            service
5355                .handle_get_history(&context, 3, &GetHistory { count: 1 })
5356                .await,
5357        );
5358        assert_not_missing_tenant(
5359            "diff",
5360            service
5361                .handle_get_diff(&context, 4, &GetDiff { git_ref: None })
5362                .await,
5363        );
5364        assert_not_missing_tenant(
5365            "draft status",
5366            service.handle_get_draft_status(&context, 5).await,
5367        );
5368        let grouping = AddGrouping {
5369            user: "bootstrap-user".to_owned(),
5370            role: "viewer".to_owned(),
5371        };
5372        let granted = service
5373            .handle_add_grouping(&context, 6, &grouping)
5374            .await
5375            .expect("global policy authority must grant a global role");
5376        assert!(
5377            matches!(granted, PolicyResponseVariant::AddGroupingResult(_))
5378                || matches!(
5379                    granted,
5380                    PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "COMMIT_FAILED"
5381                )
5382        );
5383        assert!(
5384            service
5385                .policy_manager
5386                .get_grouping_policy()
5387                .await
5388                .contains(&vec![grouping.user.clone(), grouping.role.clone()]),
5389            "a failed audit commit must retain the wildcard bootstrap role"
5390        );
5391        assert!(
5392            !service
5393                .policy_manager
5394                .get_domain_grouping_policy()
5395                .await
5396                .contains(&vec![
5397                    grouping.user.clone(),
5398                    grouping.role.clone(),
5399                    "*".to_owned(),
5400                ]),
5401            "the wildcard bootstrap domain must not create a g2 relation"
5402        );
5403        let duplicate = service
5404            .handle_add_grouping(&context, 7, &grouping)
5405            .await
5406            .expect("duplicate global role grant must return a policy response");
5407        assert!(matches!(
5408            duplicate,
5409            PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "NO_CHANGE"
5410        ));
5411
5412        let revoked = service
5413            .handle_remove_grouping(
5414                &context,
5415                8,
5416                &RemoveGrouping {
5417                    user: grouping.user.clone(),
5418                    role: grouping.role.clone(),
5419                },
5420            )
5421            .await
5422            .expect("global policy authority must revoke a global role");
5423        assert!(
5424            matches!(revoked, PolicyResponseVariant::RemoveGroupingResult(_))
5425                || matches!(
5426                    revoked,
5427                    PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "COMMIT_FAILED"
5428                )
5429        );
5430        assert!(
5431            !service
5432                .policy_manager
5433                .get_grouping_policy()
5434                .await
5435                .contains(&vec![grouping.user.clone(), grouping.role.clone()]),
5436            "a failed audit commit must retain the wildcard bootstrap role removal"
5437        );
5438        let missing = service
5439            .handle_remove_grouping(
5440                &context,
5441                9,
5442                &RemoveGrouping {
5443                    user: grouping.user,
5444                    role: grouping.role,
5445                },
5446            )
5447            .await
5448            .expect("missing global role revoke must return a policy response");
5449        assert!(matches!(
5450            missing,
5451            PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "NOT_FOUND"
5452        ));
5453    }
5454
5455    #[tokio::test]
5456    async fn unauthenticated_policy_check_is_denied() {
5457        let manager = Arc::new(
5458            PolicyManager::new_in_memory()
5459                .await
5460                .expect("test: policy manager"),
5461        );
5462        manager
5463            .add_policy_with_domain(
5464                "alice",
5465                "tenant-a",
5466                "model:allowed",
5467                "infer.generate",
5468                "allow",
5469            )
5470            .await
5471            .expect("test: policy grant");
5472        let (service, _root) = test_service_with_manager(manager).await;
5473        let ctx = EnvelopeContext::for_test_authenticated_subject(
5474            Subject::anonymous(),
5475            SigningKey::from_bytes(&[0x53; 32]).verifying_key(),
5476        );
5477        let request = PolicyCheck {
5478            subject: "alice".to_owned(),
5479            domain: "tenant-a".to_owned(),
5480            resource: "model:allowed".to_owned(),
5481            operation: "infer.generate".to_owned(),
5482        };
5483
5484        let response = service
5485            .handle_check(&ctx, 1, &request)
5486            .await
5487            .expect("denial is a policy response");
5488        assert!(matches!(
5489            response,
5490            PolicyResponseVariant::CheckResult(false)
5491        ));
5492    }
5493
5494    #[tokio::test]
5495    async fn policy_check_uses_verified_context_not_requested_identity() {
5496        let manager = Arc::new(
5497            PolicyManager::new_in_memory()
5498                .await
5499                .expect("test: policy manager"),
5500        );
5501        manager
5502            .add_policy_with_domain("alice", "tenant-a", "model:own", "infer.generate", "allow")
5503            .await
5504            .expect("test: own-tenant grant");
5505        manager
5506            .add_policy_with_domain(
5507                "victim",
5508                "tenant-b",
5509                "model:foreign",
5510                "infer.generate",
5511                "allow",
5512            )
5513            .await
5514            .expect("test: foreign-tenant grant");
5515        let (service, _root) = test_service_with_manager(manager).await;
5516        let ctx = EnvelopeContext::for_test_authenticated_subject_in_tenant(
5517            Subject::new("alice"),
5518            "tenant-a",
5519            SigningKey::from_bytes(&[0x54; 32]).verifying_key(),
5520        );
5521
5522        let forged_probe = PolicyCheck {
5523            subject: "victim".to_owned(),
5524            domain: "tenant-b".to_owned(),
5525            resource: "model:foreign".to_owned(),
5526            operation: "infer.generate".to_owned(),
5527        };
5528        let denied = service
5529            .handle_check(&ctx, 1, &forged_probe)
5530            .await
5531            .expect("denial is a policy response");
5532        assert!(matches!(denied, PolicyResponseVariant::CheckResult(false)));
5533
5534        let stale_wire_identity = PolicyCheck {
5535            subject: "victim".to_owned(),
5536            domain: "tenant-b".to_owned(),
5537            resource: "model:own".to_owned(),
5538            operation: "infer.generate".to_owned(),
5539        };
5540        let allowed = service
5541            .handle_check(&ctx, 2, &stale_wire_identity)
5542            .await
5543            .expect("allow is a policy response");
5544        assert!(matches!(allowed, PolicyResponseVariant::CheckResult(true)));
5545    }
5546
5547    #[tokio::test(flavor = "multi_thread")]
5548    async fn service_mediated_check_uses_verified_user_not_broad_deputy() {
5549        use hyprstream_service::{InprocManager, ServiceManager};
5550
5551        crate::mac::install_explicit_test_dispatch_pep();
5552        let _ = hyprstream_rpc::envelope::install_verify_config(
5553            hyprstream_rpc::envelope::EnvelopeVerifyConfig {
5554                policy: hyprstream_rpc::crypto::CryptoPolicy::Classical,
5555                pq_store: None,
5556            },
5557        );
5558        let _ = hyprstream_rpc::envelope::install_response_verify_config(
5559            hyprstream_rpc::envelope::ResponseVerifyConfig {
5560                policy: hyprstream_rpc::crypto::CryptoPolicy::Classical,
5561                pq_store: None,
5562            },
5563        );
5564        // Independently runnable: RPC-path token verification fails closed
5565        // without a process-global revocation store. Publish an isolated empty
5566        // store when none exists (guarded, matching the convention in
5567        // middleware/oauth::revocation tests) so this security test does not
5568        // depend on a sibling publishing the store first — under nextest
5569        // per-test process isolation no other test can provide it.
5570        if hyprstream_rpc::auth::global_credential_revocation_store().is_none() {
5571            let _ = hyprstream_rpc::auth::set_global_credential_revocation_store(Arc::new(
5572                hyprstream_rpc::auth::InMemoryCredentialRevocationStore::new(),
5573            ));
5574        }
5575
5576        let manager = Arc::new(
5577            PolicyManager::new_in_memory()
5578                .await
5579                .expect("test: policy manager"),
5580        );
5581        manager
5582            .add_policy_with_domain(
5583                "alice",
5584                "did:web:tenant-a.example",
5585                "model:allowed",
5586                "infer.generate",
5587                "allow",
5588            )
5589            .await
5590            .expect("test: tenant user grant");
5591        manager
5592            .add_policy_with_domain(
5593                "service:registry",
5594                "*",
5595                "model:deputy-only",
5596                "infer.generate",
5597                "allow",
5598            )
5599            .await
5600            .expect("test: broad deputy grant");
5601        let allowed_federation =
5602            crate::auth::federation_registration_resource("https://allowed.example")
5603                .expect("test: federation resource");
5604        let blocked_federation =
5605            crate::auth::federation_registration_resource("https://blocked.example")
5606                .expect("test: federation resource");
5607        manager
5608            .add_policy_with_domain("*", "*", &allowed_federation, "check", "allow")
5609            .await
5610            .expect("test: per-origin federation grant");
5611
5612        let endpoint = format!("policy-delegation-{}", rand::random::<u64>());
5613        manager
5614            .add_policy_with_domain(
5615                "alice",
5616                "did:web:tenant-a.example",
5617                "placement:candidate:*",
5618                "query",
5619                "allow",
5620            )
5621            .await
5622            .expect("capacity grant");
5623        let policy_key = SigningKey::from_bytes(&[0x70; 32]);
5624        let actor_key = SigningKey::from_bytes(&[0x71; 32]);
5625        let actor_verifying_key = actor_key.verifying_key();
5626        let user_key = SigningKey::from_bytes(&[0x72; 32]);
5627        let other_user_key = SigningKey::from_bytes(&[0x73; 32]);
5628        let issuer = "https://policy-delegation.test";
5629        let key_source = hyprstream_rpc::auth::ClusterKeySource::new(
5630            policy_key.verifying_key(),
5631            issuer.to_owned(),
5632        );
5633        let root = tempfile::tempdir().expect("test: policy git directory");
5634        let git2db = Arc::new(RwLock::new(
5635            Git2DB::open(root.path())
5636                .await
5637                .expect("test: open policy git database"),
5638        ));
5639        let service = PolicyService::new(
5640            manager,
5641            Arc::new(policy_key.clone()),
5642            crate::config::TokenConfig::default(),
5643            git2db,
5644            TransportConfig::inproc(&endpoint),
5645        )
5646        .with_jwt_key_source(Arc::new(key_source));
5647        let services = InprocManager::new();
5648        services
5649            .spawn(Box::new(service))
5650            .await
5651            .expect("test: spawn policy service");
5652
5653        let now = chrono::Utc::now().timestamp();
5654        hyprstream_service::global_trust_store().insert(
5655            actor_verifying_key,
5656            hyprstream_service::Attestation {
5657                scopes: ["registry".to_owned()].into_iter().collect(),
5658                subject: None,
5659                jwt: None,
5660                expires_at: now + 300,
5661                attested_by: Some(policy_key.verifying_key().to_bytes()),
5662            },
5663        );
5664        let user_token = hyprstream_rpc::auth::jwt::encode(
5665            &hyprstream_rpc::auth::Claims::new("alice".to_owned(), now, now + 300)
5666                .with_issuer(issuer.to_owned())
5667                .with_tenant("did:web:tenant-a.example".to_owned())
5668                .with_cnf_jwk(user_key.verifying_key().as_bytes())
5669                .with_client_id("hyprstream-oauth-client-1"),
5670            &policy_key,
5671        );
5672        let other_tenant_token = hyprstream_rpc::auth::jwt::encode(
5673            &hyprstream_rpc::auth::Claims::new("bob".to_owned(), now, now + 300)
5674                .with_issuer(issuer.to_owned())
5675                .with_tenant("did:web:tenant-b.example".to_owned())
5676                .with_cnf_jwk(other_user_key.verifying_key().as_bytes())
5677                .with_client_id("hyprstream-oauth-client-1"),
5678            &policy_key,
5679        );
5680        let client = hyprstream_rpc_std::policy_client::PolicyClient::for_local_endpoint_bootstrap(
5681            &format!("inproc://{endpoint}"),
5682            actor_key,
5683            policy_key.verifying_key(),
5684            None,
5685        )
5686        .expect("test: policy client");
5687
5688        let allowed_origin = client
5689            .check(&PolicyCheck {
5690                subject: String::new(),
5691                domain: String::new(),
5692                resource: allowed_federation,
5693                operation: "check".to_owned(),
5694            })
5695            .await
5696            .expect("test: allowlisted federation decision");
5697        assert!(allowed_origin, "the allowlisted origin must be admitted");
5698
5699        let blocked_origin = client
5700            .check(&PolicyCheck {
5701                subject: String::new(),
5702                domain: String::new(),
5703                resource: blocked_federation,
5704                operation: "check".to_owned(),
5705            })
5706            .await
5707            .expect("test: non-allowlisted federation decision");
5708        assert!(
5709            !blocked_origin,
5710            "the decision must vary by origin, not the deputy service"
5711        );
5712
5713        let allowed = client
5714            .clone()
5715            .with_delegated_bearer(user_token.clone())
5716            .check(&PolicyCheck {
5717                subject: "victim".to_owned(),
5718                domain: "did:web:tenant-b.example".to_owned(),
5719                resource: "model:allowed".to_owned(),
5720                operation: "infer.generate".to_owned(),
5721            })
5722            .await
5723            .expect("test: tenant user decision");
5724        assert!(allowed, "verified delegated user grant must be effective");
5725
5726        let provider = crate::services::discovery::PolicyAuthProvider::new(client.clone());
5727        let batched = hyprstream_discovery::AuthorizationProvider::check_batch(
5728            &provider,
5729            "alice",
5730            "forged-other-tenant",
5731            &["model:allowed".to_owned(), "model:deputy-only".to_owned()],
5732            "infer.generate",
5733            Some(&user_token),
5734        )
5735        .await
5736        .expect("real batched Policy RPC with delegated identity");
5737        assert_eq!(
5738            batched,
5739            vec![true, false],
5740            "batch preserves user authority, not deputy grants"
5741        );
5742        assert!(
5743            hyprstream_discovery::AuthorizationProvider::check_batch(
5744                &provider,
5745                "alice",
5746                "*",
5747                &["model:allowed".to_owned()],
5748                "infer.generate",
5749                None,
5750            )
5751            .await
5752            .is_err(),
5753            "batch cannot mediate a user without verified bearer"
5754        );
5755        assert!(
5756            client
5757                .clone()
5758                .with_delegated_bearer(user_token.clone())
5759                .check_batch(&PolicyCheckBatch {
5760                    checks: vec![
5761                        PolicyCheck {
5762                            subject: String::new(),
5763                            domain: String::new(),
5764                            resource: "model:allowed".to_owned(),
5765                            operation: "infer.generate".to_owned()
5766                        };
5767                        257
5768                    ],
5769                })
5770                .await
5771                .is_err(),
5772            "batch bound enforced by server, not only adapter"
5773        );
5774
5775        // Exercise the real adapter, generated wire codec and Policy handler
5776        // for a full configured fleet, separately from Valkey snapshot timing.
5777        use futures::{stream, StreamExt, TryStreamExt};
5778        let resources: Vec<_> = (0..65_536)
5779            .map(|i| format!("placement:candidate:did:web:capacity-{i}.example"))
5780            .collect();
5781        let started = std::time::Instant::now();
5782        let decisions = stream::iter(resources.chunks(256))
5783            .map(|batch| {
5784                hyprstream_discovery::AuthorizationProvider::check_batch(
5785                    &provider,
5786                    "alice",
5787                    "*",
5788                    batch,
5789                    "query",
5790                    Some(&user_token),
5791                )
5792            })
5793            .buffer_unordered(16)
5794            .try_collect::<Vec<_>>()
5795            .await
5796            .expect("full-fleet Policy batch RPC");
5797        assert_eq!(
5798            decisions
5799                .iter()
5800                .flatten()
5801                .filter(|allowed| **allowed)
5802                .count(),
5803            65_536
5804        );
5805        assert!(
5806            started.elapsed() < std::time::Duration::from_secs(5),
5807            "healthy Policy batching exceeded candidate deadline: {:?}",
5808            started.elapsed()
5809        );
5810
5811        let cross_tenant = client
5812            .clone()
5813            .with_delegated_bearer(other_tenant_token)
5814            .check(&PolicyCheck {
5815                subject: "alice".to_owned(),
5816                domain: "did:web:tenant-a.example".to_owned(),
5817                resource: "model:allowed".to_owned(),
5818                operation: "infer.generate".to_owned(),
5819            })
5820            .await
5821            .expect("test: cross-tenant decision");
5822        assert!(
5823            !cross_tenant,
5824            "tenant-b's verified bearer must not inherit tenant-a's grant"
5825        );
5826
5827        let denied = client
5828            .with_delegated_bearer(user_token)
5829            .check(&PolicyCheck {
5830                subject: "service:registry".to_owned(),
5831                domain: "*".to_owned(),
5832                resource: "model:deputy-only".to_owned(),
5833                operation: "infer.generate".to_owned(),
5834            })
5835            .await
5836            .expect("test: broad deputy decision");
5837        assert!(
5838            !denied,
5839            "the deputy's broad global grant must not replace the delegated user"
5840        );
5841        hyprstream_service::global_trust_store().remove(&actor_verifying_key);
5842    }
5843
5844    #[tokio::test]
5845    async fn tenantless_user_policy_check_is_denied() {
5846        let (service, _root) = test_service().await;
5847        let ctx = EnvelopeContext::for_test_authenticated_subject(
5848            Subject::new("alice"),
5849            SigningKey::from_bytes(&[0x55; 32]).verifying_key(),
5850        );
5851        let request = PolicyCheck {
5852            subject: "alice".to_owned(),
5853            domain: "*".to_owned(),
5854            resource: "model:any".to_owned(),
5855            operation: "infer.generate".to_owned(),
5856        };
5857
5858        let response = service
5859            .handle_check(&ctx, 1, &request)
5860            .await
5861            .expect("denial is a policy response");
5862        assert!(matches!(
5863            response,
5864            PolicyResponseVariant::CheckResult(false)
5865        ));
5866    }
5867
5868    #[tokio::test]
5869    async fn cross_domain_token_mint_is_denied_without_target_tenant_grant() {
5870        let manager = Arc::new(
5871            PolicyManager::new_in_memory()
5872                .await
5873                .expect("test: policy manager"),
5874        );
5875        manager
5876            .add_policy_with_domain(
5877                "service:test-caller",
5878                "tenant-a",
5879                "policy:IssueToken",
5880                "manage",
5881                "allow",
5882            )
5883            .await
5884            .expect("test: caller-domain mint grant");
5885        let (service, _root) = test_service_with_manager(manager).await;
5886        let signer = SigningKey::from_bytes(&[0x52; 32]).verifying_key();
5887        let ctx = EnvelopeContext::for_test_authenticated_subject_in_tenant(
5888            Subject::new("service:test-caller"),
5889            "tenant-a",
5890            signer,
5891        );
5892        let mut request = issue("victim");
5893        request.tenant = Some("tenant-b".to_owned());
5894
5895        let response = service
5896            .handle_issue_token(&ctx, 1, &request)
5897            .await
5898            .expect("cross-domain denial is a policy response");
5899
5900        match response {
5901            PolicyResponseVariant::Error(error) => {
5902                assert_eq!(error.code, "UNAUTHORIZED_SUBJECT");
5903                assert!(error.message.contains("tenant-b"));
5904            }
5905            other => panic!("cross-domain token mint unexpectedly proceeded: {other:?}"),
5906        }
5907    }
5908
5909    fn attestation(expires_at: i64, jwt: &str) -> hyprstream_service::Attestation {
5910        hyprstream_service::Attestation {
5911            scopes: std::iter::once("model".to_owned()).collect(),
5912            subject: None,
5913            jwt: Some(jwt.to_owned()),
5914            expires_at,
5915            attested_by: None,
5916        }
5917    }
5918
5919    #[tokio::test]
5920    async fn issue_token_rejects_path_form_subject_at_shared_signing_boundary() {
5921        let (service, _root) = test_service().await;
5922        let ctx = EnvelopeContext::from_callback_service(1, "test-caller");
5923
5924        let response = service
5925            .handle_issue_token(&ctx, 1, &issue("did:web:accounts.example:users:alice"))
5926            .await
5927            .expect("path-form rejection is a policy response");
5928
5929        match response {
5930            PolicyResponseVariant::Error(error) => {
5931                assert_eq!(error.code, "FROZEN_PATH_FORM_SUBJECT");
5932                assert!(error.message.contains("path-form did:web"));
5933            }
5934            other => panic!("path-form subject reached token signing: {other:?}"),
5935        }
5936    }
5937
5938    #[tokio::test]
5939    async fn issue_token_path_form_guard_allows_legitimate_subject_families() {
5940        let (service, _root) = test_service().await;
5941        let ctx = EnvelopeContext::from_callback_service(1, "test-caller");
5942
5943        for subject in [
5944            "alice",
5945            "did:web:alice.example",
5946            "did:web:localhost%3A6791",
5947            "did:key:z6MkpTHR8VNsBxYAAHWutMGeQ4hz2FV6B14xd9CZpkmS5i5o",
5948            "service:model",
5949        ] {
5950            let response = service.handle_issue_token(&ctx, 1, &issue(subject)).await;
5951            assert!(
5952                !matches!(
5953                    response,
5954                    Ok(PolicyResponseVariant::Error(ErrorInfo { ref code, .. }))
5955                        if code == "FROZEN_PATH_FORM_SUBJECT"
5956                ),
5957                "legitimate subject {subject:?} was rejected by the path-form guard",
5958            );
5959        }
5960    }
5961
5962    #[tokio::test]
5963    async fn interactive_issue_token_rejects_missing_session_id() {
5964        let (service, _root) = test_service().await;
5965        let ctx = EnvelopeContext::from_callback_service(1, "test-caller");
5966        let mut request = issue("alice");
5967        request.issuance_profile = IssueTokenProfile::InteractiveSession;
5968        request.session_id = None;
5969
5970        let response = service
5971            .handle_issue_token(&ctx, 1, &request)
5972            .await
5973            .expect("missing-session denial is a policy response");
5974        assert!(matches!(
5975            response,
5976            PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "MISSING_SESSION"
5977        ));
5978    }
5979
5980    #[tokio::test]
5981    async fn deliberate_noninteractive_rfc_profiles_mint_without_session_id() {
5982        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
5983        let (service, _root) = test_service().await;
5984        let user_ed = SigningKey::from_bytes(&[0x8a; 32]);
5985        let service = service.with_primary_enrollment_resolver(v16_primary_resolver(
5986            "alice",
5987            user_ed.verifying_key().to_bytes(),
5988        ));
5989        let ctx = EnvelopeContext::from_callback_service(1, "test-caller");
5990
5991        for profile in [IssueTokenProfile::Rfc8693, IssueTokenProfile::Rfc7523] {
5992            let mut request = issue("alice");
5993            request.issuance_profile = profile;
5994            request.session_id = None;
5995            request.user_pub_key = Some(URL_SAFE_NO_PAD.encode(user_ed.verifying_key().to_bytes()));
5996            let response = service
5997                .handle_issue_token(&ctx, 1, &request)
5998                .await
5999                .expect("non-interactive issuance is a policy response");
6000            // The RFC profiles require no session id: reaching the mint proves
6001            // the profile gate accepted without one. test_service provisions no
6002            // composite signing authority, so a cleared gate surfaces as
6003            // SIGNING_NOT_CONFIGURED rather than a session/profile rejection.
6004            match response {
6005                PolicyResponseVariant::IssueTokenResult(_) => {}
6006                PolicyResponseVariant::Error(ErrorInfo { ref code, .. })
6007                    if code == "SIGNING_NOT_CONFIGURED" => {}
6008                other => panic!("RFC profile must pass the gate without a session: {other:?}"),
6009            }
6010        }
6011    }
6012
6013    #[test]
6014    fn rfc8693_child_resolves_exact_signed_enrollment_without_caller_label() {
6015        use hyprstream_rpc::auth::mac::{Assurance, CompartmentSet, Level, SecurityLabel};
6016
6017        let did = "did:web:canary-agent.publisher.staging.lab.hyprstream.com";
6018        let label = SecurityLabel::new(
6019            Level::Internal,
6020            Assurance::Unverified,
6021            CompartmentSet::EMPTY,
6022        );
6023        let resolver = |subject: &str| (subject == did).then_some(label);
6024        let resolved =
6025            enrolled_user_clearance_for_issue(IssueTokenProfile::Rfc8693, false, did, &resolver);
6026        assert_eq!(resolved, Some(label));
6027        assert_eq!(
6028            enrolled_user_clearance_for_issue(
6029                IssueTokenProfile::Rfc8693,
6030                false,
6031                "did:web:foreign.publisher.staging.lab.hyprstream.com",
6032                &resolver,
6033            ),
6034            None,
6035            "an unenrolled child must stay unlabeled",
6036        );
6037        assert_eq!(
6038            enrolled_user_clearance_for_issue(IssueTokenProfile::Rfc7523, false, did, &resolver,),
6039            None,
6040            "the independent JWT-bearer profile keeps its existing behavior",
6041        );
6042        assert_eq!(
6043            enrolled_user_clearance_for_issue(IssueTokenProfile::Rfc8693, true, did, &resolver,),
6044            Some(label),
6045            "required-clearance behavior remains authority-derived",
6046        );
6047    }
6048
6049    #[tokio::test]
6050    async fn service_subject_rejects_noninteractive_user_profile() {
6051        let (service, _root) = test_service().await;
6052        let ctx = EnvelopeContext::from_callback_service(1, "test-caller");
6053        let mut request = issue("service:model");
6054        request.issuance_profile = IssueTokenProfile::Rfc8693;
6055
6056        let response = service
6057            .handle_issue_token(&ctx, 1, &request)
6058            .await
6059            .expect("profile-mismatch denial is a policy response");
6060        assert!(matches!(
6061            response,
6062            PolicyResponseVariant::Error(ErrorInfo { ref code, .. })
6063                if code == "INVALID_ISSUANCE_PROFILE"
6064        ));
6065    }
6066
6067    /// Process-global in-memory session registry for the issuance-profile
6068    /// tests (guarded/idempotent). `handle_issue_token` binds a supplied `sid`
6069    /// against the PROCESS-GLOBAL registry, so the interactive contracts are
6070    /// proven against that exact handle. `register_session`/`revoke_session`
6071    /// are trait methods, so registering through the returned `dyn` handle
6072    /// works regardless of which sibling test published the global first (both
6073    /// publish an InMemory registry and use distinct keys).
6074    fn interactive_test_session_registry(
6075    ) -> &'static std::sync::Arc<dyn hyprstream_rpc::auth::SessionRegistry> {
6076        if hyprstream_rpc::auth::global_session_registry().is_none() {
6077            let _ = hyprstream_rpc::auth::set_global_session_registry(std::sync::Arc::new(
6078                hyprstream_rpc::auth::InMemorySessionRegistry::new(),
6079            ));
6080        }
6081        hyprstream_rpc::auth::global_session_registry()
6082            .expect("session registry is published above")
6083    }
6084
6085    fn active_oidc_session(
6086        subject: &str,
6087        tenant: &str,
6088        now: i64,
6089    ) -> hyprstream_rpc::auth::SessionState {
6090        hyprstream_rpc::auth::SessionState {
6091            subject: subject.to_owned(),
6092            tenant: tenant.to_owned(),
6093            kind: hyprstream_rpc::auth::SessionKind::Interactive,
6094            created_at: now,
6095            expires_at: now + 3600,
6096            status: hyprstream_rpc::auth::ActiveOrRevoked::Active,
6097            clearance_epoch: 0,
6098        }
6099    }
6100
6101    /// Contract 1 (empty sid): the interactive profile treats an empty-string
6102    /// `sid` exactly like a missing one — both deny before minting.
6103    #[tokio::test]
6104    async fn interactive_issue_token_rejects_empty_session_id() {
6105        let (service, _root) = test_service().await;
6106        let ctx = EnvelopeContext::from_callback_service(1, "test-caller");
6107        let mut request = issue("alice");
6108        request.issuance_profile = IssueTokenProfile::InteractiveSession;
6109        request.session_id = Some(String::new());
6110        let response = service
6111            .handle_issue_token(&ctx, 1, &request)
6112            .await
6113            .expect("empty-session denial is a policy response");
6114        assert!(
6115            matches!(
6116                response,
6117                PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "MISSING_SESSION"
6118            ),
6119            "an empty sid must deny like a missing one: {response:?}"
6120        );
6121    }
6122
6123    /// Contract 3: an interactive credential whose `sid` names a registered,
6124    /// ACTIVE session bound to this exact subject and tenant mints, and the
6125    /// registered `sid` is stamped into the signed claims.
6126    #[tokio::test]
6127    async fn interactive_issue_token_with_registered_session_succeeds() {
6128        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
6129        let (service, _root) = test_service().await;
6130        let user_ed = SigningKey::from_bytes(&[0x89; 32]);
6131        let service = service.with_primary_enrollment_resolver(v16_primary_resolver(
6132            "alice",
6133            user_ed.verifying_key().to_bytes(),
6134        ));
6135        let reg = interactive_test_session_registry();
6136        let ctx = EnvelopeContext::from_callback_service(1, "test-caller");
6137        let issuer = "https://issuer.interactive-ok.test";
6138        let tenant = "tenant-interactive-ok";
6139        let sid = "sid-interactive-ok";
6140        let now = chrono::Utc::now().timestamp();
6141        reg.register_session(
6142            hyprstream_rpc::auth::SessionKey::oidc(issuer, sid),
6143            active_oidc_session("alice", tenant, now),
6144        )
6145        .await
6146        .expect("register active session");
6147
6148        let mut request = issue("alice");
6149        request.issuance_profile = IssueTokenProfile::InteractiveSession;
6150        request.issuer = Some(issuer.to_owned());
6151        request.tenant = Some(tenant.to_owned());
6152        request.session_id = Some(sid.to_owned());
6153        request.user_pub_key = Some(URL_SAFE_NO_PAD.encode(user_ed.verifying_key().to_bytes()));
6154        let response = service
6155            .handle_issue_token(&ctx, 1, &request)
6156            .await
6157            .expect("interactive issuance is a policy response");
6158        match response {
6159            PolicyResponseVariant::IssueTokenResult(info) => {
6160                let claims = hyprstream_rpc::auth::decode_unverified(&info.token)
6161                    .expect("issued token decodes");
6162                assert_eq!(
6163                    claims.sid.as_deref(),
6164                    Some(sid),
6165                    "the registered sid is stamped into the minted claims"
6166                );
6167            }
6168            // test_service provisions no global composite signing authority, so
6169            // a mint that clears the session gate fails at the signing boundary
6170            // instead. Reaching it proves the correctly-registered session was
6171            // ACCEPTED (the contract here); the sid-stamping assertion above is
6172            // exercised whenever the full-suite run provisions signing.
6173            PolicyResponseVariant::Error(ErrorInfo { ref code, .. })
6174                if code == "SIGNING_NOT_CONFIGURED" => {}
6175            other => panic!("a correctly-registered interactive session was rejected: {other:?}"),
6176        }
6177    }
6178
6179    /// Contract 2: an interactive `sid` that is unknown, revoked, or bound to a
6180    /// different subject/tenant is rejected — the registry is the authority and
6181    /// there is no session fixation.
6182    #[tokio::test]
6183    async fn interactive_issue_token_denies_unknown_revoked_or_mismatched_session() {
6184        let (service, _root) = test_service().await;
6185        let reg = interactive_test_session_registry();
6186        let ctx = EnvelopeContext::from_callback_service(1, "test-caller");
6187        let issuer = "https://issuer.interactive-deny.test";
6188        let tenant = "tenant-interactive-deny";
6189        let now = chrono::Utc::now().timestamp();
6190
6191        let request_for = |sid: &str| {
6192            let mut r = issue("alice");
6193            r.issuance_profile = IssueTokenProfile::InteractiveSession;
6194            r.issuer = Some(issuer.to_owned());
6195            r.tenant = Some(tenant.to_owned());
6196            r.session_id = Some(sid.to_owned());
6197            r
6198        };
6199        let assert_denied = |response: PolicyResponseVariant, label: &str| {
6200            assert!(
6201                matches!(
6202                    response,
6203                    PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "INVALID_SESSION"
6204                ),
6205                "{label} must deny with INVALID_SESSION: {response:?}"
6206            );
6207        };
6208
6209        // Unknown: never registered.
6210        assert_denied(
6211            service
6212                .handle_issue_token(&ctx, 1, &request_for("never-registered"))
6213                .await
6214                .unwrap(),
6215            "an unknown sid",
6216        );
6217
6218        // Revoked: registered then revoked.
6219        let revoked = "sid-revoked";
6220        reg.register_session(
6221            hyprstream_rpc::auth::SessionKey::oidc(issuer, revoked),
6222            active_oidc_session("alice", tenant, now),
6223        )
6224        .await
6225        .unwrap();
6226        reg.revoke_session(&hyprstream_rpc::auth::SessionKey::oidc(issuer, revoked))
6227            .await
6228            .unwrap();
6229        assert_denied(
6230            service
6231                .handle_issue_token(&ctx, 2, &request_for(revoked))
6232                .await
6233                .unwrap(),
6234            "a revoked sid",
6235        );
6236
6237        // Mismatched subject: session bound to a different user.
6238        let cross_subject = "sid-cross-subject";
6239        reg.register_session(
6240            hyprstream_rpc::auth::SessionKey::oidc(issuer, cross_subject),
6241            active_oidc_session("bob", tenant, now),
6242        )
6243        .await
6244        .unwrap();
6245        assert_denied(
6246            service
6247                .handle_issue_token(&ctx, 3, &request_for(cross_subject))
6248                .await
6249                .unwrap(),
6250            "a cross-subject sid",
6251        );
6252
6253        // Mismatched tenant: session bound to a different tenant.
6254        let cross_tenant = "sid-cross-tenant";
6255        reg.register_session(
6256            hyprstream_rpc::auth::SessionKey::oidc(issuer, cross_tenant),
6257            active_oidc_session("alice", "some-other-tenant", now),
6258        )
6259        .await
6260        .unwrap();
6261        assert_denied(
6262            service
6263                .handle_issue_token(&ctx, 4, &request_for(cross_tenant))
6264                .await
6265                .unwrap(),
6266            "a cross-tenant sid",
6267        );
6268    }
6269
6270    /// Contract 4: a service subject can never acquire a user session — neither
6271    /// under the service profile carrying a `sid`, nor by relabeling itself
6272    /// interactive. Both deny at the profile gate before any registry lookup.
6273    #[tokio::test]
6274    async fn service_subject_with_user_session_is_denied() {
6275        let (service, _root) = test_service().await;
6276        let ctx = EnvelopeContext::from_callback_service(1, "test-caller");
6277
6278        let mut service_profile = issue("service:model");
6279        service_profile.issuance_profile = IssueTokenProfile::Service;
6280        service_profile.session_id = Some("sid-illegal".to_owned());
6281        let response = service
6282            .handle_issue_token(&ctx, 1, &service_profile)
6283            .await
6284            .unwrap();
6285        assert!(
6286            matches!(
6287                response,
6288                PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "INVALID_ISSUANCE_PROFILE"
6289            ),
6290            "service profile + sid must deny: {response:?}"
6291        );
6292
6293        let mut relabeled = issue("service:model");
6294        relabeled.issuance_profile = IssueTokenProfile::InteractiveSession;
6295        relabeled.session_id = Some("sid-illegal".to_owned());
6296        let response = service
6297            .handle_issue_token(&ctx, 2, &relabeled)
6298            .await
6299            .unwrap();
6300        assert!(
6301            matches!(
6302                response,
6303                PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "INVALID_ISSUANCE_PROFILE"
6304            ),
6305            "a service subject relabeled interactive must deny: {response:?}"
6306        );
6307    }
6308
6309    /// Contract 5 (negative): the non-interactive RFC profiles cannot smuggle a
6310    /// session, and a non-interactive exchange cannot relabel itself
6311    /// interactive to bypass session verification — a fabricated (unregistered)
6312    /// sid denies, and an absent sid denies for want of a registered session.
6313    #[tokio::test]
6314    async fn noninteractive_profiles_cannot_smuggle_or_relabel_a_session() {
6315        let (service, _root) = test_service().await;
6316        // Ensure the registry is initialized so the relabel case reaches
6317        // INVALID_SESSION rather than an UNAVAILABLE registry error.
6318        let _ = interactive_test_session_registry();
6319        let ctx = EnvelopeContext::from_callback_service(1, "test-caller");
6320
6321        for profile in [IssueTokenProfile::Rfc8693, IssueTokenProfile::Rfc7523] {
6322            let mut smuggle = issue("alice");
6323            smuggle.issuance_profile = profile;
6324            smuggle.session_id = Some("smuggled-sid".to_owned());
6325            let response = service.handle_issue_token(&ctx, 1, &smuggle).await.unwrap();
6326            assert!(
6327                matches!(
6328                    response,
6329                    PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "INVALID_SESSION"
6330                ),
6331                "an RFC profile carrying a sid must deny: {response:?}"
6332            );
6333        }
6334
6335        // Relabel to interactive with a fabricated, unregistered sid → denied.
6336        let mut fabricated = issue("alice");
6337        fabricated.issuance_profile = IssueTokenProfile::InteractiveSession;
6338        fabricated.issuer = Some("https://issuer.relabel.test".to_owned());
6339        fabricated.session_id = Some("fabricated-unregistered".to_owned());
6340        let response = service
6341            .handle_issue_token(&ctx, 2, &fabricated)
6342            .await
6343            .unwrap();
6344        assert!(
6345            matches!(
6346                response,
6347                PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "INVALID_SESSION"
6348            ),
6349            "relabel with a fabricated sid must deny: {response:?}"
6350        );
6351
6352        // Relabel to interactive with no sid → denied for want of a session.
6353        let mut no_sid = issue("alice");
6354        no_sid.issuance_profile = IssueTokenProfile::InteractiveSession;
6355        no_sid.session_id = None;
6356        let response = service.handle_issue_token(&ctx, 3, &no_sid).await.unwrap();
6357        assert!(
6358            matches!(
6359                response,
6360                PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "MISSING_SESSION"
6361            ),
6362            "relabel without a sid must deny: {response:?}"
6363        );
6364    }
6365
6366    /// Gate 2 (v16 §3.3): a carried `workload_session_id` must be ACTIVE before
6367    /// a service credential may renew. A revoked family session DENIES the
6368    /// renewal — the revocation is checked BEFORE the enrollment-policy branch,
6369    /// so removing the workload-family policy (family narrowing) can never let
6370    /// a revoked family renew into an unsessioned credential.
6371    #[tokio::test]
6372    async fn revoked_workload_session_denies_service_renewal() {
6373        let (service, _root) = test_service().await;
6374        let service = service.with_default_audience("https://issuer.gate2.test".to_owned());
6375        let issuer = "https://issuer.gate2.test";
6376        let reg = interactive_test_session_registry();
6377        let now = chrono::Utc::now().timestamp();
6378        let wsid = "wl-gate2-revoked";
6379
6380        // Register then revoke the workload family session.
6381        let workload_key = hyprstream_rpc::auth::SessionKey::workload(issuer, wsid);
6382        reg.register_session(
6383            workload_key.clone(),
6384            hyprstream_rpc::auth::SessionState {
6385                subject: "service:model".to_owned(),
6386                tenant: "tenant-a".to_owned(),
6387                kind: hyprstream_rpc::auth::SessionKind::Workload,
6388                created_at: now,
6389                expires_at: now + 3600,
6390                status: hyprstream_rpc::auth::ActiveOrRevoked::Active,
6391                clearance_epoch: 0,
6392            },
6393        )
6394        .await
6395        .unwrap();
6396        reg.revoke_session(&workload_key).await.unwrap();
6397
6398        // The renewing caller's key must be trust-registered for the service.
6399        let caller = SigningKey::generate(&mut rand::rngs::OsRng).verifying_key();
6400        let trust = hyprstream_service::global_trust_store();
6401        trust.insert(
6402            caller,
6403            hyprstream_service::Attestation {
6404                scopes: std::iter::once("model".to_owned()).collect(),
6405                subject: None,
6406                jwt: Some("gate2-renew".to_owned()),
6407                expires_at: now + 300,
6408                attested_by: None,
6409            },
6410        );
6411
6412        // The presented credential carries the now-revoked workload session.
6413        let carried =
6414            hyprstream_rpc::auth::Claims::new("service:model".to_owned(), now, now + 3600)
6415                .with_workload_session_id(wsid);
6416        let ctx = EnvelopeContext::for_test_authenticated_subject_with_claims(
6417            Subject::new("service:model"),
6418            "tenant-a",
6419            caller,
6420            carried,
6421        );
6422
6423        let response = service
6424            .handle_refresh_service_token(
6425                &ctx,
6426                1,
6427                &RefreshServiceTokenRequest { ttl_seconds: 3600 },
6428            )
6429            .await
6430            .expect("refresh is a policy response");
6431        trust.remove(&caller);
6432        assert!(
6433            matches!(
6434                response,
6435                PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "SESSION_REVOKED"
6436            ),
6437            "a carried revoked workload session must deny renewal: {response:?}"
6438        );
6439    }
6440
6441    /// Gate 2 check-BEFORE-narrowing (v16 §3.3): the sibling of the test above,
6442    /// closing the case that one could not reach. Here an authoritative manifest
6443    /// enrolls the family with `workload_session = false` (policy REMOVED), so
6444    /// `family_allowed` is `false` and renewal takes the deliberate-narrowing
6445    /// branch `(Some(wsid), false)` — the session ID is dropped, not re-stamped.
6446    /// A revoked family session must STILL deny the renewal: the revocation is
6447    /// checked before the narrowing branch, so removing the family policy can
6448    /// never launder a revoked family into an unsessioned credential. The prior
6449    /// test only reaches `(Some(wsid), true)` because, with no manifest,
6450    /// `family_allowed` defaults to `true`.
6451    #[tokio::test]
6452    async fn revoked_session_with_removed_family_policy_still_denies_renewal() {
6453        // The caller/enrolled key is shared: the renewal path resolves the
6454        // signer suite against the injected manifest (the block above the
6455        // workload branch), which requires the verified `cnf` key to equal the
6456        // enrolled ed25519 key. Match them so renewal reaches the workload gate.
6457        let caller_sk = SigningKey::from_bytes(&[0x2b; 32]);
6458        let caller = caller_sk.verifying_key();
6459
6460        let (service, _root) = test_service().await;
6461        let service = service
6462            .with_default_audience("https://issuer.gate2.test".to_owned())
6463            // Authoritative family policy REMOVED: `v16_service_manifest` enrolls
6464            // "model" with `workload_session = false`. Injected (not global) so
6465            // the process-global manifest is untouched — the renewal path now
6466            // reads this same injected authority for clearance, signer-suite,
6467            // AND the workload-family policy.
6468            .with_enrollment_manifest(v16_service_manifest("model", caller.to_bytes()));
6469        let issuer = "https://issuer.gate2.test";
6470        let reg = interactive_test_session_registry();
6471        let now = chrono::Utc::now().timestamp();
6472        let wsid = "wl-gate2-narrowed-revoked";
6473
6474        // Register then revoke the workload family session.
6475        let workload_key = hyprstream_rpc::auth::SessionKey::workload(issuer, wsid);
6476        reg.register_session(
6477            workload_key.clone(),
6478            hyprstream_rpc::auth::SessionState {
6479                subject: "service:model".to_owned(),
6480                tenant: "tenant-a".to_owned(),
6481                kind: hyprstream_rpc::auth::SessionKind::Workload,
6482                created_at: now,
6483                expires_at: now + 3600,
6484                status: hyprstream_rpc::auth::ActiveOrRevoked::Active,
6485                clearance_epoch: 0,
6486            },
6487        )
6488        .await
6489        .unwrap();
6490        reg.revoke_session(&workload_key).await.unwrap();
6491
6492        // The renewing caller's key must be trust-registered for the service.
6493        let trust = hyprstream_service::global_trust_store();
6494        trust.insert(
6495            caller,
6496            hyprstream_service::Attestation {
6497                scopes: std::iter::once("model".to_owned()).collect(),
6498                subject: None,
6499                jwt: Some("gate2-narrow-renew".to_owned()),
6500                expires_at: now + 300,
6501                attested_by: None,
6502            },
6503        );
6504
6505        // The presented credential carries the now-revoked workload session.
6506        let carried =
6507            hyprstream_rpc::auth::Claims::new("service:model".to_owned(), now, now + 3600)
6508                .with_workload_session_id(wsid);
6509        let ctx = EnvelopeContext::for_test_authenticated_subject_with_claims(
6510            Subject::new("service:model"),
6511            "tenant-a",
6512            caller,
6513            carried,
6514        );
6515
6516        let response = service
6517            .handle_refresh_service_token(
6518                &ctx,
6519                1,
6520                &RefreshServiceTokenRequest { ttl_seconds: 3600 },
6521            )
6522            .await
6523            .expect("refresh is a policy response");
6524        trust.remove(&caller);
6525        assert!(
6526            matches!(
6527                response,
6528                PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "SESSION_REVOKED"
6529            ),
6530            "removing the family policy must not launder a revoked session into an \
6531             unsessioned renewal — revocation is checked before narrowing: {response:?}"
6532        );
6533    }
6534
6535    /// Testability guard for the two tests above: proves the renewal path reads
6536    /// the INJECTED (`self.enrollment()`) manifest, not `global_service_enrollment()`
6537    /// alone. Without this routing, an injected `workload_session = false` family
6538    /// could never take effect in an isolated test (the process-global manifest
6539    /// is unset), so `family_allowed` would silently default to `true` and the
6540    /// narrowing branch above would be unreachable — a false green.
6541    ///
6542    /// The observable: an injected manifest enrolls "model" with an ed25519 key
6543    /// that DIFFERS from the renewing caller's verified `cnf` key. The renewal
6544    /// signer-suite block (which reads the same injected binding) then denies
6545    /// with `SIGNER_SUITE_UNAVAILABLE`. The pre-routing code read only the unset
6546    /// global manifest, skipped that block entirely, and would have reached the
6547    /// signing boundary (`SIGNING_NOT_CONFIGURED`) instead — so this exact code
6548    /// distinguishes "injected manifest consulted" from "not consulted".
6549    #[tokio::test]
6550    async fn service_renewal_consults_injected_enrollment_manifest() {
6551        let caller = SigningKey::from_bytes(&[0x2b; 32]).verifying_key();
6552        // Enroll "model" under a DIFFERENT key than the caller's verified cnf.
6553        let enrolled_other = SigningKey::from_bytes(&[0x5c; 32]).verifying_key();
6554
6555        let (service, _root) = test_service().await;
6556        let service = service
6557            .with_default_audience("https://issuer.gate2.test".to_owned())
6558            .with_enrollment_manifest(v16_service_manifest("model", enrolled_other.to_bytes()));
6559        let now = chrono::Utc::now().timestamp();
6560
6561        let trust = hyprstream_service::global_trust_store();
6562        trust.insert(
6563            caller,
6564            hyprstream_service::Attestation {
6565                scopes: std::iter::once("model".to_owned()).collect(),
6566                subject: None,
6567                jwt: Some("gate2-inject-renew".to_owned()),
6568                expires_at: now + 300,
6569                attested_by: None,
6570            },
6571        );
6572
6573        let ctx = EnvelopeContext::for_test_authenticated_subject_in_tenant(
6574            Subject::new("service:model"),
6575            "tenant-a",
6576            caller,
6577        );
6578        let response = service
6579            .handle_refresh_service_token(
6580                &ctx,
6581                1,
6582                &RefreshServiceTokenRequest { ttl_seconds: 3600 },
6583            )
6584            .await
6585            .expect("refresh is a policy response");
6586        trust.remove(&caller);
6587        assert!(
6588            matches!(
6589                response,
6590                PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "SIGNER_SUITE_UNAVAILABLE"
6591            ),
6592            "renewal must consult the injected manifest and reject a caller key that \
6593             disagrees with the enrolled key: {response:?}"
6594        );
6595    }
6596
6597    /// The DEFINITIVE causal coverage the two handler-level tests above cannot
6598    /// observe (`test_service` provisions no signing authority, so a cleared
6599    /// renewal stops at `SIGNING_NOT_CONFIGURED` before any token is minted).
6600    /// This exercises `resolve_renewal_workload_session` directly and inspects
6601    /// the exact disposition, proving the `(Some(wsid), false)` narrowing branch
6602    /// genuinely OMITS the session — and that the revocation check runs BEFORE
6603    /// narrowing, with revoked/expired/unknown all failing closed.
6604    #[tokio::test]
6605    async fn renewal_workload_decision_narrows_and_fails_closed() {
6606        let (service, _root) = test_service().await;
6607        let reg = interactive_test_session_registry();
6608        let now = chrono::Utc::now().timestamp();
6609        // A per-test issuer keeps these session keys off any other test's keys
6610        // in the shared global registry.
6611        let issuer = "https://issuer.narrow-decision.test";
6612        let active_state = |exp: i64| hyprstream_rpc::auth::SessionState {
6613            subject: "service:model".to_owned(),
6614            tenant: "tenant-a".to_owned(),
6615            kind: hyprstream_rpc::auth::SessionKind::Workload,
6616            created_at: now,
6617            expires_at: exp,
6618            status: hyprstream_rpc::auth::ActiveOrRevoked::Active,
6619            clearance_epoch: 0,
6620        };
6621        let decide = |fp: Option<bool>, wsid: Option<&'static str>| {
6622            service.resolve_renewal_workload_session(
6623                issuer,
6624                "service:model",
6625                "tenant-a",
6626                now,
6627                fp,
6628                wsid,
6629            )
6630        };
6631
6632        // Register one ACTIVE session used by the two contrasting live cases.
6633        let active = "wl-active-narrow";
6634        reg.register_session(
6635            hyprstream_rpc::auth::SessionKey::workload(issuer, active),
6636            active_state(now + 3600),
6637        )
6638        .await
6639        .unwrap();
6640
6641        // (1) OMISSION CONTROL — ACTIVE session, family policy REMOVED
6642        // (`Some(false)`): the LIVE session is dropped from the renewed
6643        // credential. This is the positive proof that `family_allowed = false`
6644        // actually narrows (not a vacuous always-None).
6645        assert!(
6646            matches!(
6647                decide(Some(false), Some(active)).await,
6648                RenewalWorkloadSession::Stamp(None)
6649            ),
6650            "active session + removed family policy must OMIT the workload_session_id"
6651        );
6652
6653        // (2) CONTRAST — the SAME active session, family still ENROLLED
6654        // (`Some(true)`): the session is re-stamped. Proves the false branch in
6655        // (1) is a real divergence, not a constant.
6656        assert!(
6657            matches!(
6658                decide(Some(true), Some(active)).await,
6659                RenewalWorkloadSession::Stamp(Some(ref w)) if w == active
6660            ),
6661            "active session + enrolled family must RE-STAMP the workload_session_id"
6662        );
6663
6664        // (3) CHECK-BEFORE-NARROWING — a REVOKED session denies for EVERY family
6665        // policy, including the narrowing `Some(false)`: removing the policy can
6666        // never launder a revoked family into an unsessioned renewal.
6667        let revoked = "wl-revoked-narrow";
6668        let rk = hyprstream_rpc::auth::SessionKey::workload(issuer, revoked);
6669        reg.register_session(rk.clone(), active_state(now + 3600))
6670            .await
6671            .unwrap();
6672        reg.revoke_session(&rk).await.unwrap();
6673        for fp in [Some(false), Some(true), None] {
6674            assert!(
6675                matches!(
6676                    decide(fp, Some(revoked)).await,
6677                    RenewalWorkloadSession::Deny { code, .. } if code == "SESSION_REVOKED"
6678                ),
6679                "a revoked carried session must deny renewal for family policy {fp:?}"
6680            );
6681        }
6682
6683        // (4) FAIL-CLOSED, unknown — a session that was never registered denies.
6684        assert!(
6685            matches!(
6686                decide(Some(true), Some("wl-never-registered-narrow")).await,
6687                RenewalWorkloadSession::Deny { code, .. } if code == "SESSION_REVOKED"
6688            ),
6689            "an unknown carried session must fail closed"
6690        );
6691
6692        // (5) FAIL-CLOSED, expired — an expired-but-Active session denies.
6693        let expired = "wl-expired-narrow";
6694        reg.register_session(
6695            hyprstream_rpc::auth::SessionKey::workload(issuer, expired),
6696            active_state(now - 1),
6697        )
6698        .await
6699        .unwrap();
6700        assert!(
6701            matches!(
6702                decide(Some(true), Some(expired)).await,
6703                RenewalWorkloadSession::Deny { code, .. } if code == "SESSION_REVOKED"
6704            ),
6705            "an expired carried session must fail closed"
6706        );
6707
6708        // (6) No carried session: a disabled (`Some(false)`) or legacy (`None`)
6709        // family manufactures none.
6710        assert!(
6711            matches!(
6712                decide(Some(false), None).await,
6713                RenewalWorkloadSession::Stamp(None)
6714            ),
6715            "no session + disabled family stays unsessioned"
6716        );
6717        assert!(
6718            matches!(
6719                decide(None, None).await,
6720                RenewalWorkloadSession::Stamp(None)
6721            ),
6722            "no session + legacy family stays unsessioned"
6723        );
6724
6725        // (7) No carried session, family ENROLLED (`Some(true)`): a fresh session
6726        // is created, registered ACTIVE, and stamped.
6727        let created = decide(Some(true), None).await;
6728        let RenewalWorkloadSession::Stamp(Some(new_wsid)) = created else {
6729            panic!("an enrolled family with no carried session must create one: {created:?}");
6730        };
6731        assert!(
6732            !reg.is_revoked(&hyprstream_rpc::auth::SessionKey::workload(
6733                issuer, &new_wsid
6734            ))
6735            .await,
6736            "the freshly created workload session must be registered ACTIVE"
6737        );
6738    }
6739
6740    /// RFC 9068 §2.2.1 issuance (v16 credential profile): a user `at+jwt`
6741    /// profile without a non-empty `client_id` is denied; a service profile
6742    /// carrying a `client_id` is denied; and a supplied `client_id` is stamped
6743    /// into the minted `at+jwt` claims (the emitter positive).
6744    #[tokio::test]
6745    async fn issuance_enforces_and_stamps_client_id() {
6746        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
6747        let (service, _root) = test_service().await;
6748        // v16: a user at+jwt binds its authoritative Primary suite. Install the
6749        // resolver + a matching cnf key so the positive reaches the signing
6750        // boundary rather than the fail-closed Primary gate.
6751        let user_ed = SigningKey::from_bytes(&[0x88; 32]);
6752        let service = service.with_primary_enrollment_resolver(v16_primary_resolver(
6753            "alice",
6754            user_ed.verifying_key().to_bytes(),
6755        ));
6756        let ctx = EnvelopeContext::from_callback_service(1, "test-caller");
6757
6758        // User profile (RFC 8693) with a MISSING client_id → denied.
6759        let mut missing = issue("alice");
6760        missing.issuance_profile = IssueTokenProfile::Rfc8693;
6761        missing.client_id = None;
6762        let resp = service.handle_issue_token(&ctx, 1, &missing).await.unwrap();
6763        assert!(
6764            matches!(resp, PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "MISSING_CLIENT_ID"),
6765            "missing client_id: {resp:?}"
6766        );
6767
6768        // Empty/whitespace client_id → denied.
6769        let mut empty = issue("alice");
6770        empty.issuance_profile = IssueTokenProfile::Rfc8693;
6771        empty.client_id = Some("   ".to_owned());
6772        let resp = service.handle_issue_token(&ctx, 2, &empty).await.unwrap();
6773        assert!(
6774            matches!(resp, PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "MISSING_CLIENT_ID"),
6775            "empty client_id: {resp:?}"
6776        );
6777
6778        // Service (`wit+jwt`) profile carrying a client_id → denied.
6779        let mut svc_cid = issue("service:model");
6780        svc_cid.issuance_profile = IssueTokenProfile::Service;
6781        svc_cid.client_id = Some("hyprstream-oauth-client-1".to_owned());
6782        let resp = service.handle_issue_token(&ctx, 3, &svc_cid).await.unwrap();
6783        assert!(
6784            matches!(resp, PolicyResponseVariant::Error(ErrorInfo { ref code, .. }) if code == "INVALID_CLIENT_ID"),
6785            "service + client_id: {resp:?}"
6786        );
6787
6788        // Emitter positive: a supplied client_id is stamped into the minted
6789        // at+jwt (test_service may stop at the signing boundary; assert the
6790        // stamped value only when a token is actually produced).
6791        let mut ok = issue("alice");
6792        ok.issuance_profile = IssueTokenProfile::Rfc8693;
6793        ok.client_id = Some("hyprstream-oauth-client-1".to_owned());
6794        ok.user_pub_key = Some(URL_SAFE_NO_PAD.encode(user_ed.verifying_key().to_bytes()));
6795        match service.handle_issue_token(&ctx, 4, &ok).await.unwrap() {
6796            PolicyResponseVariant::IssueTokenResult(info) => {
6797                let claims = hyprstream_rpc::auth::decode_unverified(&info.token)
6798                    .expect("issued token decodes");
6799                assert_eq!(
6800                    claims.client_id.as_deref(),
6801                    Some("hyprstream-oauth-client-1"),
6802                    "the supplied client_id is stamped into the minted claims"
6803                );
6804            }
6805            // test_service configures no signing pair, so the flow stops at the
6806            // signing boundary AFTER passing the v16 Primary/client_id gates.
6807            PolicyResponseVariant::Error(ErrorInfo { ref code, .. })
6808                if code == "SIGNING_NOT_CONFIGURED" => {}
6809            other => panic!("unexpected issuance response: {other:?}"),
6810        }
6811    }
6812
6813    /// v16 fail-closed: a DISPATCH-CAPABLE user `at+jwt` (recoverable cnf.jwk)
6814    /// whose authoritative Primary cannot be resolved is denied before signing —
6815    /// no resolver installed, or a resolver whose key does not match the cnf.
6816    #[tokio::test]
6817    async fn dispatch_capable_user_issuance_without_primary_fails_closed() {
6818        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
6819        let user_ed = SigningKey::from_bytes(&[0x91; 32]);
6820        let user_pk = URL_SAFE_NO_PAD.encode(user_ed.verifying_key().to_bytes());
6821        let ctx = EnvelopeContext::from_callback_service(1, "test-caller");
6822
6823        // No resolver installed → fail closed.
6824        let (service, _root) = test_service().await;
6825        let mut req = issue("alice");
6826        req.issuance_profile = IssueTokenProfile::Rfc8693;
6827        req.user_pub_key = Some(user_pk.clone());
6828        let resp = service.handle_issue_token(&ctx, 1, &req).await.unwrap();
6829        assert_eq!(
6830            err_code_of(&resp),
6831            Some("PRIMARY_RESOLVER_UNAVAILABLE"),
6832            "no resolver must fail closed: {resp:?}"
6833        );
6834
6835        // Resolver returns a DIFFERENT key than the presented cnf → fail closed.
6836        let (service, _root) = test_service().await;
6837        let other = SigningKey::from_bytes(&[0x92; 32]);
6838        let service = service.with_primary_enrollment_resolver(v16_primary_resolver(
6839            "alice",
6840            other.verifying_key().to_bytes(),
6841        ));
6842        let mut req = issue("alice");
6843        req.issuance_profile = IssueTokenProfile::Rfc8693;
6844        req.user_pub_key = Some(user_pk);
6845        let resp = service.handle_issue_token(&ctx, 2, &req).await.unwrap();
6846        assert_eq!(
6847            err_code_of(&resp),
6848            Some("PRIMARY_UNRESOLVABLE"),
6849            "cnf/primary key mismatch must fail closed: {resp:?}"
6850        );
6851    }
6852
6853    fn err_code_of(resp: &PolicyResponseVariant) -> Option<&str> {
6854        match resp {
6855            PolicyResponseVariant::Error(ErrorInfo { code, .. }) => Some(code.as_str()),
6856            _ => None,
6857        }
6858    }
6859
6860    #[test]
6861    fn resolve_service_key_publishes_every_overlap_candidate() {
6862        let trust = hyprstream_service::TrustStore::new();
6863        let retired = SigningKey::generate(&mut rand::rngs::OsRng).verifying_key();
6864        let lead = SigningKey::generate(&mut rand::rngs::OsRng).verifying_key();
6865        let now = chrono::Utc::now().timestamp();
6866        trust.insert(retired, attestation(now + 60, "retired-attestation"));
6867        trust.insert(lead, attestation(0, "lead-attestation"));
6868
6869        let response = match published_service_key_response(&trust, "model") {
6870            Ok(response) => response,
6871            Err(error) => panic!("key set: {error}"),
6872        };
6873        assert!(response.verifying_key.is_empty(), "no singleton fallback");
6874        assert!(
6875            response.service_jwt.is_none(),
6876            "no singleton attestation fallback"
6877        );
6878        assert_eq!(
6879            response.keys.len(),
6880            2,
6881            "overlap keys must both be published"
6882        );
6883        assert!(response
6884            .keys
6885            .iter()
6886            .any(|entry| entry.verifying_key == retired.to_bytes()));
6887        assert!(response
6888            .keys
6889            .iter()
6890            .any(|entry| entry.verifying_key == lead.to_bytes()));
6891        assert!(response
6892            .keys
6893            .iter()
6894            .all(|entry| entry.key_id.starts_with("ed25519:")));
6895        assert!(response
6896            .keys
6897            .iter()
6898            .all(|entry| entry.service_jwt.is_none()));
6899    }
6900
6901    #[test]
6902    fn registration_requires_matching_present_confirmation_key() {
6903        let key = SigningKey::generate(&mut rand::rngs::OsRng).verifying_key();
6904        let now = chrono::Utc::now().timestamp();
6905        let claims = hyprstream_rpc::auth::Claims::new("service:model".to_owned(), now, now + 60);
6906        assert!(validate_service_key_registration(&claims, "model", key.as_bytes()).is_err());
6907
6908        let bound = claims.with_cnf_jwk(key.as_bytes());
6909        assert!(validate_service_key_registration(&bound, "model", key.as_bytes()).is_ok());
6910
6911        let sibling = SigningKey::generate(&mut rand::rngs::OsRng).verifying_key();
6912        assert!(validate_service_key_registration(&bound, "model", sibling.as_bytes()).is_err());
6913    }
6914
6915    #[test]
6916    fn one_key_response_projects_verification_key_but_never_credential() {
6917        let trust = hyprstream_service::TrustStore::new();
6918        let key = SigningKey::generate(&mut rand::rngs::OsRng).verifying_key();
6919        trust.insert(
6920            key,
6921            attestation(chrono::Utc::now().timestamp() + 60, "certificate"),
6922        );
6923
6924        let response = match published_service_key_response(&trust, "model") {
6925            Ok(response) => response,
6926            Err(error) => panic!("one-key response: {error}"),
6927        };
6928        assert_eq!(response.keys.len(), 1);
6929        assert_eq!(response.verifying_key, key.to_bytes());
6930        assert!(response.service_jwt.is_none());
6931        assert!(response.keys[0].service_jwt.is_none());
6932    }
6933
6934    #[tokio::test]
6935    async fn issue_token_returns_structured_errors_for_invalid_service_keys() {
6936        let (service, _root) = test_service().await;
6937        let mut ctx = EnvelopeContext::from_callback_service(1, "rotation-error-test");
6938        ctx.cnf = SigningKey::generate(&mut rand::rngs::OsRng)
6939            .verifying_key()
6940            .to_bytes();
6941
6942        let mut request = issue("service:rotation-error-test");
6943        request.issuance_profile = IssueTokenProfile::Service;
6944        request.client_id = None;
6945        request.user_pub_key = Some("not-base64url!".to_owned());
6946        let malformed = service
6947            .handle_issue_token(&ctx, 1, &request)
6948            .await
6949            .expect("malformed assertion key is a policy response");
6950        assert!(matches!(
6951            malformed,
6952            PolicyResponseVariant::Error(ErrorInfo { ref code, .. })
6953                if code == "INVALID_ASSERTION_KEY"
6954        ));
6955
6956        let requested = SigningKey::generate(&mut rand::rngs::OsRng).verifying_key();
6957        request.user_pub_key = Some(URL_SAFE_NO_PAD.encode(requested.as_bytes()));
6958        let unauthorized = service
6959            .handle_issue_token(&ctx, 2, &request)
6960            .await
6961            .expect("unregistered sibling is a policy response");
6962        assert!(matches!(
6963            unauthorized,
6964            PolicyResponseVariant::Error(ErrorInfo { ref code, .. })
6965                if code == "UNAUTHORIZED_SERVICE_KEY"
6966        ));
6967    }
6968
6969    #[tokio::test]
6970    async fn registered_sibling_reaches_service_token_signing_boundary() {
6971        let (service, _root) = test_service().await;
6972        let caller = SigningKey::generate(&mut rand::rngs::OsRng).verifying_key();
6973        let requested = SigningKey::generate(&mut rand::rngs::OsRng).verifying_key();
6974        // v16: the service credential binds its enrolled signer suite; enroll
6975        // the service to the attested assertion key so the suite resolves.
6976        let service = service.with_enrollment_manifest(v16_service_manifest(
6977            "rotation-sibling-test",
6978            requested.to_bytes(),
6979        ));
6980        let trust = hyprstream_service::global_trust_store();
6981        trust.insert(
6982            caller,
6983            hyprstream_service::Attestation {
6984                scopes: std::iter::once("rotation-sibling-test".to_owned()).collect(),
6985                subject: None,
6986                jwt: Some("registered-sibling".to_owned()),
6987                expires_at: chrono::Utc::now().timestamp() + 60,
6988                attested_by: None,
6989            },
6990        );
6991
6992        let mut ctx = EnvelopeContext::from_callback_service(1, "rotation-sibling-test");
6993        ctx.cnf = caller.to_bytes();
6994        let mut request = issue("service:rotation-sibling-test");
6995        request.issuance_profile = IssueTokenProfile::Service;
6996        request.client_id = None;
6997        request.user_pub_key = Some(URL_SAFE_NO_PAD.encode(requested.as_bytes()));
6998        let response = service.handle_issue_token(&ctx, 1, &request).await;
6999        trust.remove(&caller);
7000
7001        match response.expect("registered sibling reaches the signing boundary") {
7002            PolicyResponseVariant::IssueTokenResult(info) => {
7003                let claims = hyprstream_rpc::auth::decode_unverified(&info.token)
7004                    .expect("issued service token decodes");
7005                assert_eq!(claims.cnf_key_bytes(), Some(requested.to_bytes()));
7006            }
7007            PolicyResponseVariant::Error(ErrorInfo { code, .. })
7008                if code == "SIGNING_NOT_CONFIGURED" => {}
7009            other => panic!("registered sibling was rejected before signing: {other:?}"),
7010        }
7011    }
7012}
7013
7014#[cfg(test)]
7015mod event_prefix_registry_tests {
7016    #![allow(clippy::unwrap_used)]
7017    use super::*;
7018
7019    fn state(owner: &str, key: u8) -> EventPrefixState {
7020        EventPrefixState {
7021            owner: owner.to_owned(),
7022            publisher_pubkey: [key; 32],
7023            schema: String::new(),
7024            subscriber_pubkeys: HashMap::new(),
7025            wrapped_keys: HashMap::new(),
7026        }
7027    }
7028
7029    #[test]
7030    fn tenant_scoping_refuses_shadowing_and_takeover() {
7031        let a = EventPrefixKey::new("tenant-a".to_owned(), "orders");
7032        let b = EventPrefixKey::new("tenant-b".to_owned(), "orders");
7033        let shadow = EventPrefixKey::new("tenant-b".to_owned(), "orders.created");
7034        let mut prefixes = HashMap::new();
7035        validate_event_prefix_registration(&prefixes, &a, "subject-a").unwrap();
7036        prefixes.insert(a.clone(), state("subject-a", 0x0A));
7037        validate_event_prefix_registration(&prefixes, &b, "subject-b").unwrap();
7038        prefixes.insert(b.clone(), state("subject-b", 0x0B));
7039        assert_eq!(prefixes[&a].publisher_pubkey, [0x0A; 32]);
7040        assert_eq!(prefixes[&b].publisher_pubkey, [0x0B; 32]);
7041        assert_eq!(
7042            validate_event_prefix_registration(&prefixes, &shadow, "subject-b"),
7043            Err(EventPrefixRegistrationError::CrossTenantShadow)
7044        );
7045        assert_eq!(
7046            validate_event_prefix_registration(&prefixes, &a, "subject-b"),
7047            Err(EventPrefixRegistrationError::OwnedByAnotherSubject)
7048        );
7049    }
7050}
7051
7052// ── ExchangeDelegated (AsOriginator delegated mint) causal proofs ──
7053//
7054// Fully parallel-safe: source verification AND the output mint both resolve
7055// keys from the PolicyService's OWN injected `ClusterKeySource` composite
7056// ledger (never the process global), the enrollment manifest is injected via
7057// the cfg(test) setter, and the primary-enrollment resolver + edge authorizer
7058// are per-service mocks. No process-global state is published or mutated.
7059#[cfg(test)]
7060#[allow(clippy::unwrap_used, clippy::expect_used)]
7061mod exchange_delegated_tests {
7062    use super::*;
7063    use crate::auth::service_enrollment::{
7064        ServiceEnrollment, ServiceEnrollmentManifest, SERVICE_ENROLLMENT_VERSION,
7065    };
7066    use hyprstream_rpc::auth::mac::{
7067        Assurance, CompartmentSet, CredentialClearance, Level, SecurityLabel,
7068    };
7069    use hyprstream_rpc::auth::{
7070        ClusterKeySource, CompositeKeyPair, CompositeKeySet, CompositePairRole, CompositePairState,
7071    };
7072    use std::collections::BTreeMap;
7073    use std::sync::Arc;
7074
7075    const ISSUER: &str = "https://deleg.test";
7076    const TENANT: &str = "did:web:acme.example";
7077    const CLIENT_ID: &str = "hyprstream-oauth-client-1";
7078
7079    struct Fixture {
7080        service: PolicyService,
7081        ml_dsa: Arc<hyprstream_rpc::crypto::pq::MlDsaSigningKey>,
7082        ed: Arc<SigningKey>,
7083        actor_ed: SigningKey,
7084        user_ed: SigningKey,
7085        // Owned so per-path RAII removes exactly this fixture's scratch tree.
7086        _root: tempfile::TempDir,
7087    }
7088
7089    struct MockAuthorizer {
7090        allow: bool,
7091        require_source_aud: Option<String>,
7092        require_method: Option<String>,
7093    }
7094    impl DelegationEdgeAuthorizer for MockAuthorizer {
7095        fn authorize(&self, edge: &DelegationEdge<'_>) -> bool {
7096            self.allow
7097                && self
7098                    .require_source_aud
7099                    .as_deref()
7100                    .is_none_or(|w| edge.source_audience == Some(w))
7101                && self
7102                    .require_method
7103                    .as_deref()
7104                    .is_none_or(|w| edge.target_method_id == Some(w))
7105                && edge.target_method_id.is_some()
7106        }
7107    }
7108
7109    /// Authoritative primary resolver mock: returns the configured Ed key for
7110    /// `subject`, or `None` for anyone else (unknown ⇒ deny).
7111    struct MockPrimaryResolver {
7112        subject: String,
7113        ed25519: [u8; 32],
7114    }
7115    impl PrimaryEnrollmentResolver for MockPrimaryResolver {
7116        fn primary_group(&self, principal: &str, _tenant: &str) -> Option<PrimaryGroup> {
7117            (principal == self.subject).then(|| PrimaryGroup {
7118                suite_id: hyprstream_rpc::auth::SUITE_CLASSICAL_ED25519.to_owned(),
7119                ordered_component_keys: vec![self.ed25519.to_vec()],
7120            })
7121        }
7122    }
7123
7124    fn label() -> SecurityLabel {
7125        SecurityLabel::new(Level::Internal, Assurance::Classical, CompartmentSet::EMPTY)
7126    }
7127
7128    async fn fixture(
7129        authorizer: Option<Arc<dyn DelegationEdgeAuthorizer>>,
7130        resolver: Option<Arc<dyn PrimaryEnrollmentResolver>>,
7131    ) -> Fixture {
7132        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
7133        let ca = SigningKey::from_bytes(&[0x40; 32]);
7134        let ed = Arc::new(SigningKey::from_bytes(&[0x41; 32]));
7135        let (ml_dsa_sk, ml_dsa_vk) = hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair();
7136        let ml_dsa = Arc::new(ml_dsa_sk);
7137        let kid = hyprstream_rpc::auth::composite_kid(&ml_dsa_vk, &ed.verifying_key());
7138        let pair = CompositeKeyPair::signing(
7139            kid,
7140            ml_dsa.clone(),
7141            ed.clone(),
7142            CompositePairRole::Policy,
7143            CompositePairState::Active,
7144            0,
7145            i64::MAX,
7146        );
7147        // The service's OWN isolated authority: source verification AND the
7148        // output mint both resolve from this exact ledger.
7149        let root = tempfile::tempdir().unwrap();
7150        let key_set = Arc::new(CompositeKeySet::default());
7151        key_set
7152            .publish(1, "deleg-fixture".to_owned(), vec![pair])
7153            .unwrap();
7154        // Configure the isolated ledger as a disk-backed minting authority
7155        // (per-fixture, never the process global) so `sign_token` can mint
7156        // the output on the SAME ledger it verifies sources against.
7157        let auth = root.path().join("composite-authority");
7158        std::fs::create_dir_all(&auth).unwrap();
7159        let marker = serde_json::json!({ "version": 1, "component_digest": "deleg-fixture" });
7160        let ledger_path = auth.join("ledger.json");
7161        let committed_path = auth.join("committed.json");
7162        std::fs::write(&ledger_path, serde_json::to_vec(&marker).unwrap()).unwrap();
7163        std::fs::write(&committed_path, serde_json::to_vec(&marker).unwrap()).unwrap();
7164        key_set.configure_authority(
7165            ledger_path,
7166            committed_path,
7167            auth.join("ledger-prefix"),
7168            auth.join("ledger.lock"),
7169        );
7170        let key_source = ClusterKeySource::new(ca.verifying_key(), ISSUER.to_owned())
7171            .with_composite_key_set(key_set);
7172
7173        let actor_ed = SigningKey::from_bytes(&[0x42; 32]);
7174        let user_ed = SigningKey::from_bytes(&[0x43; 32]);
7175
7176        let mut services = BTreeMap::new();
7177        services.insert(
7178            "mcp".to_owned(),
7179            ServiceEnrollment {
7180                ed25519_pubkey: URL_SAFE_NO_PAD.encode(actor_ed.verifying_key().to_bytes()),
7181                ml_dsa_pubkey: None,
7182                clearance: label(),
7183                allowed_audiences: Some(vec!["res-b".to_owned()]),
7184                workload_session: false,
7185            },
7186        );
7187        let manifest = Arc::new(ServiceEnrollmentManifest {
7188            version: SERVICE_ENROLLMENT_VERSION,
7189            services,
7190        });
7191
7192        let git2db = Arc::new(RwLock::new(Git2DB::open(root.path()).await.unwrap()));
7193        let manager = Arc::new(PolicyManager::permissive().await.unwrap());
7194        let mut service = PolicyService::new(
7195            manager,
7196            Arc::new(ca),
7197            crate::config::TokenConfig::default(),
7198            git2db,
7199            TransportConfig::inproc("deleg-test"),
7200        )
7201        .with_default_audience(ISSUER.to_owned())
7202        .with_jwt_key_source(Arc::new(key_source))
7203        .with_enrollment_manifest(manifest);
7204        if let Some(a) = authorizer {
7205            service = service.with_delegation_edge_authorizer(a);
7206        }
7207        if let Some(r) = resolver {
7208            service = service.with_primary_enrollment_resolver(r);
7209        }
7210        Fixture {
7211            service,
7212            ml_dsa,
7213            ed,
7214            actor_ed,
7215            user_ed,
7216            _root: root,
7217        }
7218    }
7219
7220    fn allow_authorizer() -> Arc<dyn DelegationEdgeAuthorizer> {
7221        Arc::new(MockAuthorizer {
7222            allow: true,
7223            require_source_aud: None,
7224            require_method: None,
7225        })
7226    }
7227
7228    fn user_resolver(user_ed: &SigningKey) -> Arc<dyn PrimaryEnrollmentResolver> {
7229        Arc::new(MockPrimaryResolver {
7230            subject: "alice".to_owned(),
7231            ed25519: user_ed.verifying_key().to_bytes(),
7232        })
7233    }
7234
7235    fn sign_source(fx: &Fixture, claims: &hyprstream_rpc::auth::Claims) -> String {
7236        crate::auth::jwt::encode_composite_ml_dsa_65_ed25519(claims, &fx.ml_dsa, &fx.ed)
7237    }
7238
7239    /// A valid interactive user `at+jwt` source. Its `cnf.hs_signer_suite` is
7240    /// the suite over the AUTHORITATIVE primary key (the resolver's key), not
7241    /// a value the handler re-derives from the wire.
7242    fn user_source_claims(fx: &Fixture, now: i64) -> hyprstream_rpc::auth::Claims {
7243        let hs = hyprstream_rpc::auth::service_signer_suite_b64(
7244            &fx.user_ed.verifying_key().to_bytes(),
7245            None,
7246        );
7247        hyprstream_rpc::auth::Claims::new("alice".to_owned(), now, now + 3600)
7248            .with_issuer(ISSUER.to_owned())
7249            .with_tenant(TENANT.to_owned())
7250            .with_sid("sess-1")
7251            .with_client_id(CLIENT_ID)
7252            .with_scope(Some("read write".to_owned()))
7253            .with_clearance(label())
7254            .with_audience(Some("res-a".to_owned()))
7255            .with_cnf_jwk(&fx.user_ed.verifying_key().to_bytes())
7256            .with_cnf_hs_signer_suite(hs)
7257    }
7258
7259    fn actor_ctx(fx: &Fixture, now: i64) -> EnvelopeContext {
7260        let actor_claims =
7261            hyprstream_rpc::auth::Claims::new("service:mcp".to_owned(), now, now + 3600)
7262                .with_clearance(label());
7263        EnvelopeContext::for_test_authenticated_subject_with_claims(
7264            Subject::new("service:mcp"),
7265            TENANT,
7266            fx.actor_ed.verifying_key(),
7267            actor_claims,
7268        )
7269    }
7270
7271    fn session_registry() -> &'static Arc<dyn hyprstream_rpc::auth::SessionRegistry> {
7272        if hyprstream_rpc::auth::global_session_registry().is_none() {
7273            let _ = hyprstream_rpc::auth::set_global_session_registry(Arc::new(
7274                hyprstream_rpc::auth::InMemorySessionRegistry::new(),
7275            ));
7276        }
7277        hyprstream_rpc::auth::global_session_registry().expect("session registry published")
7278    }
7279
7280    async fn register_active_sid(now: i64) {
7281        let reg = session_registry();
7282        let key = hyprstream_rpc::auth::SessionKey::oidc(ISSUER, "sess-1");
7283        let _ = reg
7284            .register_session(
7285                key,
7286                hyprstream_rpc::auth::SessionState {
7287                    subject: "alice".to_owned(),
7288                    tenant: TENANT.to_owned(),
7289                    kind: hyprstream_rpc::auth::SessionKind::Interactive,
7290                    created_at: now,
7291                    expires_at: now + 3600,
7292                    status: hyprstream_rpc::auth::ActiveOrRevoked::Active,
7293                    clearance_epoch: 0,
7294                },
7295            )
7296            .await;
7297    }
7298
7299    fn ensure_revocation_store() {
7300        if hyprstream_rpc::auth::global_credential_revocation_store().is_none() {
7301            let _ = hyprstream_rpc::auth::set_global_credential_revocation_store(Arc::new(
7302                hyprstream_rpc::auth::InMemoryCredentialRevocationStore::new(),
7303            ));
7304        }
7305    }
7306
7307    fn request(source: String) -> ExchangeDelegated {
7308        ExchangeDelegated {
7309            source_credential: source,
7310            requested_scopes: Some("read".to_owned()),
7311            requested_capabilities: None,
7312            audience: Some("res-b".to_owned()),
7313            target_method_id: Some("model.Infer".to_owned()),
7314            ttl: Some(300),
7315        }
7316    }
7317
7318    fn err_code(resp: &PolicyResponseVariant) -> Option<&str> {
7319        match resp {
7320            PolicyResponseVariant::Error(ErrorInfo { code, .. }) => Some(code.as_str()),
7321            _ => None,
7322        }
7323    }
7324
7325    /// Happy path: a valid interactive user source + enrolled actor + allowing
7326    /// edge + authoritative primary resolver mints a delegated `at+jwt` whose
7327    /// `jti` is fresh (≠ source), `sub` is the originator, `act` nests the
7328    /// terminal actor, `cnf.hs_signer_suite` equals the ACTOR's authoritative
7329    /// suite (jwk preserved), clearance is the meet, scope is attenuated,
7330    /// client_id is inherited, and the active sid is retained.
7331    #[tokio::test]
7332    async fn delegated_mint_happy_path_stamps_expected_output() {
7333        ensure_revocation_store();
7334        let now = chrono::Utc::now().timestamp();
7335        register_active_sid(now).await;
7336        let fx = fixture(Some(allow_authorizer()), None).await;
7337        let resolver = user_resolver(&fx.user_ed);
7338        let fx = Fixture {
7339            service: fx.service.with_primary_enrollment_resolver(resolver),
7340            ..fx
7341        };
7342
7343        let source = sign_source(&fx, &user_source_claims(&fx, now));
7344        let source_jti = hyprstream_rpc::auth::decode_unverified(&source)
7345            .unwrap()
7346            .jti;
7347        let ctx = actor_ctx(&fx, now);
7348        let resp = fx
7349            .service
7350            .handle_exchange_delegated(&ctx, 1, &request(source))
7351            .await
7352            .unwrap();
7353
7354        let token = match resp {
7355            PolicyResponseVariant::ExchangeDelegatedResult(info) => info.token,
7356            other => panic!("expected a minted delegated token, got {other:?}"),
7357        };
7358        let minted = hyprstream_rpc::auth::decode_unverified(&token).unwrap();
7359        assert_eq!(minted.sub, "alice", "originator sub preserved");
7360        assert_ne!(minted.jti, source_jti, "fresh jti distinct from the source");
7361        assert!(minted.jti.is_some());
7362        let act = minted.act.expect("act chain present");
7363        assert_eq!(act.sub, "service:mcp", "terminal actor nested in act");
7364        let cnf = minted.cnf.expect("cnf present");
7365        let expected_actor_hs = hyprstream_rpc::auth::service_signer_suite_b64(
7366            &fx.actor_ed.verifying_key().to_bytes(),
7367            None,
7368        );
7369        assert_eq!(
7370            cnf.hs_signer_suite.as_deref(),
7371            Some(expected_actor_hs.as_str()),
7372            "cnf binds the terminal actor's authoritative signer suite"
7373        );
7374        assert!(cnf.jwk.is_some(), "legacy cnf.jwk preserved");
7375        assert_eq!(
7376            minted.clearance,
7377            Some(CredentialClearance::from_label(label())),
7378            "clearance is the meet"
7379        );
7380        assert_eq!(
7381            minted.scope.as_deref(),
7382            Some("read"),
7383            "scope attenuated to subset"
7384        );
7385        assert_eq!(
7386            minted.client_id.as_deref(),
7387            Some(CLIENT_ID),
7388            "client_id inherited"
7389        );
7390        assert_eq!(minted.sid.as_deref(), Some("sess-1"), "active sid retained");
7391        assert_eq!(minted.iss, ISSUER, "minted under the authority issuer");
7392    }
7393
7394    /// A first-hop delegated token (its `cnf` bound to the first terminal
7395    /// actor `service:worker`) is a valid SECOND-hop source: its `cnf`
7396    /// resolves against `act.sub` (the terminal actor enrollment), not `sub`.
7397    #[tokio::test]
7398    async fn two_hop_delegated_source_resolves_cnf_against_terminal_actor() {
7399        ensure_revocation_store();
7400        let now = chrono::Utc::now().timestamp();
7401        register_active_sid(now).await;
7402        let fx = fixture(
7403            Some(allow_authorizer()),
7404            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7405        )
7406        .await;
7407
7408        // The first-hop terminal actor is `service:worker`, enrolled with the
7409        // fixture's actor Ed key (reuse `mcp`'s key is fine — we add worker).
7410        // Build a source: sub = alice (originator), act = service:mcp (the
7411        // enrolled terminal actor), cnf bound to service:mcp's enrolled key.
7412        let actor_hs = hyprstream_rpc::auth::service_signer_suite_b64(
7413            &fx.actor_ed.verifying_key().to_bytes(),
7414            None,
7415        );
7416        let src_claims = hyprstream_rpc::auth::Claims::new("alice".to_owned(), now, now + 3600)
7417            .with_issuer(ISSUER.to_owned())
7418            .with_tenant(TENANT.to_owned())
7419            .with_sid("sess-1")
7420            .with_client_id(CLIENT_ID)
7421            .with_scope(Some("read".to_owned()))
7422            .with_clearance(label())
7423            .with_audience(Some("res-a".to_owned()))
7424            .with_act(hyprstream_rpc::auth::ActClaim {
7425                sub: "service:mcp".to_owned(),
7426                clearance: Some(CredentialClearance::from_label(label())),
7427                act: None,
7428            })
7429            .with_cnf_jwk(&fx.actor_ed.verifying_key().to_bytes())
7430            .with_cnf_hs_signer_suite(actor_hs);
7431        let source = sign_source(&fx, &src_claims);
7432        let ctx = actor_ctx(&fx, now);
7433        let resp = fx
7434            .service
7435            .handle_exchange_delegated(&ctx, 1, &request(source))
7436            .await
7437            .unwrap();
7438        // The source cnf validates against the terminal actor enrollment, so
7439        // the delegated mint proceeds to a token (not INVALID_SOURCE_CNF).
7440        assert!(
7441            matches!(resp, PolicyResponseVariant::ExchangeDelegatedResult(_)),
7442            "two-hop source cnf must resolve against act.sub, got {resp:?}"
7443        );
7444    }
7445
7446    /// The bound applies to the minted chain, including the new actor.
7447    #[tokio::test]
7448    async fn delegated_mint_reserves_terminal_actor_hop() {
7449        ensure_revocation_store();
7450        let now = chrono::Utc::now().timestamp();
7451        register_active_sid(now).await;
7452        let fx = fixture(Some(allow_authorizer()), None).await;
7453        let actor_hs = hyprstream_rpc::auth::service_signer_suite_b64(
7454            &fx.actor_ed.verifying_key().to_bytes(),
7455            None,
7456        );
7457        for existing_hops in [7, 8] {
7458            let mut chain = None;
7459            for index in 0..existing_hops {
7460                chain = Some(Box::new(hyprstream_rpc::auth::ActClaim {
7461                    sub: if index == existing_hops - 1 {
7462                        "service:mcp".to_owned()
7463                    } else {
7464                        format!("service:prior-{index}")
7465                    },
7466                    clearance: Some(CredentialClearance::from_label(label())),
7467                    act: chain,
7468                }));
7469            }
7470            let claims = user_source_claims(&fx, now)
7471                .with_act(*chain.expect("nonempty source chain"))
7472                .with_cnf_jwk(&fx.actor_ed.verifying_key().to_bytes())
7473                .with_cnf_hs_signer_suite(actor_hs.clone());
7474            let response = fx
7475                .service
7476                .handle_exchange_delegated(
7477                    &actor_ctx(&fx, now),
7478                    1,
7479                    &request(sign_source(&fx, &claims)),
7480                )
7481                .await
7482                .expect("exchange returns a response");
7483            if existing_hops == 8 {
7484                assert_eq!(err_code(&response), Some("MALFORMED_ACTOR_CHAIN"));
7485            } else {
7486                let PolicyResponseVariant::ExchangeDelegatedResult(info) = response else {
7487                    panic!("seven existing actors must permit one final actor");
7488                };
7489                let minted = hyprstream_rpc::auth::decode_unverified(&info.token)
7490                    .expect("issued token parses");
7491                let mut depth = 0;
7492                let mut actor = minted.act.as_ref();
7493                while let Some(hop) = actor {
7494                    depth += 1;
7495                    actor = hop.act.as_deref();
7496                }
7497                assert_eq!(depth, 8, "issued chain includes the new terminal actor");
7498            }
7499        }
7500    }
7501
7502    /// A user source whose primary is UNKNOWN to the resolver denies.
7503    #[tokio::test]
7504    async fn user_primary_unknown_denies() {
7505        ensure_revocation_store();
7506        let now = chrono::Utc::now().timestamp();
7507        register_active_sid(now).await;
7508        // Resolver only knows "someone-else", not "alice".
7509        let resolver: Arc<dyn PrimaryEnrollmentResolver> = Arc::new(MockPrimaryResolver {
7510            subject: "someone-else".to_owned(),
7511            ed25519: [0u8; 32],
7512        });
7513        let fx = fixture(Some(allow_authorizer()), Some(resolver)).await;
7514        let source = sign_source(&fx, &user_source_claims(&fx, now));
7515        let ctx = actor_ctx(&fx, now);
7516        let resp = fx
7517            .service
7518            .handle_exchange_delegated(&ctx, 1, &request(source))
7519            .await
7520            .unwrap();
7521        assert_eq!(err_code(&resp), Some("INVALID_SOURCE_CNF"));
7522    }
7523
7524    /// A user source whose presented `cnf.jwk` mismatches the resolved primary
7525    /// Ed key denies (the wire key never self-confirms).
7526    #[tokio::test]
7527    async fn user_primary_key_mismatch_denies() {
7528        ensure_revocation_store();
7529        let now = chrono::Utc::now().timestamp();
7530        register_active_sid(now).await;
7531        // Resolver returns a DIFFERENT key than the source's cnf.jwk.
7532        let resolver: Arc<dyn PrimaryEnrollmentResolver> = Arc::new(MockPrimaryResolver {
7533            subject: "alice".to_owned(),
7534            ed25519: SigningKey::from_bytes(&[0x55; 32])
7535                .verifying_key()
7536                .to_bytes(),
7537        });
7538        let fx = fixture(Some(allow_authorizer()), Some(resolver)).await;
7539        let source = sign_source(&fx, &user_source_claims(&fx, now));
7540        let ctx = actor_ctx(&fx, now);
7541        let resp = fx
7542            .service
7543            .handle_exchange_delegated(&ctx, 1, &request(source))
7544            .await
7545            .unwrap();
7546        assert_eq!(err_code(&resp), Some("INVALID_SOURCE_CNF"));
7547    }
7548
7549    /// An uninstalled primary resolver denies a user source (fail closed).
7550    #[tokio::test]
7551    async fn uninstalled_primary_resolver_denies_user_source() {
7552        ensure_revocation_store();
7553        let now = chrono::Utc::now().timestamp();
7554        register_active_sid(now).await;
7555        let fx = fixture(Some(allow_authorizer()), None).await; // no resolver
7556        let source = sign_source(&fx, &user_source_claims(&fx, now));
7557        let ctx = actor_ctx(&fx, now);
7558        let resp = fx
7559            .service
7560            .handle_exchange_delegated(&ctx, 1, &request(source))
7561            .await
7562            .unwrap();
7563        assert_eq!(err_code(&resp), Some("INVALID_SOURCE_CNF"));
7564    }
7565
7566    /// An uninstalled edge authorizer denies every delegation (fail closed).
7567    #[tokio::test]
7568    async fn uninstalled_edge_authorizer_denies() {
7569        ensure_revocation_store();
7570        let now = chrono::Utc::now().timestamp();
7571        register_active_sid(now).await;
7572        let fx = fixture(
7573            None,
7574            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7575        )
7576        .await;
7577        let source = sign_source(&fx, &user_source_claims(&fx, now));
7578        let ctx = actor_ctx(&fx, now);
7579        let resp = fx
7580            .service
7581            .handle_exchange_delegated(&ctx, 1, &request(source))
7582            .await
7583            .unwrap();
7584        assert_eq!(err_code(&resp), Some("EDGE_AUTHORIZER_UNAVAILABLE"));
7585    }
7586
7587    /// A cross-service source (source `aud` names another resource) is denied
7588    /// by the edge authorizer despite the actor's valid enrollment.
7589    #[tokio::test]
7590    async fn cross_service_source_audience_denies() {
7591        ensure_revocation_store();
7592        let now = chrono::Utc::now().timestamp();
7593        register_active_sid(now).await;
7594        let authz: Arc<dyn DelegationEdgeAuthorizer> = Arc::new(MockAuthorizer {
7595            allow: true,
7596            require_source_aud: Some("res-for-A".to_owned()),
7597            require_method: None,
7598        });
7599        let fx = fixture(
7600            Some(authz),
7601            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7602        )
7603        .await;
7604        let source = sign_source(&fx, &user_source_claims(&fx, now));
7605        let ctx = actor_ctx(&fx, now);
7606        let resp = fx
7607            .service
7608            .handle_exchange_delegated(&ctx, 1, &request(source))
7609            .await
7610            .unwrap();
7611        assert_eq!(err_code(&resp), Some("EDGE_DENIED"));
7612    }
7613
7614    /// A missing/empty target method id denies (no wildcard).
7615    #[tokio::test]
7616    async fn missing_target_method_denies() {
7617        ensure_revocation_store();
7618        let now = chrono::Utc::now().timestamp();
7619        register_active_sid(now).await;
7620        let fx = fixture(
7621            Some(allow_authorizer()),
7622            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7623        )
7624        .await;
7625        let source = sign_source(&fx, &user_source_claims(&fx, now));
7626        let mut req = request(source);
7627        req.target_method_id = Some("   ".to_owned());
7628        let ctx = actor_ctx(&fx, now);
7629        let resp = fx
7630            .service
7631            .handle_exchange_delegated(&ctx, 1, &req)
7632            .await
7633            .unwrap();
7634        assert_eq!(err_code(&resp), Some("TARGET_METHOD_REQUIRED"));
7635    }
7636
7637    /// Requested scope that broadens the source scope is denied.
7638    #[tokio::test]
7639    async fn scope_broadening_denies() {
7640        ensure_revocation_store();
7641        let now = chrono::Utc::now().timestamp();
7642        register_active_sid(now).await;
7643        let fx = fixture(
7644            Some(allow_authorizer()),
7645            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7646        )
7647        .await;
7648        let source = sign_source(&fx, &user_source_claims(&fx, now));
7649        let mut req = request(source);
7650        req.requested_scopes = Some("read admin".to_owned());
7651        let ctx = actor_ctx(&fx, now);
7652        let resp = fx
7653            .service
7654            .handle_exchange_delegated(&ctx, 1, &req)
7655            .await
7656            .unwrap();
7657        assert_eq!(err_code(&resp), Some("SCOPE_ATTENUATION"));
7658    }
7659
7660    /// A non-service caller cannot be a terminal actor.
7661    #[tokio::test]
7662    async fn non_service_actor_denies() {
7663        ensure_revocation_store();
7664        let now = chrono::Utc::now().timestamp();
7665        let fx = fixture(
7666            Some(allow_authorizer()),
7667            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7668        )
7669        .await;
7670        let source = sign_source(&fx, &user_source_claims(&fx, now));
7671        let user_claims = hyprstream_rpc::auth::Claims::new("bob".to_owned(), now, now + 3600)
7672            .with_clearance(label());
7673        let ctx = EnvelopeContext::for_test_authenticated_subject_with_claims(
7674            Subject::new("bob"),
7675            TENANT,
7676            fx.actor_ed.verifying_key(),
7677            user_claims,
7678        );
7679        let resp = fx
7680            .service
7681            .handle_exchange_delegated(&ctx, 1, &request(source))
7682            .await
7683            .unwrap();
7684        assert_eq!(err_code(&resp), Some("NOT_A_TERMINAL_ACTOR"));
7685    }
7686
7687    /// A source `at+jwt` with no sid (ambiguous non-interactive) is unsupported.
7688    #[tokio::test]
7689    async fn user_source_without_sid_is_unsupported() {
7690        ensure_revocation_store();
7691        let now = chrono::Utc::now().timestamp();
7692        let fx = fixture(
7693            Some(allow_authorizer()),
7694            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7695        )
7696        .await;
7697        let mut claims = user_source_claims(&fx, now);
7698        claims.sid = None;
7699        let source = sign_source(&fx, &claims);
7700        let ctx = actor_ctx(&fx, now);
7701        let resp = fx
7702            .service
7703            .handle_exchange_delegated(&ctx, 1, &request(source))
7704            .await
7705            .unwrap();
7706        assert_eq!(err_code(&resp), Some("UNSUPPORTED_SOURCE"));
7707    }
7708
7709    /// A revoked source credential is denied.
7710    #[tokio::test]
7711    async fn revoked_source_denies() {
7712        ensure_revocation_store();
7713        let now = chrono::Utc::now().timestamp();
7714        register_active_sid(now).await;
7715        let fx = fixture(
7716            Some(allow_authorizer()),
7717            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7718        )
7719        .await;
7720        let source = sign_source(&fx, &user_source_claims(&fx, now));
7721        let jti = hyprstream_rpc::auth::decode_unverified(&source)
7722            .unwrap()
7723            .jti
7724            .unwrap();
7725        let store = hyprstream_rpc::auth::global_credential_revocation_store().unwrap();
7726        store
7727            .revoke_credential(
7728                hyprstream_rpc::auth::CredentialId::jwt(ISSUER, jti),
7729                now + 3600,
7730            )
7731            .await
7732            .unwrap();
7733        let ctx = actor_ctx(&fx, now);
7734        let resp = fx
7735            .service
7736            .handle_exchange_delegated(&ctx, 1, &request(source))
7737            .await
7738            .unwrap();
7739        assert_eq!(err_code(&resp), Some("SOURCE_REVOKED"));
7740    }
7741
7742    /// A source tenant that differs from the actor's verified tenant denies.
7743    #[tokio::test]
7744    async fn tenant_mismatch_denies() {
7745        ensure_revocation_store();
7746        let now = chrono::Utc::now().timestamp();
7747        register_active_sid(now).await;
7748        let fx = fixture(
7749            Some(allow_authorizer()),
7750            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7751        )
7752        .await;
7753        let mut claims = user_source_claims(&fx, now);
7754        claims.tenant = Some("did:web:other.example".to_owned());
7755        let source = sign_source(&fx, &claims);
7756        let ctx = actor_ctx(&fx, now);
7757        let resp = fx
7758            .service
7759            .handle_exchange_delegated(&ctx, 1, &request(source))
7760            .await
7761            .unwrap();
7762        assert_eq!(err_code(&resp), Some("TENANT_MISMATCH"));
7763    }
7764
7765    /// A source signed by a FOREIGN composite pair (not in the authority's
7766    /// ledger) is denied — key possession is not issuer trust.
7767    #[tokio::test]
7768    async fn foreign_pair_source_denies() {
7769        ensure_revocation_store();
7770        let now = chrono::Utc::now().timestamp();
7771        register_active_sid(now).await;
7772        let fx = fixture(
7773            Some(allow_authorizer()),
7774            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7775        )
7776        .await;
7777        let foreign_ed = Arc::new(SigningKey::from_bytes(&[0x77; 32]));
7778        let (foreign_ml, _) = hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair();
7779        let foreign_ml = Arc::new(foreign_ml);
7780        let source = crate::auth::jwt::encode_composite_ml_dsa_65_ed25519(
7781            &user_source_claims(&fx, now),
7782            &foreign_ml,
7783            &foreign_ed,
7784        );
7785        let ctx = actor_ctx(&fx, now);
7786        let resp = fx
7787            .service
7788            .handle_exchange_delegated(&ctx, 1, &request(source))
7789            .await
7790            .unwrap();
7791        assert_eq!(err_code(&resp), Some("INVALID_SOURCE"));
7792    }
7793
7794    /// An edge whose target method is not the exact reviewed method denies.
7795    #[tokio::test]
7796    async fn wrong_target_method_denies() {
7797        ensure_revocation_store();
7798        let now = chrono::Utc::now().timestamp();
7799        register_active_sid(now).await;
7800        let authz: Arc<dyn DelegationEdgeAuthorizer> = Arc::new(MockAuthorizer {
7801            allow: true,
7802            require_source_aud: None,
7803            require_method: Some("only.Allowed".to_owned()),
7804        });
7805        let fx = fixture(
7806            Some(authz),
7807            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7808        )
7809        .await;
7810        let source = sign_source(&fx, &user_source_claims(&fx, now));
7811        let ctx = actor_ctx(&fx, now);
7812        // request() uses "model.Infer" ≠ "only.Allowed".
7813        let resp = fx
7814            .service
7815            .handle_exchange_delegated(&ctx, 1, &request(source))
7816            .await
7817            .unwrap();
7818        assert_eq!(err_code(&resp), Some("EDGE_DENIED"));
7819    }
7820
7821    /// A capability that broadens the source `cap` is denied (monotonic
7822    /// attenuation on the capability axis).
7823    #[tokio::test]
7824    async fn capability_broadening_denies() {
7825        ensure_revocation_store();
7826        let now = chrono::Utc::now().timestamp();
7827        register_active_sid(now).await;
7828        let fx = fixture(
7829            Some(allow_authorizer()),
7830            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7831        )
7832        .await;
7833        let claims = user_source_claims(&fx, now).with_cap("read@mac://model/x".to_owned());
7834        let source = sign_source(&fx, &claims);
7835        let mut req = request(source);
7836        req.requested_capabilities = Some("write@mac://model/x".to_owned()); // not covered by read
7837        let ctx = actor_ctx(&fx, now);
7838        let resp = fx
7839            .service
7840            .handle_exchange_delegated(&ctx, 1, &req)
7841            .await
7842            .unwrap();
7843        assert_eq!(err_code(&resp), Some("CAPABILITY_ATTENUATION"));
7844    }
7845
7846    /// An expired source credential is denied. The signed-credential decoder
7847    /// enforces `exp` first (fail-closed at verification), so the stable deny
7848    /// is `INVALID_SOURCE` — the decoder never admits an expired token to the
7849    /// later `SOURCE_EXPIRED` re-check.
7850    #[tokio::test]
7851    async fn expired_source_denies() {
7852        ensure_revocation_store();
7853        let now = chrono::Utc::now().timestamp();
7854        register_active_sid(now).await;
7855        let fx = fixture(
7856            Some(allow_authorizer()),
7857            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7858        )
7859        .await;
7860        let mut claims = user_source_claims(&fx, now);
7861        claims.exp = now - 10; // already expired
7862        let source = sign_source(&fx, &claims);
7863        let ctx = actor_ctx(&fx, now);
7864        let resp = fx
7865            .service
7866            .handle_exchange_delegated(&ctx, 1, &request(source))
7867            .await
7868            .unwrap();
7869        assert_eq!(err_code(&resp), Some("INVALID_SOURCE"));
7870    }
7871
7872    /// A source whose `iss` is not this authority's configured issuer denies
7873    /// (key possession is not issuer trust).
7874    #[tokio::test]
7875    async fn untrusted_issuer_source_denies() {
7876        ensure_revocation_store();
7877        let now = chrono::Utc::now().timestamp();
7878        register_active_sid(now).await;
7879        let fx = fixture(
7880            Some(allow_authorizer()),
7881            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7882        )
7883        .await;
7884        let mut claims = user_source_claims(&fx, now);
7885        claims.iss = "https://evil.example".to_owned();
7886        let source = sign_source(&fx, &claims);
7887        let ctx = actor_ctx(&fx, now);
7888        let resp = fx
7889            .service
7890            .handle_exchange_delegated(&ctx, 1, &request(source))
7891            .await
7892            .unwrap();
7893        assert_eq!(err_code(&resp), Some("UNTRUSTED_ISSUER"));
7894    }
7895
7896    /// A terminal actor whose verified signer key does NOT match its enrolled
7897    /// key cannot resolve a v16 signer suite for the output (fail closed).
7898    #[tokio::test]
7899    async fn actor_cnf_not_enrolled_denies() {
7900        ensure_revocation_store();
7901        let now = chrono::Utc::now().timestamp();
7902        register_active_sid(now).await;
7903        let fx = fixture(
7904            Some(allow_authorizer()),
7905            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7906        )
7907        .await;
7908        let source = sign_source(&fx, &user_source_claims(&fx, now));
7909        // Actor authenticates with a key that is NOT the enrolled `mcp` key.
7910        let wrong = SigningKey::from_bytes(&[0x99; 32]);
7911        let actor_claims =
7912            hyprstream_rpc::auth::Claims::new("service:mcp".to_owned(), now, now + 3600)
7913                .with_clearance(label());
7914        let ctx = EnvelopeContext::for_test_authenticated_subject_with_claims(
7915            Subject::new("service:mcp"),
7916            TENANT,
7917            wrong.verifying_key(),
7918            actor_claims,
7919        );
7920        let resp = fx
7921            .service
7922            .handle_exchange_delegated(&ctx, 1, &request(source))
7923            .await
7924            .unwrap();
7925        assert_eq!(err_code(&resp), Some("ACTOR_SUITE_UNRESOLVABLE"));
7926    }
7927
7928    /// An unlabeled terminal actor (no clearance) denies.
7929    #[tokio::test]
7930    async fn unlabeled_actor_denies() {
7931        ensure_revocation_store();
7932        let now = chrono::Utc::now().timestamp();
7933        register_active_sid(now).await;
7934        let fx = fixture(
7935            Some(allow_authorizer()),
7936            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7937        )
7938        .await;
7939        let source = sign_source(&fx, &user_source_claims(&fx, now));
7940        let actor_claims =
7941            hyprstream_rpc::auth::Claims::new("service:mcp".to_owned(), now, now + 3600); // no clearance
7942        let ctx = EnvelopeContext::for_test_authenticated_subject_with_claims(
7943            Subject::new("service:mcp"),
7944            TENANT,
7945            fx.actor_ed.verifying_key(),
7946            actor_claims,
7947        );
7948        let resp = fx
7949            .service
7950            .handle_exchange_delegated(&ctx, 1, &request(source))
7951            .await
7952            .unwrap();
7953        assert_eq!(err_code(&resp), Some("UNLABELED_ACTOR"));
7954    }
7955
7956    /// A source OIDC session that is REVOKED denies (unique sid, no shared
7957    /// session-registry contamination).
7958    #[tokio::test]
7959    async fn revoked_session_denies() {
7960        ensure_revocation_store();
7961        let now = chrono::Utc::now().timestamp();
7962        let sid = "sess-revoked-unique-1";
7963        let reg = session_registry();
7964        let key = hyprstream_rpc::auth::SessionKey::oidc(ISSUER, sid);
7965        reg.register_session(
7966            key.clone(),
7967            hyprstream_rpc::auth::SessionState {
7968                subject: "alice".to_owned(),
7969                tenant: TENANT.to_owned(),
7970                kind: hyprstream_rpc::auth::SessionKind::Interactive,
7971                created_at: now,
7972                expires_at: now + 3600,
7973                status: hyprstream_rpc::auth::ActiveOrRevoked::Active,
7974                clearance_epoch: 0,
7975            },
7976        )
7977        .await
7978        .unwrap();
7979        reg.revoke_session(&key).await.unwrap();
7980        let fx = fixture(
7981            Some(allow_authorizer()),
7982            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
7983        )
7984        .await;
7985        let mut claims = user_source_claims(&fx, now);
7986        claims.sid = Some(sid.to_owned());
7987        let source = sign_source(&fx, &claims);
7988        let ctx = actor_ctx(&fx, now);
7989        let resp = fx
7990            .service
7991            .handle_exchange_delegated(&ctx, 1, &request(source))
7992            .await
7993            .unwrap();
7994        assert_eq!(err_code(&resp), Some("SESSION_INVALID"));
7995    }
7996
7997    /// A source OIDC session bound to a DIFFERENT subject denies (mismatch).
7998    #[tokio::test]
7999    async fn mismatched_session_subject_denies() {
8000        ensure_revocation_store();
8001        let now = chrono::Utc::now().timestamp();
8002        let sid = "sess-mismatch-unique-1";
8003        let reg = session_registry();
8004        let key = hyprstream_rpc::auth::SessionKey::oidc(ISSUER, sid);
8005        reg.register_session(
8006            key,
8007            hyprstream_rpc::auth::SessionState {
8008                subject: "carol".to_owned(), // NOT alice
8009                tenant: TENANT.to_owned(),
8010                kind: hyprstream_rpc::auth::SessionKind::Interactive,
8011                created_at: now,
8012                expires_at: now + 3600,
8013                status: hyprstream_rpc::auth::ActiveOrRevoked::Active,
8014                clearance_epoch: 0,
8015            },
8016        )
8017        .await
8018        .unwrap();
8019        let fx = fixture(
8020            Some(allow_authorizer()),
8021            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
8022        )
8023        .await;
8024        let mut claims = user_source_claims(&fx, now);
8025        claims.sid = Some(sid.to_owned());
8026        let source = sign_source(&fx, &claims);
8027        let ctx = actor_ctx(&fx, now);
8028        let resp = fx
8029            .service
8030            .handle_exchange_delegated(&ctx, 1, &request(source))
8031            .await
8032            .unwrap();
8033        assert_eq!(err_code(&resp), Some("SESSION_INVALID"));
8034    }
8035
8036    /// A source whose sid is UNKNOWN to the registry denies.
8037    #[tokio::test]
8038    async fn unknown_session_denies() {
8039        ensure_revocation_store();
8040        let now = chrono::Utc::now().timestamp();
8041        let _ = session_registry(); // ensure the registry exists (empty for this sid)
8042        let fx = fixture(
8043            Some(allow_authorizer()),
8044            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
8045        )
8046        .await;
8047        let mut claims = user_source_claims(&fx, now);
8048        claims.sid = Some("sess-never-registered-unique-1".to_owned());
8049        let source = sign_source(&fx, &claims);
8050        let ctx = actor_ctx(&fx, now);
8051        let resp = fx
8052            .service
8053            .handle_exchange_delegated(&ctx, 1, &request(source))
8054            .await
8055            .unwrap();
8056        assert_eq!(err_code(&resp), Some("SESSION_INVALID"));
8057    }
8058
8059    /// A source whose sid is registered but EXPIRED denies.
8060    #[tokio::test]
8061    async fn expired_session_denies() {
8062        ensure_revocation_store();
8063        let now = chrono::Utc::now().timestamp();
8064        let sid = "sess-expired-unique-1";
8065        let reg = session_registry();
8066        reg.register_session(
8067            hyprstream_rpc::auth::SessionKey::oidc(ISSUER, sid),
8068            hyprstream_rpc::auth::SessionState {
8069                subject: "alice".to_owned(),
8070                tenant: TENANT.to_owned(),
8071                kind: hyprstream_rpc::auth::SessionKind::Interactive,
8072                created_at: now - 7200,
8073                expires_at: now - 3600, // already expired
8074                status: hyprstream_rpc::auth::ActiveOrRevoked::Active,
8075                clearance_epoch: 0,
8076            },
8077        )
8078        .await
8079        .unwrap();
8080        let fx = fixture(
8081            Some(allow_authorizer()),
8082            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
8083        )
8084        .await;
8085        let mut claims = user_source_claims(&fx, now);
8086        claims.sid = Some(sid.to_owned());
8087        let source = sign_source(&fx, &claims);
8088        let ctx = actor_ctx(&fx, now);
8089        let resp = fx
8090            .service
8091            .handle_exchange_delegated(&ctx, 1, &request(source))
8092            .await
8093            .unwrap();
8094        assert_eq!(err_code(&resp), Some("SESSION_INVALID"));
8095    }
8096
8097    /// A low-clearance INTERMEDIATE actor in the source's delegation chain
8098    /// lowers the effective meet: the minted credential's clearance is the
8099    /// intersection/min across originator, every actor, and the terminal
8100    /// actor — never above any input.
8101    #[tokio::test]
8102    async fn low_clearance_intermediate_lowers_the_meet() {
8103        ensure_revocation_store();
8104        let now = chrono::Utc::now().timestamp();
8105        register_active_sid(now).await;
8106        let fx = fixture(
8107            Some(allow_authorizer()),
8108            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
8109        )
8110        .await;
8111        let public = SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY);
8112        let actor_hs = hyprstream_rpc::auth::service_signer_suite_b64(
8113            &fx.actor_ed.verifying_key().to_bytes(),
8114            None,
8115        );
8116        // Source: originator alice (Internal), act = terminal service:mcp
8117        // (Internal) nesting an intermediate service:low (Public). The cnf
8118        // resolves against the OUTERMOST act (service:mcp).
8119        let claims = hyprstream_rpc::auth::Claims::new("alice".to_owned(), now, now + 3600)
8120            .with_issuer(ISSUER.to_owned())
8121            .with_tenant(TENANT.to_owned())
8122            .with_sid("sess-1")
8123            .with_client_id(CLIENT_ID)
8124            .with_scope(Some("read".to_owned()))
8125            .with_clearance(label())
8126            .with_audience(Some("res-a".to_owned()))
8127            .with_act(hyprstream_rpc::auth::ActClaim {
8128                sub: "service:mcp".to_owned(),
8129                clearance: Some(CredentialClearance::from_label(label())),
8130                act: Some(Box::new(hyprstream_rpc::auth::ActClaim {
8131                    sub: "service:low".to_owned(),
8132                    clearance: Some(CredentialClearance::from_label(public)),
8133                    act: None,
8134                })),
8135            })
8136            .with_cnf_jwk(&fx.actor_ed.verifying_key().to_bytes())
8137            .with_cnf_hs_signer_suite(actor_hs);
8138        let source = sign_source(&fx, &claims);
8139        let ctx = actor_ctx(&fx, now);
8140        let token = match fx
8141            .service
8142            .handle_exchange_delegated(&ctx, 1, &request(source))
8143            .await
8144            .unwrap()
8145        {
8146            PolicyResponseVariant::ExchangeDelegatedResult(info) => info.token,
8147            other => panic!("expected a minted token, got {other:?}"),
8148        };
8149        let minted = hyprstream_rpc::auth::decode_unverified(&token).unwrap();
8150        assert_eq!(
8151            minted.clearance,
8152            Some(CredentialClearance::from_label(public)),
8153            "the low-clearance intermediate must lower the effective meet to Public"
8154        );
8155    }
8156
8157    /// A NON-DISPATCH OAuth token (valid signature/profile but NO
8158    /// `cnf.hs_signer_suite`) presented as a delegation SOURCE is denied —
8159    /// issuance may accept such a bearer, but delegation admission rejects it
8160    /// for the missing authoritative confirmation.
8161    #[tokio::test]
8162    async fn non_dispatch_source_without_hs_is_denied() {
8163        ensure_revocation_store();
8164        let now = chrono::Utc::now().timestamp();
8165        register_active_sid(now).await;
8166        let fx = fixture(
8167            Some(allow_authorizer()),
8168            Some(user_resolver(&SigningKey::from_bytes(&[0x43; 32]))),
8169        )
8170        .await;
8171        // The same valid interactive user source, but WITHOUT the v16 cnf
8172        // signer-suite confirmation (a bearer/non-dispatch shape).
8173        let claims = hyprstream_rpc::auth::Claims::new("alice".to_owned(), now, now + 3600)
8174            .with_issuer(ISSUER.to_owned())
8175            .with_tenant(TENANT.to_owned())
8176            .with_sid("sess-1")
8177            .with_client_id(CLIENT_ID)
8178            .with_scope(Some("read write".to_owned()))
8179            .with_clearance(label())
8180            .with_audience(Some("res-a".to_owned()))
8181            .with_cnf_jwk(&fx.user_ed.verifying_key().to_bytes());
8182        let source = sign_source(&fx, &claims);
8183        let ctx = actor_ctx(&fx, now);
8184        let resp = fx
8185            .service
8186            .handle_exchange_delegated(&ctx, 1, &request(source))
8187            .await
8188            .unwrap();
8189        assert_eq!(err_code(&resp), Some("INVALID_SOURCE_CNF"));
8190    }
8191}