Skip to main content

hyprstream_core/services/
revocation.rs

1//! Policy-authority credential revocation and session registry: one canonical
2//! store of each kind per deployment.
3//!
4//! The policy service process owns the single canonical credential-revocation
5//! store and session registry, each backed by a durable local file
6//! ([`hyprstream_rpc::auth::FileBackedCredentialRevocationStore`] and
7//! [`hyprstream_rpc::auth::FileBackedSessionRegistry`]). Every other service
8//! process publishes [`PolicyAuthorityRevocationStore`] and
9//! [`PolicyAuthoritySessionRegistry`] as its process-global handles: checks
10//! and publications cross the RPC bus to the policy service. Fail-closed
11//! everywhere — at startup (an unreachable or unhealthy authority aborts the
12//! process), at check (any RPC error or timeout reports the credential as
13//! revoked / the session as not active), and at publication (a failed
14//! publication is an error, never a silent no-op).
15
16use std::sync::Arc;
17use std::time::Duration;
18
19use anyhow::Context as _;
20use hyprstream_rpc::auth::{
21    CredentialId, CredentialRevocationStore, CredentialValue, RevocationPublishError, SessionKey,
22    SessionRegisterError, SessionRegistry, SessionRevokeError, SessionState,
23};
24use hyprstream_rpc::crypto::SigningKey;
25use hyprstream_service::ServiceContext;
26
27use hyprstream_rpc_std::policy_client::PolicyClient;
28use hyprstream_rpc_std::policy_client::{
29    CheckCredentialRevocation, CheckSession, CredentialIdRef, CredentialIdRefContent,
30    RegisterSession, RevokeCredential, RevokeSession, SessionKeyRef, SessionKeyRefContent,
31};
32
33/// Timeout for a single revocation check RPC. The underlying RPC client has a
34/// fixed 30s call timeout; a revocation check sits on the verification hot
35/// path, so it gets a much shorter budget.
36const CHECK_TIMEOUT: Duration = Duration::from_secs(5);
37
38/// Startup probe policy: attempts, and the delay between them. The policy
39/// service is a startup dependency, but its listener may not be accepting yet
40/// when a dependent process boots — retry instead of racing.
41const PROBE_ATTEMPTS: u32 = 10;
42const PROBE_RETRY_DELAY: Duration = Duration::from_secs(2);
43
44/// Map a wire [`CredentialIdRef`] to a validated [`CredentialId`], preserving
45/// the JWT/CWT typed namespace. `None` = malformed (empty issuer or empty
46/// value) — callers fail closed.
47pub(crate) fn credential_id_from_ref(reference: &CredentialIdRef) -> Option<CredentialId> {
48    let id = match &reference.content {
49        CredentialIdRefContent::JwtJti(jti) => {
50            CredentialId::jwt(reference.issuer.clone(), jti.clone())
51        }
52        CredentialIdRefContent::CwtCti(cti) => {
53            CredentialId::cwt(reference.issuer.clone(), cti.clone())
54        }
55    };
56    id.is_valid().then_some(id)
57}
58
59/// Map a [`CredentialId`] to its wire form, preserving the JWT/CWT typed
60/// namespace.
61fn credential_id_to_ref(id: &CredentialId) -> CredentialIdRef {
62    let content = match &id.value {
63        CredentialValue::Jwt(jti) => CredentialIdRefContent::JwtJti(jti.clone()),
64        CredentialValue::Cwt(cti) => CredentialIdRefContent::CwtCti(cti.clone()),
65    };
66    CredentialIdRef {
67        issuer: id.issuer.clone(),
68        content,
69    }
70}
71
72/// Map a wire [`SessionKeyRef`] to a validated [`SessionKey`], preserving
73/// the OIDC/workload typed namespace. `None` = malformed (empty issuer or
74/// identifier) — callers fail closed.
75pub(crate) fn session_key_from_ref(reference: &SessionKeyRef) -> Option<SessionKey> {
76    let key = match &reference.content {
77        SessionKeyRefContent::OidcSid(sid) => {
78            SessionKey::oidc(reference.issuer.clone(), sid.clone())
79        }
80        SessionKeyRefContent::WorkloadSessionId(id) => {
81            SessionKey::workload(reference.issuer.clone(), id.clone())
82        }
83    };
84    key.is_valid().then_some(key)
85}
86
87/// Map a [`SessionKey`] to its wire form, preserving the OIDC/workload typed
88/// namespace.
89fn session_key_to_ref(key: &SessionKey) -> SessionKeyRef {
90    let content = match &key.id {
91        hyprstream_rpc::auth::SessionIdentifier::OidcSid(sid) => {
92            SessionKeyRefContent::OidcSid(sid.clone())
93        }
94        hyprstream_rpc::auth::SessionIdentifier::WorkloadSessionId(id) => {
95            SessionKeyRefContent::WorkloadSessionId(id.clone())
96        }
97    };
98    SessionKeyRef {
99        issuer: key.issuer.clone(),
100        content,
101    }
102}
103
104/// Session registry that delegates to the policy service — the one canonical
105/// session authority — over the RPC bus. Published as the process-global
106/// registry by [`init_process_authority_stores`] in every process that does
107/// not host the policy service.
108pub struct PolicyAuthoritySessionRegistry {
109    client_provider: Arc<dyn Fn() -> anyhow::Result<Arc<PolicyClient>> + Send + Sync>,
110}
111
112impl PolicyAuthoritySessionRegistry {
113    /// Wrap a policy client as a session registry.
114    pub fn new(client: PolicyClient) -> Self {
115        let client = Arc::new(client);
116        Self::with_client_provider(move || Ok(Arc::clone(&client)))
117    }
118
119    /// Resolve a current authenticated client separately for every operation.
120    /// A provider failure denies checks and rejects publications; it never
121    /// falls back to a previously captured token or an anonymous client.
122    pub fn with_client_provider(
123        provider: impl Fn() -> anyhow::Result<Arc<PolicyClient>> + Send + Sync + 'static,
124    ) -> Self {
125        Self {
126            client_provider: Arc::new(provider),
127        }
128    }
129
130    /// Follow the exact service key's renewed trust-store JWT for the process
131    /// lifetime. Resolver authority and remote crypto validation are unchanged.
132    fn for_service(signing_key: SigningKey) -> Self {
133        Self::with_client_provider(move || {
134            let token = crate::services::factories::service_token(&signing_key)
135                .context("current service JWT unavailable for session authority")?;
136            PolicyClient::from_provider(
137                &hyprstream_discovery::ProductionRpcClientProvider,
138                signing_key.clone(),
139                Some(token),
140            )
141            .map(Arc::new)
142        })
143    }
144}
145
146#[async_trait::async_trait]
147impl SessionRegistry for PolicyAuthoritySessionRegistry {
148    /// The remote surface answers active/revoked checks only; a full state
149    /// record is never fabricated. Consumers must use `is_revoked`.
150    async fn session_state(&self, _key: &SessionKey) -> Option<SessionState> {
151        None
152    }
153
154    async fn register_session(
155        &self,
156        key: SessionKey,
157        state: SessionState,
158    ) -> Result<(), SessionRegisterError> {
159        let request = RegisterSession {
160            session: session_key_to_ref(&key),
161            subject: state.subject,
162            tenant: state.tenant,
163            expires_at: state.expires_at,
164            clearance_epoch: state.clearance_epoch,
165        };
166        let client = (self.client_provider)().map_err(|_| -> SessionRegisterError {
167            hyprstream_rpc::auth::SessionPublicationFailed.into()
168        })?;
169        client.register_session(&request).await.map_err(|e| {
170            let message = e.to_string();
171            if message.contains("already exists") {
172                hyprstream_rpc::auth::SessionExists.into()
173            } else if message.contains("durably") || message.contains("not initialized") {
174                hyprstream_rpc::auth::SessionPublicationFailed.into()
175            } else {
176                hyprstream_rpc::auth::InvalidSessionRecord.into()
177            }
178        })
179    }
180
181    async fn revoke_session(&self, key: &SessionKey) -> Result<(), SessionRevokeError> {
182        let request = RevokeSession {
183            session: session_key_to_ref(key),
184        };
185        // Publication BEFORE eviction: only after the authority has durably
186        // accepted the revocation is the local cache generation flushed.
187        (self.client_provider)()
188            .map_err(|e| SessionRevokeError::new(format!("authority client unavailable: {e}")))?
189            .revoke_session(&request)
190            .await
191            .map_err(|e| SessionRevokeError::new(format!("authority rejected publication: {e}")))?;
192        hyprstream_rpc::auth::mac::flush_verified_subject_cache_generation();
193        Ok(())
194    }
195
196    async fn is_revoked(&self, key: &SessionKey) -> bool {
197        let request = CheckSession {
198            session: session_key_to_ref(key),
199        };
200        match tokio::time::timeout(CHECK_TIMEOUT, async {
201            (self.client_provider)()?.check_session(&request).await
202        })
203        .await
204        {
205            // true = active and known; anything else is not active.
206            Ok(Ok(active)) => !active,
207            Ok(Err(e)) => {
208                tracing::warn!(error = %e, "session check RPC failed — failing closed");
209                true
210            }
211            Err(_) => {
212                tracing::warn!(
213                    timeout_ms = CHECK_TIMEOUT.as_millis() as u64,
214                    "session check RPC timed out — failing closed"
215                );
216                true
217            }
218        }
219    }
220}
221
222/// Credential-revocation store that delegates to the policy service — the one
223/// canonical revocation authority — over the RPC bus. Published as the
224/// process-global store by [`init_process_authority_stores`] in
225/// every process that does not host the policy service.
226pub struct PolicyAuthorityRevocationStore {
227    client_provider: Arc<dyn Fn() -> anyhow::Result<Arc<PolicyClient>> + Send + Sync>,
228}
229
230impl PolicyAuthorityRevocationStore {
231    /// Wrap a policy client as a revocation store.
232    pub fn new(client: PolicyClient) -> Self {
233        let client = Arc::new(client);
234        Self::with_client_provider(move || Ok(Arc::clone(&client)))
235    }
236
237    /// Resolve a current authenticated client separately for every operation.
238    /// A provider failure denies checks and rejects publications; it never
239    /// falls back to a previously captured token or an anonymous client.
240    pub fn with_client_provider(
241        provider: impl Fn() -> anyhow::Result<Arc<PolicyClient>> + Send + Sync + 'static,
242    ) -> Self {
243        Self {
244            client_provider: Arc::new(provider),
245        }
246    }
247
248    /// Follow the exact service key's renewed trust-store JWT for the process
249    /// lifetime. Resolver authority and remote crypto validation are unchanged.
250    fn for_service(signing_key: SigningKey) -> Self {
251        Self::with_client_provider(move || {
252            let token = crate::services::factories::service_token(&signing_key)
253                .context("current service JWT unavailable for revocation authority")?;
254            PolicyClient::from_provider(
255                &hyprstream_discovery::ProductionRpcClientProvider,
256                signing_key.clone(),
257                Some(token),
258            )
259            .map(Arc::new)
260        })
261    }
262}
263
264#[async_trait::async_trait]
265impl CredentialRevocationStore for PolicyAuthorityRevocationStore {
266    async fn is_revoked_checked(&self, id: &CredentialId) -> bool {
267        let request = CheckCredentialRevocation {
268            credential: credential_id_to_ref(id),
269        };
270        match tokio::time::timeout(CHECK_TIMEOUT, async {
271            (self.client_provider)()?
272                .check_credential_revocation(&request)
273                .await
274        })
275        .await
276        {
277            Ok(Ok(revoked)) => revoked,
278            Ok(Err(e)) => {
279                tracing::warn!(credential = %id, error = %e,
280                    "revocation check RPC failed — failing closed");
281                true
282            }
283            Err(_) => {
284                tracing::warn!(credential = %id, timeout_ms = CHECK_TIMEOUT.as_millis() as u64,
285                    "revocation check RPC timed out — failing closed");
286                true
287            }
288        }
289    }
290
291    async fn revoke_credential(
292        &self,
293        id: CredentialId,
294        expires_at: i64,
295    ) -> Result<(), RevocationPublishError> {
296        let request = RevokeCredential {
297            credential: credential_id_to_ref(&id),
298            expires_at,
299        };
300        // Publication BEFORE eviction: only after the authority has durably
301        // accepted the revocation are cached handles derived from the
302        // credential evicted. On failure nothing is evicted.
303        (self.client_provider)()
304            .map_err(|e| RevocationPublishError::new(format!("authority client unavailable: {e}")))?
305            .revoke_credential(&request)
306            .await
307            .map_err(|e| {
308                RevocationPublishError::new(format!("authority rejected publication: {e}"))
309            })?;
310        hyprstream_rpc::auth::mac::revoke_verified_subject_credential(&id);
311        Ok(())
312    }
313}
314
315/// Initialize the process-global authority stores at startup: the
316/// credential-revocation store AND the session registry.
317///
318/// When this process hosts the policy service (`hosts_policy`), it owns both
319/// canonical stores as durable files under the deployment data dir
320/// (`credential-revocations.jsonl`, `sessions.jsonl`). Every compatibility-mode
321/// process PROBES the authority (a freshly generated random credential ID,
322/// expected not revoked; and a random session key, expected not active) before
323/// publishing the RPC client stores. In the required-native profile, the
324/// standalone Discovery process starts before Policy so its resolver can
325/// publish the bootstrap announcement; that bootstrap process publishes lazy
326/// RPC client stores without a startup probe. Other service processes retain
327/// the startup probe and therefore do not report ready when Policy is
328/// unavailable. Lazy stores still fail closed on every operation. Both stores
329/// resolve a fresh
330/// [`PolicyClient`] per operation through the production resolver, so a
331/// renewed trust-store service JWT is consumed without a process restart.
332///
333/// Fail-closed: any error in compatibility-mode probing — an unreadable/corrupt
334/// durable file, or an authority unreachable after [`PROBE_ATTEMPTS`] attempts
335/// — is propagated and MUST abort startup. Required-native Discovery clients
336/// retain the same fail-closed operation behavior while allowing the
337/// dependency-ordered Discovery → Policy bootstrap to complete. Policy-
338/// dependent services keep the probe so a standalone service cannot become
339/// ready without its authority.
340pub async fn init_process_authority_stores(
341    ctx: &ServiceContext,
342    signing_key: &SigningKey,
343    hosts_policy: bool,
344    defer_policy_probe: bool,
345) -> anyhow::Result<()> {
346    // W1.3: install the authority-owned Federate TUI class reservation BEFORE
347    // any factory runs, so the RPC dispatch fence classifies TUI-class
348    // credentials (including marker-stripped shapes) identically in every
349    // service process. The reservation comes from the deployment's
350    // trusted-issuer config — never from a caller. A configured-but-invalid
351    // class leaves the reservation uninstalled (fail-closed: only the
352    // marker set classifies, and nothing can mint the class).
353    {
354        let config = super::factories::load_config()?;
355        let tui_client = config
356            .oauth
357            .trusted_issuers
358            .get(crate::services::oauth::federate_source::ISSUER)
359            .and_then(|issuer| issuer.federate_tui_client.as_ref())
360            .and_then(|class| {
361                match crate::services::oauth::federate_source::ClientClass::new(
362                    &class.client_id,
363                    &class.aud,
364                    class.connector_id.as_deref(),
365                ) {
366                    Ok(class) => Some(class.client_id().to_owned()),
367                    Err(error) => {
368                        tracing::warn!(
369                            %error,
370                            "Federate TUI class reservation not installed: invalid trusted-issuer configuration"
371                        );
372                        None
373                    }
374                }
375            });
376        hyprstream_rpc::auth::install_federate_tui_class_client(tui_client.as_deref())?;
377    }
378    if hosts_policy {
379        let data_dir = ctx.deployment_data_dir()?;
380        let credentials_path = data_dir.join("credential-revocations.jsonl");
381        let store =
382            hyprstream_rpc::auth::FileBackedCredentialRevocationStore::open(&credentials_path)
383                .with_context(|| {
384                    format!(
385                        "open credential-revocation store {}",
386                        credentials_path.display()
387                    )
388                })?;
389        hyprstream_rpc::auth::set_global_credential_revocation_store(Arc::new(store))
390            .map_err(|e| anyhow::anyhow!("{e}"))?;
391        tracing::info!(path = %credentials_path.display(), "Credential revocation authority store initialized (durable)");
392
393        let sessions_path = data_dir.join("sessions.jsonl");
394        let sessions = hyprstream_rpc::auth::FileBackedSessionRegistry::open(&sessions_path)
395            .with_context(|| format!("open session registry {}", sessions_path.display()))?;
396        hyprstream_rpc::auth::set_global_session_registry(Arc::new(sessions))
397            .map_err(|e| anyhow::anyhow!("{e}"))?;
398        tracing::info!(path = %sessions_path.display(), "Session authority registry initialized (durable)");
399        return Ok(());
400    }
401
402    let store = PolicyAuthorityRevocationStore::for_service(signing_key.clone());
403    let sessions = PolicyAuthoritySessionRegistry::for_service(signing_key.clone());
404    // Required-native standalone Discovery launches before Policy so the native
405    // resolver can publish the bootstrap announcement. Only that bootstrap
406    // process may defer the probe; policy-dependent services must remain
407    // blocked until their authority is reachable.
408    if ctx.iroh_required() && defer_policy_probe {
409        hyprstream_rpc::auth::set_global_credential_revocation_store(Arc::new(store))
410            .map_err(|e| anyhow::anyhow!("{e}"))?;
411        hyprstream_rpc::auth::set_global_session_registry(Arc::new(sessions))
412            .map_err(|e| anyhow::anyhow!("{e}"))?;
413        tracing::info!(
414            "Required-native profile: lazy revocation/session authority clients published; Policy probe deferred"
415        );
416        return Ok(());
417    }
418
419    let probe = CredentialId::jwt(
420        "https://revocation-probe.invalid",
421        format!("probe-{:032x}", rand::random::<u128>()),
422    );
423    let session_probe = SessionKey::oidc(
424        "https://revocation-probe.invalid",
425        format!("probe-{:032x}", rand::random::<u128>()),
426    );
427    let mut last_error = String::new();
428    for attempt in 1..=PROBE_ATTEMPTS {
429        let request = CheckCredentialRevocation {
430            credential: credential_id_to_ref(&probe),
431        };
432        let session_request = CheckSession {
433            session: session_key_to_ref(&session_probe),
434        };
435        let revocation_probe = tokio::time::timeout(CHECK_TIMEOUT, async {
436            (store.client_provider)()?
437                .check_credential_revocation(&request)
438                .await
439        })
440        .await;
441        let session_probe_result = tokio::time::timeout(CHECK_TIMEOUT, async {
442            (sessions.client_provider)()?
443                .check_session(&session_request)
444                .await
445        })
446        .await;
447        match (revocation_probe, session_probe_result) {
448            (Ok(Ok(false)), Ok(Ok(false))) => {
449                hyprstream_rpc::auth::set_global_credential_revocation_store(Arc::new(store))
450                    .map_err(|e| anyhow::anyhow!("{e}"))?;
451                hyprstream_rpc::auth::set_global_session_registry(Arc::new(sessions))
452                    .map_err(|e| anyhow::anyhow!("{e}"))?;
453                tracing::info!(
454                    "Revocation/session authority reachable; RPC client stores published"
455                );
456                return Ok(());
457            }
458            // A never-issued random ID reading as revoked (or a random
459            // session reading active) means the authority itself is
460            // unhealthy (its own store missing → fail-closed answers).
461            (Ok(Ok(true)), _) => {
462                last_error =
463                    "authority reported a never-issued probe credential as revoked".to_owned();
464            }
465            (_, Ok(Ok(true))) => {
466                last_error =
467                    "authority reported a never-registered probe session as active".to_owned();
468            }
469            (Ok(Err(e)), _) | (_, Ok(Err(e))) => last_error = e.to_string(),
470            (Err(_), _) | (_, Err(_)) => {
471                last_error = format!("probe timed out after {}s", CHECK_TIMEOUT.as_secs());
472            }
473        }
474        tracing::warn!(attempt, error = %last_error, "authority probe failed; retrying");
475        if attempt < PROBE_ATTEMPTS {
476            tokio::time::sleep(PROBE_RETRY_DELAY).await;
477        }
478    }
479    anyhow::bail!(
480        "revocation/session authority unreachable after {PROBE_ATTEMPTS} attempts: {last_error}"
481    )
482}