hyprstream_core/services/
revocation.rs1use 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
33const CHECK_TIMEOUT: Duration = Duration::from_secs(5);
37
38const PROBE_ATTEMPTS: u32 = 10;
42const PROBE_RETRY_DELAY: Duration = Duration::from_secs(2);
43
44pub(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
59fn 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
72pub(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
87fn 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
104pub struct PolicyAuthoritySessionRegistry {
109 client_provider: Arc<dyn Fn() -> anyhow::Result<Arc<PolicyClient>> + Send + Sync>,
110}
111
112impl PolicyAuthoritySessionRegistry {
113 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 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 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 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 (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 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
222pub struct PolicyAuthorityRevocationStore {
227 client_provider: Arc<dyn Fn() -> anyhow::Result<Arc<PolicyClient>> + Send + Sync>,
228}
229
230impl PolicyAuthorityRevocationStore {
231 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 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 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 (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
315pub 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 {
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 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 (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}