From c4bc865573792fa473117610b808cb727a4798f6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 9 Oct 2026 16:32:55 +0200 Subject: [PATCH 1/7] Map: name the clause that refuses an executed Heimdall refresh Co-Authored-By: Claude Opus 5.5 --- notes/ghostlight-verse-map.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/notes/ghostlight-verse-map.md b/notes/ghostlight-verse-map.md index bdfb753..aa5ba6a 100644 --- a/notes/ghostlight-verse-map.md +++ b/notes/ghostlight-verse-map.md @@ -148,7 +148,15 @@ from 21:04 the denial forever. Mechanism: that key can ever succeed, and `sessions_due_for_refresh` (`app_session.rs:247-268`) keeps offering the same candidate while `refresh_expires_at > now`. Which clause of `app_session.rs:293-299` fired at - 21:03 is not logged. + 21:03 is not logged, but only one is reachable: the session-id and account + clauses are pre-checked and revoked at `runtime.rs:1904-1916`, a revoked + session is never offered, and nothing else moves `access_revision`. That + leaves `input.access_revision() <= expected` (`app_session.rs:295`). Heimdall's + refresh reissues the claim with the refresh claim's `access_revision` + unchanged (`Heimdall/src/app.ts:716-724`; only logout bumps it, + `private-command-plane.ts:197`), so every real refresh is executed upstream + and refused locally, and the key `refresh:{sid}:{rev}` never changes within a + session. Question `ghostlight-verse:question:refresh-revision-contract`. ### The host From af7e5448301d3d500b6f8774fa82850e127ee46f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 9 Oct 2026 16:37:52 +0200 Subject: [PATCH 2/7] Refresh: apply an equal-revision receipt, key each refresh by its claim, revoke what cannot succeed Heimdall's access_revision is a revocation epoch, so a refresh receipt at the session's revision is the normal case (ruling refresh-revision-is-revocation-epoch). The loop pass moves behind a SessionRefresher port; a typed HeimdallDenied revokes the session, a backwards receipt revokes it, every local refusal names its clause, and the idempotency key derives from the claim being spent. Co-Authored-By: Claude Opus 5.5 --- crates/ghostlight-dungeon/src/app_session.rs | 84 ++++- crates/ghostlight-dungeon/src/heimdall.rs | 72 +++- crates/ghostlight-dungeon/src/runtime.rs | 346 ++++++++++++++++--- 3 files changed, 438 insertions(+), 64 deletions(-) diff --git a/crates/ghostlight-dungeon/src/app_session.rs b/crates/ghostlight-dungeon/src/app_session.rs index 1fd62fc..f35a449 100644 --- a/crates/ghostlight-dungeon/src/app_session.rs +++ b/crates/ghostlight-dungeon/src/app_session.rs @@ -46,6 +46,21 @@ struct AppSession { revoked_at: Option>, } +/// The clause by which the local commit refuses a refresh Heimdall executed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub(crate) enum RefreshRefusal { + #[error("local session was revoked during refresh")] + Revoked, + #[error("local session moved to another revision since the refresh candidate was taken")] + MovedSinceCandidate, + #[error("refresh receipt revision went backwards")] + RevisionWentBackwards, + #[error("refresh receipt names a different Heimdall session")] + SessionId, + #[error("refresh receipt names a different account")] + Account, +} + pub(crate) struct RefreshCandidate { pub(crate) cookie_hash: String, pub(crate) account_subject_hash: String, @@ -290,14 +305,25 @@ impl AppSessionOwner { .sessions .get_mut(cookie_hash) .context("local session vanished during refresh")?; - if session.revoked_at.is_some() - || session.access_revision != expected_access_revision - || input.access_revision() <= expected_access_revision - || session.heimdall_session_id != input.heimdall_session_id() - || session.account_subject_hash - != secret_hash(&format!("heimdall-account:{}", input.account_id())) + if session.revoked_at.is_some() { + return Err(RefreshRefusal::Revoked.into()); + } + if session.access_revision != expected_access_revision { + return Err(RefreshRefusal::MovedSinceCandidate.into()); + } + // Heimdall's access_revision is a revocation epoch: refresh rotates + // the token at the same revision, so equal is the normal receipt and + // only a lower one is a refusal. + if input.access_revision() < expected_access_revision { + return Err(RefreshRefusal::RevisionWentBackwards.into()); + } + if session.heimdall_session_id != input.heimdall_session_id() { + return Err(RefreshRefusal::SessionId.into()); + } + if session.account_subject_hash + != secret_hash(&format!("heimdall-account:{}", input.account_id())) { - bail!("local session changed during refresh"); + return Err(RefreshRefusal::Account.into()); } session.access_revision = input.access_revision(); session.verified_capabilities = input.capabilities().to_vec(); @@ -367,6 +393,16 @@ impl AppSessionOwner { } } +/// The idempotency key of the refresh that spends `refresh_claim`: a retry of +/// that refresh derives the same key, the next refresh (a new claim) a new one, +/// and the claim itself never leaves the process in it. +pub(crate) fn refresh_idempotency_key(refresh_claim: &str) -> String { + format!( + "refresh:{}", + secret_hash(&format!("heimdall-refresh-key:{refresh_claim}")) + ) +} + pub(crate) fn secret_hash(value: &str) -> String { format!("sha256:{:x}", Sha256::digest(value.as_bytes())) } @@ -787,6 +823,40 @@ mod tests { assert!(AppSessionOwner::open(&store_path, &key).is_err()); } + #[test] + fn a_refresh_for_a_session_that_moved_is_refused_by_name() { + let directory = tempfile::tempdir().unwrap(); + let key = directory.path().join("session.key"); + std::fs::write(&key, [5_u8; 32]).unwrap(); + let mut owner = + AppSessionOwner::open(directory.path().join("sessions.cc"), &key).unwrap(); + let cookie = owner + .create_session(VerifiedSessionAdmission::fixture( + "account", + "session", + 1, + Utc::now() + chrono::Duration::minutes(1), + Utc::now() + chrono::Duration::days(1), + "claim-0", + )) + .unwrap(); + let receipt = VerifiedSessionRefresh::fixture( + "account", + "session", + 1, + Utc::now() + chrono::Duration::minutes(1), + Utc::now() + chrono::Duration::days(1), + "claim-1", + ); + let error = owner + .apply_refresh(&secret_hash(&cookie), 0, receipt) + .unwrap_err(); + assert_eq!( + error.downcast_ref::(), + Some(&RefreshRefusal::MovedSinceCandidate) + ); + } + #[test] fn refresh_claim_is_encrypted_and_exactly_bound() { let directory = tempfile::tempdir().unwrap(); diff --git a/crates/ghostlight-dungeon/src/heimdall.rs b/crates/ghostlight-dungeon/src/heimdall.rs index 01345f6..8816536 100644 --- a/crates/ghostlight-dungeon/src/heimdall.rs +++ b/crates/ghostlight-dungeon/src/heimdall.rs @@ -30,6 +30,48 @@ const APP_SLUG: &str = "ghostlight"; const PRIVATE_SERVICE: &str = "heimdall.private.commands"; const PRIVATE_ENVELOPE_SCHEMA: &str = "heimdall.private_command_envelope.v1"; +/// Heimdall answered a private command with status denied. Distinct from a +/// transport failure so the refresh loop never reads a message string. +#[derive(Debug, thiserror::Error)] +#[error("Heimdall denied the private command: {diagnostics}")] +pub(crate) struct HeimdallDenied { + pub(crate) diagnostics: String, +} + +/// The two Heimdall calls the refresh loop makes, as a port so a scripted +/// Heimdall can stand in for the real one. +#[async_trait::async_trait] +pub(crate) trait SessionRefresher { + async fn refresh( + &self, + refresh_token: &str, + idempotency_key: &str, + ) -> anyhow::Result; + + async fn verify_refresh( + &self, + completion: AuthCompletionReceipt, + ) -> anyhow::Result; +} + +#[async_trait::async_trait] +impl SessionRefresher for HeimdallClient { + async fn refresh( + &self, + refresh_token: &str, + idempotency_key: &str, + ) -> anyhow::Result { + HeimdallClient::refresh(self, refresh_token, idempotency_key).await + } + + async fn verify_refresh( + &self, + completion: AuthCompletionReceipt, + ) -> anyhow::Result { + HeimdallClient::verify_refresh(self, completion).await + } +} + #[derive(Clone)] pub struct HeimdallClient { http: Client, @@ -325,6 +367,28 @@ impl VerifiedSessionAdmission { } } +#[cfg(test)] +impl VerifiedSessionRefresh { + pub(crate) fn fixture( + account_id: impl Into, + heimdall_session_id: impl Into, + access_revision: u64, + access_expires_at: DateTime, + refresh_expires_at: DateTime, + refresh_claim: impl Into, + ) -> Self { + Self(VerifiedSessionMaterial { + account_id: account_id.into(), + heimdall_session_id: heimdall_session_id.into(), + access_revision, + capabilities: vec!["app_access".into()], + access_expires_at, + refresh_expires_at, + refresh_claim: refresh_claim.into(), + }) + } +} + impl HeimdallClient { pub fn from_env( runtime_id: &str, @@ -581,10 +645,10 @@ impl HeimdallClient { bail!("Heimdall returned a non-operation response"); }; if status == "denied" { - bail!( - "Heimdall denied the private command: {}", - diagnostics.join("; ") - ); + return Err(HeimdallDenied { + diagnostics: diagnostics.join("; "), + } + .into()); } if payload_schema != PRIVATE_ENVELOPE_SCHEMA || payload_encoding != "messagepack-base64" { bail!("Heimdall returned the wrong private response contract"); diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index 6f83252..6a2b84c 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -1,9 +1,9 @@ //! One-process runtime for the sealed world owner. use crate::{ - app_session::AppSessionOwner, + app_session::{AppSessionOwner, RefreshRefusal}, eve::{self, EveCommandInvocation}, - heimdall::{self, HeimdallClient}, + heimdall::{self, HeimdallClient, HeimdallDenied, SessionRefresher}, idunn_health::{ IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT, ProcessWriteLeaseGuard, RuntimePresencePublisher, TARGET as GHOSTLIGHT_TARGET, @@ -1867,66 +1867,86 @@ async fn maintain_session_refresh(state: AppState) -> anyhow::Result<()> { interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { interval.tick().await; - let candidates = state - .sessions - .lock() - .await - .sessions_due_for_refresh(Utc::now(), chrono::Duration::minutes(2)) - .context("app-session refresh scan lost custody")?; - for candidate in candidates { - let idempotency = format!( - "refresh:{}:{}", - candidate.heimdall_session_id, candidate.access_revision - ); - let completion = match state - .heimdall - .refresh(&candidate.refresh_claim, &idempotency) - .await - { - Ok(value) => value, - Err(error) => { - tracing::warn!(%error, "Heimdall refresh transport unavailable"); - continue; - } - }; - let verified = match state.heimdall.verify_refresh(completion).await { - Ok(value) => value, - Err(error) => { - tracing::warn!(%error, "Heimdall refresh receipt was invalid"); - let mut sessions = state.sessions.lock().await; - if let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash) { - return Err(revoke_error) - .context("invalid Heimdall refresh could not revoke local custody"); - } - continue; - } - }; - if verified.heimdall_session_id() != candidate.heimdall_session_id - || crate::app_session::secret_hash(&format!( - "heimdall-account:{}", - verified.account_id() - )) != candidate.account_subject_hash - { - tracing::warn!("Heimdall refresh changed local session custody"); - let mut sessions = state.sessions.lock().await; + refresh_due_sessions(&state.sessions, state.heimdall.as_ref()).await?; + } +} + +/// One pass of the refresh loop over every session due for refresh. +async fn refresh_due_sessions( + sessions: &Mutex, + heimdall: &impl SessionRefresher, +) -> anyhow::Result<()> { + let candidates = sessions + .lock() + .await + .sessions_due_for_refresh(Utc::now(), chrono::Duration::minutes(2)) + .context("app-session refresh scan lost custody")?; + for candidate in candidates { + let idempotency = crate::app_session::refresh_idempotency_key(&candidate.refresh_claim); + let completion = match heimdall.refresh(&candidate.refresh_claim, &idempotency).await { + Ok(value) => value, + Err(error) if error.downcast_ref::().is_some() => { + // Heimdall refused this refresh claim: it can never succeed. + tracing::warn!(%error, "Heimdall denied the refresh; revoking the local session"); + let mut sessions = sessions.lock().await; if let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash) { return Err(revoke_error) - .context("changed Heimdall custody could not revoke local session"); + .context("denied Heimdall refresh could not revoke local custody"); } continue; } - let mut sessions = state.sessions.lock().await; - if let Err(error) = - sessions.apply_refresh(&candidate.cookie_hash, candidate.access_revision, verified) - { - if sessions.is_healthy() { - tracing::warn!(%error, "local app session rejected Heimdall refresh"); - } else { - return Err(error).context("app-session refresh commit lost custody"); + Err(error) => { + tracing::warn!(%error, "Heimdall refresh transport unavailable"); + continue; + } + }; + let verified = match heimdall.verify_refresh(completion).await { + Ok(value) => value, + Err(error) => { + tracing::warn!(%error, "Heimdall refresh receipt was invalid"); + let mut sessions = sessions.lock().await; + if let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash) { + return Err(revoke_error) + .context("invalid Heimdall refresh could not revoke local custody"); } + continue; + } + }; + if verified.heimdall_session_id() != candidate.heimdall_session_id + || crate::app_session::secret_hash(&format!( + "heimdall-account:{}", + verified.account_id() + )) != candidate.account_subject_hash + { + tracing::warn!("Heimdall refresh changed local session custody"); + let mut sessions = sessions.lock().await; + if let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash) { + return Err(revoke_error) + .context("changed Heimdall custody could not revoke local session"); + } + continue; + } + let mut sessions = sessions.lock().await; + if let Err(error) = + sessions.apply_refresh(&candidate.cookie_hash, candidate.access_revision, verified) + { + if !sessions.is_healthy() { + return Err(error).context("app-session refresh commit lost custody"); + } + tracing::warn!(%error, "local app session refused Heimdall refresh"); + // The refresh claim is spent upstream, so a receipt that went + // backwards leaves nothing to retry. A session that merely moved + // is newer state: the next scan decides. + if error.downcast_ref::() + == Some(&RefreshRefusal::RevisionWentBackwards) + && let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash) + { + return Err(revoke_error) + .context("backwards Heimdall refresh could not revoke local session"); } } } + Ok(()) } /// Idunn publishes Expected and starts the unit before it observes the @@ -6370,3 +6390,223 @@ mod tests { assert_eq!(after.revision, before.revision + 1); } } + +/// The refresh loop against a scripted Heimdall: it answers each call from a +/// queue and records the claim and idempotency key it was sent. +#[cfg(test)] +mod refresh_loop_tests { + use super::*; + use crate::heimdall::{AuthCompletionReceipt, VerifiedSessionRefresh}; + use std::{collections::VecDeque, sync::Mutex as StdMutex}; + + enum Reply { + Deny, + Timeout, + Receipt { revision: u64, claim: &'static str }, + } + + #[derive(Default)] + struct ScriptedHeimdall { + replies: StdMutex>, + pending: StdMutex>, + calls: StdMutex>, + } + + impl ScriptedHeimdall { + fn answering(replies: Vec) -> Self { + Self { + replies: StdMutex::new(replies.into()), + ..Self::default() + } + } + + fn calls(&self) -> Vec<(String, String)> { + self.calls.lock().unwrap().clone() + } + } + + #[async_trait::async_trait] + impl SessionRefresher for ScriptedHeimdall { + async fn refresh( + &self, + refresh_token: &str, + idempotency_key: &str, + ) -> anyhow::Result { + self.calls + .lock() + .unwrap() + .push((refresh_token.into(), idempotency_key.into())); + match self.replies.lock().unwrap().pop_front().expect("scripted reply") { + Reply::Deny => Err(HeimdallDenied { + diagnostics: "Idempotency key was reused".into(), + } + .into()), + Reply::Timeout => bail!("Heimdall private command timed out"), + Reply::Receipt { revision, claim } => { + *self.pending.lock().unwrap() = Some(VerifiedSessionRefresh::fixture( + "operator-account", + "heimdall-session", + revision, + Utc::now() + chrono::Duration::seconds(90), + Utc::now() + chrono::Duration::days(1), + claim, + )); + Ok(AuthCompletionReceipt { + status: "authenticated".into(), + handle: None, + error: None, + account: None, + session: None, + access_token: None, + refresh_token: None, + refresh: None, + shared_capabilities: Vec::new(), + }) + } + } + } + + async fn verify_refresh( + &self, + _completion: AuthCompletionReceipt, + ) -> anyhow::Result { + Ok(self.pending.lock().unwrap().take().expect("scripted receipt")) + } + } + + /// A store holding one live session at `revision` whose access expires in + /// a minute, so every pass finds it due. + fn due_session(revision: u64) -> (tempfile::TempDir, Mutex, String) { + let directory = tempfile::tempdir().unwrap(); + let key = directory.path().join("session.key"); + std::fs::write(&key, [23_u8; 32]).unwrap(); + let mut owner = AppSessionOwner::open(directory.path().join("sessions.cc"), &key).unwrap(); + let cookie = owner + .create_session(heimdall::VerifiedSessionAdmission::fixture( + "operator-account", + "heimdall-session", + revision, + Utc::now() + chrono::Duration::seconds(60), + Utc::now() + chrono::Duration::days(1), + "claim-0", + )) + .unwrap(); + (directory, Mutex::new(owner), cookie) + } + + async fn is_live(sessions: &Mutex, cookie: &str) -> bool { + sessions + .lock() + .await + .account_for_cookie(cookie, Utc::now()) + .unwrap() + .is_some() + } + + #[derive(Clone, Default)] + struct Captured(std::sync::Arc>>); + + impl std::io::Write for Captured { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Captured { + type Writer = Captured; + + fn make_writer(&'a self) -> Captured { + self.clone() + } + } + + #[tokio::test] + async fn a_real_refresh_at_an_equal_revision_is_applied_and_the_session_stays_live() { + let (_directory, sessions, cookie) = due_session(1); + let heimdall = ScriptedHeimdall::answering(vec![ + Reply::Receipt { revision: 1, claim: "claim-1" }, + Reply::Timeout, + ]); + refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + assert!(is_live(&sessions, &cookie).await); + // The wrapped claim is the receipt's: the next refresh spends it. + refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + assert_eq!(heimdall.calls()[1].0, "claim-1"); + assert!(is_live(&sessions, &cookie).await); + } + + #[tokio::test] + async fn a_retry_of_the_same_refresh_sends_the_same_key() { + let (_directory, sessions, cookie) = due_session(1); + let heimdall = ScriptedHeimdall::answering(vec![Reply::Timeout, Reply::Timeout]); + refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + let calls = heimdall.calls(); + assert_eq!(calls.len(), 2, "a transport failure leaves the session offered"); + assert_eq!(calls[0], calls[1]); + assert!(is_live(&sessions, &cookie).await); + } + + #[tokio::test] + async fn the_refresh_after_a_successful_one_sends_a_new_key() { + let (_directory, sessions, _cookie) = due_session(1); + let heimdall = ScriptedHeimdall::answering(vec![ + Reply::Receipt { revision: 1, claim: "claim-1" }, + Reply::Timeout, + ]); + refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + let calls = heimdall.calls(); + assert_ne!(calls[0].1, calls[1].1); + assert!(calls.iter().all(|(claim, key)| !key.contains(claim))); + } + + #[tokio::test] + async fn a_receipt_with_a_lower_revision_is_refused_and_the_session_revoked() { + let (_directory, sessions, cookie) = due_session(2); + let heimdall = ScriptedHeimdall::answering(vec![ + Reply::Receipt { revision: 1, claim: "claim-1" }, + Reply::Timeout, + ]); + refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + assert!(!is_live(&sessions, &cookie).await); + refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + assert_eq!(heimdall.calls().len(), 1, "a revoked session is not offered again"); + } + + #[tokio::test] + async fn a_heimdall_denial_revokes_the_session_and_it_is_not_offered_again() { + let (_directory, sessions, cookie) = due_session(1); + let heimdall = ScriptedHeimdall::answering(vec![Reply::Deny, Reply::Timeout]); + refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + assert!(!is_live(&sessions, &cookie).await); + refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + assert_eq!(heimdall.calls().len(), 1); + } + + #[tokio::test] + async fn a_local_refusal_logs_the_clause_that_fired() { + let (_directory, sessions, _cookie) = due_session(2); + let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt { + revision: 1, + claim: "claim-1", + }]); + let captured = Captured::default(); + let subscriber = tracing_subscriber::fmt() + .with_writer(captured.clone()) + .with_ansi(false) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + let logged = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap(); + assert!( + logged.contains("refresh receipt revision went backwards"), + "{logged}" + ); + } +} From 1b31bfc39963cb1c3d5cd6817ab73c888ec3b4d0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 9 Oct 2026 16:49:22 +0200 Subject: [PATCH 3/7] Refresh tests: pin the denied-status split and the session and account custody checks Mutation survivors of the first cut: the status comparison inside invoke (now refuse_denied, tested directly) and the session-or-account custody check (a receipt for another session, or another account, revokes). Co-Authored-By: Claude Opus 5.5 --- crates/ghostlight-dungeon/src/heimdall.rs | 28 ++++++++++++++++++----- crates/ghostlight-dungeon/src/runtime.rs | 28 ++++++++++++++++++++--- 2 files changed, 47 insertions(+), 9 deletions(-) diff --git a/crates/ghostlight-dungeon/src/heimdall.rs b/crates/ghostlight-dungeon/src/heimdall.rs index 8816536..671cbe6 100644 --- a/crates/ghostlight-dungeon/src/heimdall.rs +++ b/crates/ghostlight-dungeon/src/heimdall.rs @@ -644,12 +644,7 @@ impl HeimdallClient { else { bail!("Heimdall returned a non-operation response"); }; - if status == "denied" { - return Err(HeimdallDenied { - diagnostics: diagnostics.join("; "), - } - .into()); - } + refuse_denied(&status, &diagnostics)?; if payload_schema != PRIVATE_ENVELOPE_SCHEMA || payload_encoding != "messagepack-base64" { bail!("Heimdall returned the wrong private response contract"); } @@ -659,6 +654,18 @@ impl HeimdallClient { } } +/// A response with status denied is Heimdall's answer, not a transport +/// failure: it becomes the typed `HeimdallDenied`. +fn refuse_denied(status: &str, diagnostics: &[String]) -> anyhow::Result<()> { + if status == "denied" { + return Err(HeimdallDenied { + diagnostics: diagnostics.join("; "), + } + .into()); + } + Ok(()) +} + fn validate_private_response_binding( envelope: &PrivateEnvelope, operation: &str, @@ -1104,6 +1111,15 @@ mod tests { } } + #[test] + fn a_denied_status_is_the_typed_denial_and_any_other_status_passes() { + let diagnostics = vec!["Idempotency key was reused".to_owned()]; + let denial = refuse_denied("denied", &diagnostics).unwrap_err(); + assert!(denial.downcast_ref::().is_some()); + assert!(denial.to_string().contains("Idempotency key was reused")); + refuse_denied("accepted", &diagnostics).unwrap(); + } + #[test] fn private_responses_are_bound_to_the_exact_app_and_request() { let secret = "fixture-shared-secret"; diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index 6a2b84c..6de4527 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -6403,6 +6403,10 @@ mod refresh_loop_tests { Deny, Timeout, Receipt { revision: u64, claim: &'static str }, + /// A receipt for the same claim but another Heimdall session. + OtherSession, + /// A receipt for the same claim but another account. + OtherAccount, } #[derive(Default)] @@ -6442,10 +6446,18 @@ mod refresh_loop_tests { } .into()), Reply::Timeout => bail!("Heimdall private command timed out"), - Reply::Receipt { revision, claim } => { + reply @ (Reply::Receipt { .. } | Reply::OtherSession | Reply::OtherAccount) => { + let (account, session, revision, claim) = match reply { + Reply::OtherSession => ("operator-account", "other-session", 1, "claim-1"), + Reply::OtherAccount => ("other-account", "heimdall-session", 1, "claim-1"), + Reply::Receipt { revision, claim } => { + ("operator-account", "heimdall-session", revision, claim) + } + _ => unreachable!("matched above"), + }; *self.pending.lock().unwrap() = Some(VerifiedSessionRefresh::fixture( - "operator-account", - "heimdall-session", + account, + session, revision, Utc::now() + chrono::Duration::seconds(90), Utc::now() + chrono::Duration::days(1), @@ -6579,6 +6591,16 @@ mod refresh_loop_tests { assert_eq!(heimdall.calls().len(), 1, "a revoked session is not offered again"); } + #[tokio::test] + async fn a_receipt_for_another_session_or_account_revokes_the_local_session() { + for reply in [Reply::OtherSession, Reply::OtherAccount] { + let (_directory, sessions, cookie) = due_session(1); + let heimdall = ScriptedHeimdall::answering(vec![reply]); + refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + assert!(!is_live(&sessions, &cookie).await); + } + } + #[tokio::test] async fn a_heimdall_denial_revokes_the_session_and_it_is_not_offered_again() { let (_directory, sessions, cookie) = due_session(1); From 2b6e8c78267273da44209f47acc3571862fe336b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 9 Oct 2026 17:21:18 +0200 Subject: [PATCH 4/7] Heimdall: type the unavailable-keys failure and cache the signing keys for a bounded time A JWKS fetch failure is now VerificationUnavailable, distinct from a receipt that positively fails verification. The fetched key set is cached for five minutes. Co-Authored-By: Claude Opus 5.5 --- crates/ghostlight-dungeon/src/heimdall.rs | 110 ++++++++++++++++++---- 1 file changed, 93 insertions(+), 17 deletions(-) diff --git a/crates/ghostlight-dungeon/src/heimdall.rs b/crates/ghostlight-dungeon/src/heimdall.rs index 671cbe6..7f32c9b 100644 --- a/crates/ghostlight-dungeon/src/heimdall.rs +++ b/crates/ghostlight-dungeon/src/heimdall.rs @@ -15,7 +15,10 @@ use cultnet_rs::{ CultNetRudpSocketTransportOptions, }; use hmac::{Hmac, Mac}; -use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header, jwk::JwkSet}; +use jsonwebtoken::{ + Algorithm, DecodingKey, Validation, decode, decode_header, + jwk::{Jwk, JwkSet}, +}; use rand::RngCore; use reqwest::Client; use serde::{Deserialize, Serialize, de::DeserializeOwned}; @@ -23,6 +26,7 @@ use sha2::{Digest, Sha256}; use std::{ net::{SocketAddr, UdpSocket}, path::PathBuf, + sync::{Arc, Mutex as StdMutex}, time::{Duration, Instant}, }; @@ -38,6 +42,40 @@ pub(crate) struct HeimdallDenied { pub(crate) diagnostics: String, } +/// Heimdall's signing keys could not be fetched, so a receipt could not be +/// judged either way. Distinct from a receipt that positively fails +/// verification: the refresh loop keeps the receipt for this and revokes for +/// that. +#[derive(Debug, thiserror::Error)] +#[error("Heimdall signing keys unavailable: {0}")] +pub(crate) struct VerificationUnavailable(pub(crate) String); + +/// How long a fetched signing-key set is trusted before it is fetched again. +const JWKS_TTL: Duration = Duration::from_secs(300); + +/// The last fetched signing-key set and when it was fetched. +#[derive(Default)] +pub(crate) struct JwksCache { + fetched: Option<(Instant, JwkSet)>, +} + +impl JwksCache { + /// The key published under `kid`, if the cached set is still fresh and + /// holds it. A miss on a fresh set still refetches, so a rotated key is + /// found. + pub(crate) fn key(&self, kid: &str, now: Instant) -> Option { + let (fetched_at, set) = self.fetched.as_ref()?; + if now.saturating_duration_since(*fetched_at) >= JWKS_TTL { + return None; + } + set.find(kid).cloned() + } + + pub(crate) fn store(&mut self, set: JwkSet, now: Instant) { + self.fetched = Some((now, set)); + } +} + /// The two Heimdall calls the refresh loop makes, as a port so a scripted /// Heimdall can stand in for the real one. #[async_trait::async_trait] @@ -82,6 +120,7 @@ pub struct HeimdallClient { boundary_locator: HeimdallBoundaryLocator, runtime_id: String, shared_secret: String, + jwks: Arc>, } /// Idunn's projection of a managed Heimdall dependency, when Heimdall is a @@ -226,7 +265,7 @@ pub struct AuthNavigation { pub allowed_origins: Vec, } -#[derive(Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuthCompletionReceipt { pub status: String, @@ -241,12 +280,12 @@ pub struct AuthCompletionReceipt { pub shared_capabilities: Vec, } -#[derive(Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize)] pub struct AccountSummary { pub id: String, } -#[derive(Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct HeimdallSession { pub account_id: String, @@ -256,7 +295,7 @@ pub struct HeimdallSession { pub expires_at: String, } -#[derive(Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RefreshSummary { pub expires_at: String, @@ -424,6 +463,7 @@ impl HeimdallClient { }, runtime_id: runtime_id.into(), shared_secret, + jwks: Arc::default(), }) } @@ -447,6 +487,7 @@ impl HeimdallClient { }), runtime_id: "ghostlight-test-runtime".into(), shared_secret: "fixture-secret".into(), + jwks: Arc::default(), } } @@ -565,28 +606,44 @@ impl HeimdallClient { )?)) } - async fn verify_access(&self, token: &str) -> anyhow::Result { - let header = decode_header(token)?; - if header.alg != Algorithm::EdDSA { - bail!("Heimdall used an unsupported signing algorithm"); - } - let kid = header.kid.context("Heimdall token omitted kid")?; - let jwks: JwkSet = self + async fn fetch_jwks(&self) -> anyhow::Result { + Ok(self .http .get(format!("{}/.well-known/jwks.json", self.issuer)) .send() .await? .error_for_status()? .json() - .await?; - let jwk = jwks - .find(&kid) - .context("Heimdall signing key was not published")?; + .await?) + } + + async fn verify_access(&self, token: &str) -> anyhow::Result { + let header = decode_header(token)?; + if header.alg != Algorithm::EdDSA { + bail!("Heimdall used an unsupported signing algorithm"); + } + let kid = header.kid.context("Heimdall token omitted kid")?; + let cached = self.jwks.lock().expect("jwks cache").key(&kid, Instant::now()); + let jwk = match cached { + Some(jwk) => jwk, + None => { + let set = self + .fetch_jwks() + .await + .map_err(|error| VerificationUnavailable(format!("{error:#}")))?; + let jwk = set.find(&kid).cloned(); + self.jwks + .lock() + .expect("jwks cache") + .store(set, Instant::now()); + jwk.context("Heimdall signing key was not published")? + } + }; let mut validation = Validation::new(Algorithm::EdDSA); validation.set_audience(&[APP_SLUG]); validation.set_issuer(&[self.issuer.as_str()]); let claims = - decode::(token, &DecodingKey::from_jwk(jwk)?, &validation)?.claims; + decode::(token, &DecodingKey::from_jwk(&jwk)?, &validation)?.claims; if claims.typ != "heimdall_access" || claims.aud != APP_SLUG || claims.iss != self.issuer @@ -1111,6 +1168,25 @@ mod tests { } } + fn key_set(kid: &str) -> JwkSet { + serde_json::from_value(serde_json::json!({ + "keys": [{"kty": "OKP", "crv": "Ed25519", "kid": kid, + "x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}] + })) + .unwrap() + } + + #[test] + fn a_cached_key_set_serves_until_its_ttl_and_misses_an_unpublished_kid() { + let start = Instant::now(); + let mut cache = JwksCache::default(); + assert!(cache.key("k1", start).is_none(), "an empty cache has no key"); + cache.store(key_set("k1"), start); + assert!(cache.key("k1", start + Duration::from_secs(299)).is_some()); + assert!(cache.key("k2", start).is_none(), "a rotated-in kid refetches"); + assert!(cache.key("k1", start + JWKS_TTL).is_none(), "stale at the ttl"); + } + #[test] fn a_denied_status_is_the_typed_denial_and_any_other_status_passes() { let diagnostics = vec!["Idempotency key was reused".to_owned()]; From 72a98d8468d20dcd6cd3d8b0baea11978b458966 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 9 Oct 2026 17:21:23 +0200 Subject: [PATCH 5/7] Refresh: keep a receipt whose keys were unavailable, and pin the loop and the branch rules The refresh pass keeps a spent-upstream receipt when verification could not fetch the signing keys and verifies it on the next pass instead of refreshing again; only a positive verification failure revokes. The loop body is run_refresh_loop, tested for calling the pass; tests pin that a moved session is not revoked and a higher revision is applied. Co-Authored-By: Claude Opus 5.5 --- crates/ghostlight-dungeon/src/runtime.rs | 272 ++++++++++++++++++++--- 1 file changed, 236 insertions(+), 36 deletions(-) diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index 6de4527..9d1e6c7 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -3,7 +3,7 @@ use crate::{ app_session::{AppSessionOwner, RefreshRefusal}, eve::{self, EveCommandInvocation}, - heimdall::{self, HeimdallClient, HeimdallDenied, SessionRefresher}, + heimdall::{self, HeimdallClient, HeimdallDenied, SessionRefresher, VerificationUnavailable}, idunn_health::{ IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT, ProcessWriteLeaseGuard, RuntimePresencePublisher, TARGET as GHOSTLIGHT_TARGET, @@ -41,7 +41,7 @@ use cultnet_rs::{ use serde::Deserialize; use serde_json::{Value, json}; use std::{ - collections::BTreeMap, + collections::{BTreeMap, HashMap}, convert::Infallible, fs, net::SocketAddr, @@ -1863,45 +1863,86 @@ fn session_cookie(raw: &str, expires_at: DateTime, now: DateTime) -> H } async fn maintain_session_refresh(state: AppState) -> anyhow::Result<()> { - let mut interval = tokio::time::interval(Duration::from_secs(60)); + run_refresh_loop( + &state.sessions, + state.heimdall.as_ref(), + Duration::from_secs(60), + ) + .await +} + +/// Runs `refresh_due_sessions` once per `period` for as long as the daemon +/// serves. The receipts it holds are Heimdall refreshes already spent +/// upstream whose verification could not yet be judged. +async fn run_refresh_loop( + sessions: &Mutex, + heimdall: &impl SessionRefresher, + period: Duration, +) -> anyhow::Result<()> { + let mut interval = tokio::time::interval(period); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + let mut unverified = HashMap::new(); loop { interval.tick().await; - refresh_due_sessions(&state.sessions, state.heimdall.as_ref()).await?; + refresh_due_sessions(sessions, heimdall, &mut unverified).await?; } } /// One pass of the refresh loop over every session due for refresh. +/// `unverified` holds, per session, a receipt Heimdall issued for a refresh +/// that is already spent upstream but whose signing keys could not be +/// fetched: the next pass verifies it instead of refreshing again. async fn refresh_due_sessions( sessions: &Mutex, heimdall: &impl SessionRefresher, + unverified: &mut HashMap, ) -> anyhow::Result<()> { let candidates = sessions .lock() .await .sessions_due_for_refresh(Utc::now(), chrono::Duration::minutes(2)) .context("app-session refresh scan lost custody")?; + unverified.retain(|cookie_hash, _| { + candidates + .iter() + .any(|candidate| &candidate.cookie_hash == cookie_hash) + }); for candidate in candidates { - let idempotency = crate::app_session::refresh_idempotency_key(&candidate.refresh_claim); - let completion = match heimdall.refresh(&candidate.refresh_claim, &idempotency).await { - Ok(value) => value, - Err(error) if error.downcast_ref::().is_some() => { - // Heimdall refused this refresh claim: it can never succeed. - tracing::warn!(%error, "Heimdall denied the refresh; revoking the local session"); - let mut sessions = sessions.lock().await; - if let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash) { - return Err(revoke_error) - .context("denied Heimdall refresh could not revoke local custody"); + let completion = match unverified.remove(&candidate.cookie_hash) { + Some(completion) => completion, + None => { + let idempotency = + crate::app_session::refresh_idempotency_key(&candidate.refresh_claim); + match heimdall.refresh(&candidate.refresh_claim, &idempotency).await { + Ok(value) => value, + Err(error) if error.downcast_ref::().is_some() => { + // Heimdall refused this refresh claim: it can never succeed. + tracing::warn!(%error, "Heimdall denied the refresh; revoking the local session"); + let mut sessions = sessions.lock().await; + if let Err(revoke_error) = + sessions.revoke_cookie_hash(&candidate.cookie_hash) + { + return Err(revoke_error) + .context("denied Heimdall refresh could not revoke local custody"); + } + continue; + } + Err(error) => { + tracing::warn!(%error, "Heimdall refresh transport unavailable"); + continue; + } } - continue; - } - Err(error) => { - tracing::warn!(%error, "Heimdall refresh transport unavailable"); - continue; } }; - let verified = match heimdall.verify_refresh(completion).await { + let verified = match heimdall.verify_refresh(completion.clone()).await { Ok(value) => value, + Err(error) if error.downcast_ref::().is_some() => { + // The claim is spent upstream and the receipt may be genuine: + // keep it and verify again on the next pass. + tracing::warn!(%error, "Heimdall refresh receipt could not be verified yet"); + unverified.insert(candidate.cookie_hash.clone(), completion); + continue; + } Err(error) => { tracing::warn!(%error, "Heimdall refresh receipt was invalid"); let mut sessions = sessions.lock().await; @@ -6396,7 +6437,7 @@ mod tests { #[cfg(test)] mod refresh_loop_tests { use super::*; - use crate::heimdall::{AuthCompletionReceipt, VerifiedSessionRefresh}; + use crate::heimdall::{AuthCompletionReceipt, VerificationUnavailable, VerifiedSessionRefresh}; use std::{collections::VecDeque, sync::Mutex as StdMutex}; enum Reply { @@ -6409,9 +6450,22 @@ mod refresh_loop_tests { OtherAccount, } + /// What `verify_refresh` answers; an empty queue accepts the receipt. + enum Verdict { + /// The signing keys could not be fetched. + Unavailable, + /// The receipt positively fails verification. + Invalid, + } + #[derive(Default)] struct ScriptedHeimdall { replies: StdMutex>, + verdicts: StdMutex>, + verifications: StdMutex, + /// While answering a refresh, apply a newer revision to this store, + /// as a concurrent refresh of the same session would. + moving: Option>>, pending: StdMutex>, calls: StdMutex>, } @@ -6424,6 +6478,15 @@ mod refresh_loop_tests { } } + fn verifying(mut self, verdicts: Vec) -> Self { + self.verdicts = StdMutex::new(verdicts.into()); + self + } + + fn verifications(&self) -> usize { + *self.verifications.lock().unwrap() + } + fn calls(&self) -> Vec<(String, String)> { self.calls.lock().unwrap().clone() } @@ -6440,6 +6503,27 @@ mod refresh_loop_tests { .lock() .unwrap() .push((refresh_token.into(), idempotency_key.into())); + if let Some(sessions) = &self.moving { + let mut sessions = sessions.lock().await; + let candidate = sessions + .sessions_due_for_refresh(Utc::now(), chrono::Duration::minutes(2)) + .unwrap() + .remove(0); + sessions + .apply_refresh( + &candidate.cookie_hash, + candidate.access_revision, + VerifiedSessionRefresh::fixture( + "operator-account", + "heimdall-session", + candidate.access_revision + 1, + Utc::now() + chrono::Duration::seconds(90), + Utc::now() + chrono::Duration::days(1), + "claim-moved", + ), + ) + .unwrap(); + } match self.replies.lock().unwrap().pop_front().expect("scripted reply") { Reply::Deny => Err(HeimdallDenied { diagnostics: "Idempotency key was reused".into(), @@ -6482,13 +6566,22 @@ mod refresh_loop_tests { &self, _completion: AuthCompletionReceipt, ) -> anyhow::Result { - Ok(self.pending.lock().unwrap().take().expect("scripted receipt")) + *self.verifications.lock().unwrap() += 1; + match self.verdicts.lock().unwrap().pop_front() { + Some(Verdict::Unavailable) => { + Err(VerificationUnavailable("jwks fetch timed out".into()).into()) + } + Some(Verdict::Invalid) => bail!("Heimdall access token signature is invalid"), + None => Ok(self.pending.lock().unwrap().take().expect("scripted receipt")), + } } } /// A store holding one live session at `revision` whose access expires in /// a minute, so every pass finds it due. - fn due_session(revision: u64) -> (tempfile::TempDir, Mutex, String) { + fn due_session( + revision: u64, + ) -> (tempfile::TempDir, std::sync::Arc>, String) { let directory = tempfile::tempdir().unwrap(); let key = directory.path().join("session.key"); std::fs::write(&key, [23_u8; 32]).unwrap(); @@ -6503,7 +6596,14 @@ mod refresh_loop_tests { "claim-0", )) .unwrap(); - (directory, Mutex::new(owner), cookie) + (directory, std::sync::Arc::new(Mutex::new(owner)), cookie) + } + + /// One refresh pass with no receipt carried over from an earlier one. + async fn pass(sessions: &Mutex, heimdall: &ScriptedHeimdall) { + refresh_due_sessions(sessions, heimdall, &mut HashMap::new()) + .await + .unwrap(); } async fn is_live(sessions: &Mutex, cookie: &str) -> bool { @@ -6544,10 +6644,10 @@ mod refresh_loop_tests { Reply::Receipt { revision: 1, claim: "claim-1" }, Reply::Timeout, ]); - refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + pass(&sessions, &heimdall).await; assert!(is_live(&sessions, &cookie).await); // The wrapped claim is the receipt's: the next refresh spends it. - refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + pass(&sessions, &heimdall).await; assert_eq!(heimdall.calls()[1].0, "claim-1"); assert!(is_live(&sessions, &cookie).await); } @@ -6556,8 +6656,8 @@ mod refresh_loop_tests { async fn a_retry_of_the_same_refresh_sends_the_same_key() { let (_directory, sessions, cookie) = due_session(1); let heimdall = ScriptedHeimdall::answering(vec![Reply::Timeout, Reply::Timeout]); - refresh_due_sessions(&sessions, &heimdall).await.unwrap(); - refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + pass(&sessions, &heimdall).await; + pass(&sessions, &heimdall).await; let calls = heimdall.calls(); assert_eq!(calls.len(), 2, "a transport failure leaves the session offered"); assert_eq!(calls[0], calls[1]); @@ -6571,8 +6671,8 @@ mod refresh_loop_tests { Reply::Receipt { revision: 1, claim: "claim-1" }, Reply::Timeout, ]); - refresh_due_sessions(&sessions, &heimdall).await.unwrap(); - refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + pass(&sessions, &heimdall).await; + pass(&sessions, &heimdall).await; let calls = heimdall.calls(); assert_ne!(calls[0].1, calls[1].1); assert!(calls.iter().all(|(claim, key)| !key.contains(claim))); @@ -6585,9 +6685,9 @@ mod refresh_loop_tests { Reply::Receipt { revision: 1, claim: "claim-1" }, Reply::Timeout, ]); - refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + pass(&sessions, &heimdall).await; assert!(!is_live(&sessions, &cookie).await); - refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + pass(&sessions, &heimdall).await; assert_eq!(heimdall.calls().len(), 1, "a revoked session is not offered again"); } @@ -6596,7 +6696,7 @@ mod refresh_loop_tests { for reply in [Reply::OtherSession, Reply::OtherAccount] { let (_directory, sessions, cookie) = due_session(1); let heimdall = ScriptedHeimdall::answering(vec![reply]); - refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + pass(&sessions, &heimdall).await; assert!(!is_live(&sessions, &cookie).await); } } @@ -6605,9 +6705,9 @@ mod refresh_loop_tests { async fn a_heimdall_denial_revokes_the_session_and_it_is_not_offered_again() { let (_directory, sessions, cookie) = due_session(1); let heimdall = ScriptedHeimdall::answering(vec![Reply::Deny, Reply::Timeout]); - refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + pass(&sessions, &heimdall).await; assert!(!is_live(&sessions, &cookie).await); - refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + pass(&sessions, &heimdall).await; assert_eq!(heimdall.calls().len(), 1); } @@ -6624,11 +6724,111 @@ mod refresh_loop_tests { .with_ansi(false) .finish(); let _guard = tracing::subscriber::set_default(subscriber); - refresh_due_sessions(&sessions, &heimdall).await.unwrap(); + pass(&sessions, &heimdall).await; let logged = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap(); assert!( logged.contains("refresh receipt revision went backwards"), "{logged}" ); } + + #[tokio::test] + async fn a_receipt_whose_keys_were_unavailable_is_kept_and_applied_on_the_next_pass() { + let (_directory, sessions, cookie) = due_session(1); + let heimdall = ScriptedHeimdall::answering(vec![ + Reply::Receipt { revision: 1, claim: "claim-1" }, + Reply::Timeout, + ]) + .verifying(vec![Verdict::Unavailable]); + let mut unverified = HashMap::new(); + refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap(); + assert!(is_live(&sessions, &cookie).await, "unavailable keys do not revoke"); + assert_eq!(unverified.len(), 1); + refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap(); + assert_eq!(heimdall.calls().len(), 1, "the spent claim is not sent again"); + assert_eq!(heimdall.verifications(), 2); + assert!(unverified.is_empty(), "an applied receipt is not kept"); + assert!(is_live(&sessions, &cookie).await); + // The applied receipt's claim is the one the next refresh spends. + refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap(); + assert_eq!(heimdall.calls()[1].0, "claim-1"); + assert_eq!(heimdall.verifications(), 2, "the receipt was applied once"); + } + + #[tokio::test] + async fn a_receipt_that_positively_fails_verification_revokes_and_is_not_kept() { + let (_directory, sessions, cookie) = due_session(1); + let heimdall = ScriptedHeimdall::answering(vec![ + Reply::Receipt { revision: 1, claim: "claim-1" }, + Reply::Timeout, + ]) + .verifying(vec![Verdict::Invalid]); + let mut unverified = HashMap::new(); + refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap(); + assert!(!is_live(&sessions, &cookie).await); + assert!(unverified.is_empty()); + refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap(); + assert_eq!(heimdall.calls().len(), 1); + assert_eq!(heimdall.verifications(), 1); + } + + #[tokio::test] + async fn a_kept_receipt_for_a_session_that_is_gone_is_dropped() { + let (_directory, sessions, cookie) = due_session(1); + let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt { + revision: 1, + claim: "claim-1", + }]) + .verifying(vec![Verdict::Unavailable]); + let mut unverified = HashMap::new(); + refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap(); + assert_eq!(unverified.len(), 1); + let cookie_hash = unverified.keys().next().unwrap().clone(); + sessions.lock().await.revoke_cookie_hash(&cookie_hash).unwrap(); + refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap(); + assert!(unverified.is_empty()); + assert!(!is_live(&sessions, &cookie).await); + assert_eq!(heimdall.verifications(), 1); + } + + #[tokio::test] + async fn a_session_that_moved_while_refreshing_is_not_revoked() { + let (_directory, sessions, cookie) = due_session(1); + let mut heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt { + revision: 1, + claim: "claim-1", + }]); + heimdall.moving = Some(sessions.clone()); + pass(&sessions, &heimdall).await; + assert!(is_live(&sessions, &cookie).await); + } + + #[tokio::test] + async fn a_receipt_with_a_higher_revision_is_applied() { + let (_directory, sessions, cookie) = due_session(1); + let heimdall = ScriptedHeimdall::answering(vec![ + Reply::Receipt { revision: 2, claim: "claim-1" }, + Reply::Receipt { revision: 1, claim: "claim-2" }, + ]); + pass(&sessions, &heimdall).await; + assert!(is_live(&sessions, &cookie).await); + // The session now sits at revision 2, so a revision-1 receipt is + // backwards. + pass(&sessions, &heimdall).await; + assert_eq!(heimdall.calls()[1].0, "claim-1"); + assert!(!is_live(&sessions, &cookie).await); + } + + #[tokio::test] + async fn the_refresh_loop_runs_a_pass_on_every_tick() { + let (_directory, sessions, _cookie) = due_session(1); + let heimdall = ScriptedHeimdall::answering((0..200).map(|_| Reply::Timeout).collect()); + let ran = tokio::time::timeout( + Duration::from_millis(400), + run_refresh_loop(&sessions, &heimdall, Duration::from_millis(10)), + ) + .await; + assert!(ran.is_err(), "the loop never returns"); + assert!(heimdall.calls().len() >= 2, "{:?}", heimdall.calls()); + } } From 57b16df2862cc4c3c4c8ec0e33a6506996718fcf Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 9 Oct 2026 17:32:28 +0200 Subject: [PATCH 6/7] Refresh tests: pin the refresh owner's endurance and the signing-algorithm check Co-Authored-By: Claude Opus 5.5 --- crates/ghostlight-dungeon/src/heimdall.rs | 16 ++++++++++++++++ crates/ghostlight-dungeon/src/runtime.rs | 13 +++++++++++++ 2 files changed, 29 insertions(+) diff --git a/crates/ghostlight-dungeon/src/heimdall.rs b/crates/ghostlight-dungeon/src/heimdall.rs index 7f32c9b..5177cc9 100644 --- a/crates/ghostlight-dungeon/src/heimdall.rs +++ b/crates/ghostlight-dungeon/src/heimdall.rs @@ -1187,6 +1187,22 @@ mod tests { assert!(cache.key("k1", start + JWKS_TTL).is_none(), "stale at the ttl"); } + #[tokio::test] + async fn a_token_signed_with_another_algorithm_is_refused_before_any_key_fetch() { + let token = jsonwebtoken::encode( + &jsonwebtoken::Header::new(Algorithm::HS256), + &serde_json::json!({"sub": "x"}), + &jsonwebtoken::EncodingKey::from_secret(b"secret"), + ) + .unwrap(); + let error = HeimdallClient::fixture() + .verify_access(&token) + .await + .unwrap_err(); + assert!(error.to_string().contains("unsupported signing algorithm"), "{error:#}"); + assert!(error.downcast_ref::().is_none()); + } + #[test] fn a_denied_status_is_the_typed_denial_and_any_other_status_passes() { let diagnostics = vec!["Idempotency key was reused".to_owned()]; diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index 9d1e6c7..e1574f4 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -2548,6 +2548,19 @@ mod tests { } } + /// The daemon's refresh owner serves until it fails: a body that returns + /// at once would be read by `serve` as the owner stopping. + #[tokio::test] + async fn the_session_refresh_owner_keeps_serving() { + let fixture = fixture().await; + let ran = tokio::time::timeout( + Duration::from_millis(300), + maintain_session_refresh(fixture.state.clone()), + ) + .await; + assert!(ran.is_err(), "the refresh owner returned: {ran:?}"); + } + /// PA.f172: `state.play` being `None` — a play table that failed to /// open, for any reason, `PlayTurnStore::open` returning `Err` among /// them — must be visible on `/health`, the same operator-facing surface From 26f533e8f46d4bebe8e53fbc6b3a16958e7ccdde Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 9 Oct 2026 20:13:25 +0200 Subject: [PATCH 7/7] Refresh tests pin the production edges: key-fetch typing, cache wiring, algorithm gate, cadence VerificationUnavailable now carries an error class and never the fetch error, whose text named the key-set URL. fetch_jwks returns the reqwest error so the class is read from it, not from a string. run_refresh_loop loses its period parameter: SESSION_REFRESH_PERIOD is decided in one place and a paused-clock test observes it exactly and over twelve ticks. Tests drive HeimdallClient::verify_access against a loopback issuer that counts fetches (cache stored, read, ttl 299 s fresh and 301 s stale), a closed port and a 503 (kept session and receipt, no URL in the error or the log line), and nine wrong-algorithm tokens. The moved-session test also pins that the newer claim is the one spent next. Builds and passes under ygg-verify (28 of 28 in heimdall:: and refresh_loop_tests). Co-Authored-By: Claude Opus 5.5 --- crates/ghostlight-dungeon/Cargo.toml | 1 + crates/ghostlight-dungeon/src/heimdall.rs | 243 +++++++++++++++++++--- crates/ghostlight-dungeon/src/runtime.rs | 129 +++++++++--- 3 files changed, 325 insertions(+), 48 deletions(-) diff --git a/crates/ghostlight-dungeon/Cargo.toml b/crates/ghostlight-dungeon/Cargo.toml index ff99b00..0692839 100644 --- a/crates/ghostlight-dungeon/Cargo.toml +++ b/crates/ghostlight-dungeon/Cargo.toml @@ -43,4 +43,5 @@ zeroize.workspace = true [dev-dependencies] tempfile = "3" +tokio = { workspace = true, features = ["test-util"] } tower = { version = "0.5", features = ["util"] } diff --git a/crates/ghostlight-dungeon/src/heimdall.rs b/crates/ghostlight-dungeon/src/heimdall.rs index 5177cc9..9b9e27b 100644 --- a/crates/ghostlight-dungeon/src/heimdall.rs +++ b/crates/ghostlight-dungeon/src/heimdall.rs @@ -45,10 +45,35 @@ pub(crate) struct HeimdallDenied { /// Heimdall's signing keys could not be fetched, so a receipt could not be /// judged either way. Distinct from a receipt that positively fails /// verification: the refresh loop keeps the receipt for this and revokes for -/// that. +/// that. It carries an error class and never the fetch error itself, whose +/// text names the key-set URL: an error never echoes an input value. #[derive(Debug, thiserror::Error)] -#[error("Heimdall signing keys unavailable: {0}")] -pub(crate) struct VerificationUnavailable(pub(crate) String); +#[error("Heimdall signing keys unavailable: the key-set fetch {class}")] +pub(crate) struct VerificationUnavailable { + class: &'static str, +} + +impl VerificationUnavailable { + fn of_fetch(error: &reqwest::Error) -> Self { + let class = if error.is_timeout() { + "timed out" + } else if error.is_connect() { + "could not connect" + } else if error.is_status() { + "returned an error status" + } else if error.is_decode() { + "returned an unreadable key set" + } else { + "failed" + }; + Self { class } + } + + #[cfg(test)] + pub(crate) fn new(class: &'static str) -> Self { + Self { class } + } +} /// How long a fetched signing-key set is trusted before it is fetched again. const JWKS_TTL: Duration = Duration::from_secs(300); @@ -491,6 +516,13 @@ impl HeimdallClient { } } + /// The same client against another issuer, for tests that stand up their own. + #[cfg(test)] + pub(crate) fn with_issuer(mut self, issuer: impl Into) -> Self { + self.issuer = issuer.into(); + self + } + pub async fn begin(&self, idempotency_key: &str) -> anyhow::Result { let payload = BeginCommand { provider: "discord", @@ -606,15 +638,14 @@ impl HeimdallClient { )?)) } - async fn fetch_jwks(&self) -> anyhow::Result { - Ok(self - .http + async fn fetch_jwks(&self) -> Result { + self.http .get(format!("{}/.well-known/jwks.json", self.issuer)) .send() .await? .error_for_status()? .json() - .await?) + .await } async fn verify_access(&self, token: &str) -> anyhow::Result { @@ -630,7 +661,7 @@ impl HeimdallClient { let set = self .fetch_jwks() .await - .map_err(|error| VerificationUnavailable(format!("{error:#}")))?; + .map_err(|error| VerificationUnavailable::of_fetch(&error))?; let jwk = set.find(&kid).cloned(); self.jwks .lock() @@ -1143,10 +1174,190 @@ fn required_env(name: &str) -> anyhow::Result { Ok(value.to_owned()) } +/// A local stand-in for Heimdall's issuer: it serves the key set (or a 5xx) +/// on a loopback port and counts the requests it receives. The key is the +/// RFC 8037 appendix A.1 Ed25519 test key. +#[cfg(test)] +pub(crate) mod test_issuer { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpListener, + }; + + pub(crate) const KID: &str = "k1"; + const PRIVATE_D: &str = "nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A"; + const PUBLIC_X: &str = "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"; + + #[derive(Clone, Copy)] + pub(crate) enum Answer { + KeySet, + ServerError, + } + + pub(crate) struct Issuer { + pub(crate) url: String, + fetches: Arc, + } + + impl Issuer { + pub(crate) async fn start(answer: Answer) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let fetches = Arc::new(AtomicUsize::new(0)); + let counted = fetches.clone(); + let key_set = serde_json::json!({ + "keys": [{"kty": "OKP", "crv": "Ed25519", "kid": KID, "x": PUBLIC_X}] + }) + .to_string(); + tokio::spawn(async move { + while let Ok((mut stream, _)) = listener.accept().await { + let mut request = Vec::new(); + let mut chunk = [0_u8; 1024]; + while !request.windows(4).any(|window| window == b"\r\n\r\n") { + match stream.read(&mut chunk).await { + Ok(0) | Err(_) => break, + Ok(read) => request.extend_from_slice(&chunk[..read]), + } + } + counted.fetch_add(1, Ordering::SeqCst); + let (status, body) = match answer { + Answer::KeySet => ("200 OK", key_set.as_str()), + Answer::ServerError => ("503 Service Unavailable", ""), + }; + let response = format!( + "HTTP/1.1 {status}\r\ncontent-type: application/json\r\n\ + content-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ); + let _ = stream.write_all(response.as_bytes()).await; + let _ = stream.shutdown().await; + } + }); + Self { url, fetches } + } + + pub(crate) fn fetches(&self) -> usize { + self.fetches.load(Ordering::SeqCst) + } + + /// The URL of a loopback port nothing listens on. + pub(crate) fn closed_url() -> String { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + format!("http://{}", listener.local_addr().unwrap()) + } + } + + /// An access token Heimdall's key signs for `issuer`, with the claims + /// `verify_access` demands. + pub(crate) fn signed_token(issuer: &str) -> String { + let mut der = vec![ + 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, + 0x04, 0x20, + ]; + der.extend(URL_SAFE_NO_PAD.decode(PRIVATE_D).unwrap()); + let pem = format!( + "-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----\n", + STANDARD.encode(der) + ); + let mut header = jsonwebtoken::Header::new(Algorithm::EdDSA); + header.kid = Some(KID.into()); + let claims = serde_json::json!({ + "iss": issuer, "aud": APP_SLUG, "sub": "account-1", "sid": "session-1", + "exp": Utc::now().timestamp() + 300, "typ": "heimdall_access", + "account_id": "account-1", "access_revision": 1, + "capabilities": ["app_access"], "app": {"slug": APP_SLUG}, + }); + jsonwebtoken::encode( + &header, + &claims, + &jsonwebtoken::EncodingKey::from_ed_pem(pem.as_bytes()).unwrap(), + ) + .unwrap() + } +} + #[cfg(test)] mod tests { use super::*; + use super::test_issuer::{Answer, Issuer, signed_token}; + + #[tokio::test] + async fn a_key_fetch_failure_is_typed_unavailable_and_names_no_url() { + let closed = Issuer::closed_url(); + let failing = Issuer::start(Answer::ServerError).await; + for (base, class) in [ + (closed, "could not connect"), + (failing.url.clone(), "returned an error status"), + ] { + let canary = format!("{base}/canary-q7x1"); + let client = HeimdallClient::fixture().with_issuer(canary.clone()); + let error = client + .verify_access(&signed_token(&canary)) + .await + .unwrap_err(); + assert!(error.downcast_ref::().is_some(), "{error:#}"); + for text in [format!("{error}"), format!("{error:#}"), format!("{error:?}")] { + assert!(text.contains("signing keys unavailable"), "{text}"); + assert!(text.contains(class), "{text}"); + for leaked in [canary.as_str(), base.as_str(), "canary-q7x1", "127.0.0.1"] { + assert!(!text.contains(leaked), "{leaked} leaked into {text}"); + } + } + } + } + + #[tokio::test] + async fn the_key_set_is_fetched_once_within_its_ttl_and_again_after_it() { + let issuer = Issuer::start(Answer::KeySet).await; + let client = HeimdallClient::fixture().with_issuer(issuer.url.clone()); + let token = signed_token(&issuer.url); + client.verify_access(&token).await.unwrap(); + assert_eq!(issuer.fetches(), 1); + client.verify_access(&token).await.unwrap(); + assert_eq!(issuer.fetches(), 1, "a second verify within the ttl reads the cache"); + let age = |seconds: u64| { + client.jwks.lock().unwrap().fetched.as_mut().unwrap().0 = + Instant::now().checked_sub(Duration::from_secs(seconds)).unwrap(); + }; + age(299); + client.verify_access(&token).await.unwrap(); + assert_eq!(issuer.fetches(), 1, "299 s old is still fresh"); + age(301); + client.verify_access(&token).await.unwrap(); + assert_eq!(issuer.fetches(), 2, "301 s old is fetched again"); + client.verify_access(&token).await.unwrap(); + assert_eq!(issuer.fetches(), 2, "and the new fetch is cached"); + } + + #[tokio::test] + async fn a_token_signed_under_any_other_algorithm_is_refused_before_any_key_fetch() { + let issuer = Issuer::start(Answer::KeySet).await; + let client = HeimdallClient::fixture().with_issuer(issuer.url.clone()); + let part = |text: &str| URL_SAFE_NO_PAD.encode(text); + for alg in [ + "none", "HS256", "HS384", "HS512", "RS256", "RS384", "PS256", "ES256", "ES384", + ] { + let token = format!( + "{}.{}.{}", + part(&format!(r#"{{"alg":"{alg}","typ":"JWT","kid":"k1"}}"#)), + part(r#"{"sub":"account-1"}"#), + URL_SAFE_NO_PAD.encode([0xAB_u8; 32]), + ); + let error = client.verify_access(&token).await.unwrap_err(); + assert!(error.downcast_ref::().is_none(), "{alg}"); + if alg != "none" { + assert!( + error.to_string().contains("unsupported signing algorithm"), + "{alg}: {error:#}" + ); + } + assert_eq!(issuer.fetches(), 0, "{alg} reached the key fetch"); + } + } + fn boundary(endpoint: &str) -> HeimdallCommandBoundaryRecord { HeimdallCommandBoundaryRecord { schema: "heimdall.command_boundary.v1".into(), @@ -1187,22 +1398,6 @@ mod tests { assert!(cache.key("k1", start + JWKS_TTL).is_none(), "stale at the ttl"); } - #[tokio::test] - async fn a_token_signed_with_another_algorithm_is_refused_before_any_key_fetch() { - let token = jsonwebtoken::encode( - &jsonwebtoken::Header::new(Algorithm::HS256), - &serde_json::json!({"sub": "x"}), - &jsonwebtoken::EncodingKey::from_secret(b"secret"), - ) - .unwrap(); - let error = HeimdallClient::fixture() - .verify_access(&token) - .await - .unwrap_err(); - assert!(error.to_string().contains("unsupported signing algorithm"), "{error:#}"); - assert!(error.downcast_ref::().is_none()); - } - #[test] fn a_denied_status_is_the_typed_denial_and_any_other_status_passes() { let diagnostics = vec!["Idempotency key was reused".to_owned()]; diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index e1574f4..fbd1db6 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -1863,23 +1863,21 @@ fn session_cookie(raw: &str, expires_at: DateTime, now: DateTime) -> H } async fn maintain_session_refresh(state: AppState) -> anyhow::Result<()> { - run_refresh_loop( - &state.sessions, - state.heimdall.as_ref(), - Duration::from_secs(60), - ) - .await + run_refresh_loop(&state.sessions, state.heimdall.as_ref()).await } -/// Runs `refresh_due_sessions` once per `period` for as long as the daemon -/// serves. The receipts it holds are Heimdall refreshes already spent -/// upstream whose verification could not yet be judged. +/// How often the refresh loop scans for sessions due for refresh. Decided +/// here and nowhere else. +const SESSION_REFRESH_PERIOD: Duration = Duration::from_secs(60); + +/// Runs `refresh_due_sessions` once per `SESSION_REFRESH_PERIOD` for as long +/// as the daemon serves. The receipts it holds are Heimdall refreshes already +/// spent upstream whose verification could not yet be judged. async fn run_refresh_loop( sessions: &Mutex, heimdall: &impl SessionRefresher, - period: Duration, ) -> anyhow::Result<()> { - let mut interval = tokio::time::interval(period); + let mut interval = tokio::time::interval(SESSION_REFRESH_PERIOD); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); let mut unverified = HashMap::new(); loop { @@ -6481,6 +6479,9 @@ mod refresh_loop_tests { moving: Option>>, pending: StdMutex>, calls: StdMutex>, + /// Verify receipts with this real client, against the access token + /// each receipt carries, instead of from the verdict queue. + real: Option<(HeimdallClient, String)>, } impl ScriptedHeimdall { @@ -6496,6 +6497,11 @@ mod refresh_loop_tests { self } + fn verifying_for_real(mut self, client: HeimdallClient, token: String) -> Self { + self.real = Some((client, token)); + self + } + fn verifications(&self) -> usize { *self.verifications.lock().unwrap() } @@ -6566,7 +6572,7 @@ mod refresh_loop_tests { error: None, account: None, session: None, - access_token: None, + access_token: self.real.as_ref().map(|(_, token)| token.clone()), refresh_token: None, refresh: None, shared_capabilities: Vec::new(), @@ -6577,12 +6583,15 @@ mod refresh_loop_tests { async fn verify_refresh( &self, - _completion: AuthCompletionReceipt, + completion: AuthCompletionReceipt, ) -> anyhow::Result { *self.verifications.lock().unwrap() += 1; + if let Some((client, _)) = &self.real { + return client.verify_refresh(completion).await; + } match self.verdicts.lock().unwrap().pop_front() { Some(Verdict::Unavailable) => { - Err(VerificationUnavailable("jwks fetch timed out".into()).into()) + Err(VerificationUnavailable::new("timed out").into()) } Some(Verdict::Invalid) => bail!("Heimdall access token signature is invalid"), None => Ok(self.pending.lock().unwrap().take().expect("scripted receipt")), @@ -6814,6 +6823,12 @@ mod refresh_loop_tests { heimdall.moving = Some(sessions.clone()); pass(&sessions, &heimdall).await; assert!(is_live(&sessions, &cookie).await); + // The newer state wins: the next refresh spends its claim, not the + // stale receipt's. + heimdall.moving = None; + heimdall.replies.lock().unwrap().push_back(Reply::Timeout); + pass(&sessions, &heimdall).await; + assert_eq!(heimdall.calls()[1].0, "claim-moved"); } #[tokio::test] @@ -6832,16 +6847,82 @@ mod refresh_loop_tests { assert!(!is_live(&sessions, &cookie).await); } - #[tokio::test] - async fn the_refresh_loop_runs_a_pass_on_every_tick() { + /// Lets the loop under test run everything that is ready, without moving + /// the paused clock. + async fn settle() { + for _ in 0..16 { + tokio::task::yield_now().await; + } + } + + #[tokio::test(start_paused = true)] + async fn the_refresh_loop_runs_a_pass_every_sixty_seconds_and_keeps_going() { let (_directory, sessions, _cookie) = due_session(1); - let heimdall = ScriptedHeimdall::answering((0..200).map(|_| Reply::Timeout).collect()); - let ran = tokio::time::timeout( - Duration::from_millis(400), - run_refresh_loop(&sessions, &heimdall, Duration::from_millis(10)), - ) - .await; - assert!(ran.is_err(), "the loop never returns"); - assert!(heimdall.calls().len() >= 2, "{:?}", heimdall.calls()); + let heimdall = ScriptedHeimdall::answering((0..64).map(|_| Reply::Timeout).collect()); + let observed = async { + settle().await; + assert_eq!(heimdall.calls().len(), 1, "the first pass runs at once"); + tokio::time::advance(Duration::from_millis(59_999)).await; + settle().await; + assert_eq!(heimdall.calls().len(), 1, "no pass before sixty seconds"); + tokio::time::advance(Duration::from_millis(1)).await; + settle().await; + assert_eq!(heimdall.calls().len(), 2, "the second pass at sixty seconds"); + for passes in 3..=12 { + tokio::time::advance(Duration::from_secs(60)).await; + settle().await; + assert_eq!(heimdall.calls().len(), passes); + } + }; + tokio::select! { + ran = run_refresh_loop(&sessions, &heimdall) => panic!("the loop returned: {ran:?}"), + () = observed => {} + } + } + + /// A refresh receipt verified by the real client against `issuer_url`, + /// whose key-set fetch fails. Returns whether the session stayed live, + /// how many receipts were kept, and the log the pass wrote. + async fn pass_through_real_verification(issuer_url: &str) -> (bool, usize, String) { + let (_directory, sessions, cookie) = due_session(1); + let client = HeimdallClient::fixture().with_issuer(issuer_url); + let token = heimdall::test_issuer::signed_token(issuer_url); + let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt { + revision: 1, + claim: "claim-1", + }]) + .verifying_for_real(client, token); + let captured = Captured::default(); + let subscriber = tracing_subscriber::fmt() + .with_writer(captured.clone()) + .with_ansi(false) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + let mut unverified = HashMap::new(); + refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap(); + let logged = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap(); + (is_live(&sessions, &cookie).await, unverified.len(), logged) + } + + #[tokio::test] + async fn a_key_fetch_failure_in_the_real_verification_keeps_the_session_and_the_receipt() { + let failing = heimdall::test_issuer::Issuer::start(heimdall::test_issuer::Answer::ServerError) + .await; + for issuer_url in [heimdall::test_issuer::Issuer::closed_url(), failing.url.clone()] { + let (live, kept, logged) = pass_through_real_verification(&issuer_url).await; + assert!(live, "{issuer_url}: a key-fetch failure signed the session out"); + assert_eq!(kept, 1, "{issuer_url}: the spent receipt was not kept"); + assert!(logged.contains("could not be verified yet"), "{logged}"); + } + } + + #[tokio::test] + async fn the_unverified_warning_names_the_error_class_and_no_url() { + let canary = format!("{}/canary-q7x1", heimdall::test_issuer::Issuer::closed_url()); + let (_, _, logged) = pass_through_real_verification(&canary).await; + assert!(logged.contains("could not connect"), "{logged}"); + for leaked in [canary.as_str(), "canary-q7x1", "127.0.0.1", "jwks.json"] { + assert!(!logged.contains(leaked), "{leaked} leaked into the log: {logged}"); + } } }