Skip to main content

hyprstream_core/auth/
federation_admission.rs

1//! `hyprstream`-side wiring for the federation admission gate (#137, M3).
2//!
3//! The transport-agnostic two-stage gate lives in
4//! [`hyprstream_rpc::admission`] (lower crate, no `PolicyService` client). This
5//! module supplies the **stage-1 origin-admission decision** over the real
6//! `PolicyService`, reusing the existing unified federation trust gate
7//! (`federation:register:<origin>`) — the same origin-scoped Casbin resource
8//! checked by CIMD client registration and
9//! [`crate::auth::federation::FederationKeyResolver`].
10//!
11//! It also exposes a constructor that assembles a ready-to-use
12//! [`hyprstream_rpc::admission::FederationAdmissionGate`] from a `PolicyClient`
13//! plus a `did:web` resolver, so the live accept/identity path can construct the
14//! gate once and call `admit(...)` per inbound federated peer.
15//!
16//! ## Integration seam (honest status)
17//!
18//! Stage 1 here is wired against the real `PolicyService`. **Stage 2's live peer
19//! key** is the documented seam: in this architecture the peer's authenticated
20//! identity is the verified Ed25519 *envelope signer key* (`cnf`), surfaced at
21//! the application/service layer ([`hyprstream_rpc::service`]'s
22//! `verify_claims`/`resolve_key_subject`), **not** at the transport accept loop
23//! (the QUIC/WebTransport server has only carrier metadata, which is never an
24//! application signer proof). The accept
25//! loop also does not know the peer's *origin* (it arrives in the app-layer
26//! JWT/envelope), so even stage 1 cannot run at the raw accept loop. The gate is
27//! therefore designed to be invoked from the service layer once that path passes
28//! the verified signer key + issuer origin in; see the integration TODO below.
29
30use std::sync::Arc;
31
32use anyhow::Result;
33use async_trait::async_trait;
34use hyprstream_rpc::admission::{FederationAdmissionGate, OriginAdmission};
35use hyprstream_rpc::did_web::{DidWebResolver, HttpDidDocFetcher};
36
37use hyprstream_rpc_std::policy_client::PolicyClient;
38
39/// Stage-1 origin admission over `PolicyService` `federation:register`.
40///
41/// Wraps the same decision as [`crate::auth::federation::FederationKeyResolver`]'s
42/// peer trust gate: an origin is admitted iff Casbin returns `allow` for the
43/// origin-scoped `federation:register:<origin>` resource. The RPC subject and
44/// domain remain inert; PolicyService derives those only from the verified
45/// envelope context. Fail-closed on denial **and** on `PolicyService` outage.
46pub struct PolicyOriginAdmission {
47    policy_client: Arc<PolicyClient>,
48}
49impl PolicyOriginAdmission {
50    /// Construct over a shared `PolicyService` client.
51    pub fn new(policy_client: Arc<PolicyClient>) -> Self {
52        Self { policy_client }
53    }
54}
55#[async_trait]
56impl OriginAdmission for PolicyOriginAdmission {
57    async fn admit_origin(&self, origin: &str) -> Result<()> {
58        use hyprstream_rpc_std::policy_client::PolicyCheck;
59        let resource = crate::auth::federation_registration_resource(origin)?;
60        match self
61            .policy_client
62            .check(&PolicyCheck {
63                subject: String::new(),
64                domain: String::new(),
65                resource,
66                operation: "check".to_owned(),
67            })
68            .await
69        {
70            Ok(true) => Ok(()),
71            Ok(false) => anyhow::bail!(
72                "origin {origin} is not permitted by policy (federation:register denied)"
73            ),
74            Err(e) => {
75                // Fail-closed: an unreachable PolicyService must reject, never
76                // default-allow. Same posture as the CIMD / FederationKeyResolver
77                // gate.
78                tracing::error!(
79                    origin = %origin,
80                    error = %e,
81                    "PolicyService unreachable during federation admission stage 1 — failing closed"
82                );
83                anyhow::bail!(
84                    "PolicyService unreachable; federation admission rejected (fail-closed): {e}"
85                )
86            }
87        }
88    }
89}
90
91/// Assemble a ready-to-use [`FederationAdmissionGate`] over the real
92/// `PolicyService` (stage 1) and a native `did:web` resolver (stage 2).
93///
94/// The resolver reuses the #279 [`HttpDidDocFetcher`] (TTL-cached, SSRF/DoS
95/// hardened) — no new fetch/cache infrastructure. Construct this once and call
96/// [`FederationAdmissionGate::admit`] per inbound federated peer with the
97/// verified envelope-signer key and the peer's origin + DID.
98///
99/// # Live proof seam
100///
101/// The caller must pass the peer's *authenticated* Ed25519 key
102/// (`ApplicationSignerKey`). Today that key is the verified COSE envelope signer key,
103/// available at the service layer after `verify_claims`. A transport NodeId is
104/// never a substitute for that application proof (#1031/#1027).
105pub fn build_federation_admission_gate(
106    policy_client: Arc<PolicyClient>,
107) -> Result<FederationAdmissionGate<PolicyOriginAdmission, DidWebResolver<HttpDidDocFetcher>>> {
108    // One-hour TTL, matching the JWKS / DID-doc cache default.
109    let fetcher = HttpDidDocFetcher::new(std::time::Duration::from_secs(3600))?;
110    let resolver = DidWebResolver::new(fetcher);
111    Ok(FederationAdmissionGate::new(
112        PolicyOriginAdmission::new(policy_client),
113        resolver,
114    ))
115}