Merge remote-tracking branch 'origin/main' into ghostlight-verse/play-faults
This commit is contained in:
commit
d79a96ede4
5 changed files with 1086 additions and 84 deletions
|
|
@ -44,4 +44,5 @@ zeroize.workspace = true
|
|||
[dev-dependencies]
|
||||
ghostlight = { path = "../ghostlight", features = ["test-support"] }
|
||||
tempfile = "3"
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
|
|
|
|||
|
|
@ -46,6 +46,21 @@ struct AppSession {
|
|||
revoked_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// 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::<RefreshRefusal>(),
|
||||
Some(&RefreshRefusal::MovedSinceCandidate)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_claim_is_encrypted_and_exactly_bound() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
|
|
|
|||
|
|
@ -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},
|
||||
};
|
||||
|
||||
|
|
@ -30,6 +34,107 @@ 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,
|
||||
}
|
||||
|
||||
/// 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. 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: 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);
|
||||
|
||||
/// 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<Jwk> {
|
||||
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]
|
||||
pub(crate) trait SessionRefresher {
|
||||
async fn refresh(
|
||||
&self,
|
||||
refresh_token: &str,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthCompletionReceipt>;
|
||||
|
||||
async fn verify_refresh(
|
||||
&self,
|
||||
completion: AuthCompletionReceipt,
|
||||
) -> anyhow::Result<VerifiedSessionRefresh>;
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl SessionRefresher for HeimdallClient {
|
||||
async fn refresh(
|
||||
&self,
|
||||
refresh_token: &str,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthCompletionReceipt> {
|
||||
HeimdallClient::refresh(self, refresh_token, idempotency_key).await
|
||||
}
|
||||
|
||||
async fn verify_refresh(
|
||||
&self,
|
||||
completion: AuthCompletionReceipt,
|
||||
) -> anyhow::Result<VerifiedSessionRefresh> {
|
||||
HeimdallClient::verify_refresh(self, completion).await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HeimdallClient {
|
||||
http: Client,
|
||||
|
|
@ -40,6 +145,7 @@ pub struct HeimdallClient {
|
|||
boundary_locator: HeimdallBoundaryLocator,
|
||||
runtime_id: String,
|
||||
shared_secret: String,
|
||||
jwks: Arc<StdMutex<JwksCache>>,
|
||||
}
|
||||
|
||||
/// Idunn's projection of a managed Heimdall dependency, when Heimdall is a
|
||||
|
|
@ -184,7 +290,7 @@ pub struct AuthNavigation {
|
|||
pub allowed_origins: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AuthCompletionReceipt {
|
||||
pub status: String,
|
||||
|
|
@ -199,12 +305,12 @@ pub struct AuthCompletionReceipt {
|
|||
pub shared_capabilities: Vec<String>,
|
||||
}
|
||||
|
||||
#[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,
|
||||
|
|
@ -214,7 +320,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,
|
||||
|
|
@ -325,6 +431,28 @@ impl VerifiedSessionAdmission {
|
|||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl VerifiedSessionRefresh {
|
||||
pub(crate) fn fixture(
|
||||
account_id: impl Into<String>,
|
||||
heimdall_session_id: impl Into<String>,
|
||||
access_revision: u64,
|
||||
access_expires_at: DateTime<Utc>,
|
||||
refresh_expires_at: DateTime<Utc>,
|
||||
refresh_claim: impl Into<String>,
|
||||
) -> 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,
|
||||
|
|
@ -360,6 +488,7 @@ impl HeimdallClient {
|
|||
},
|
||||
runtime_id: runtime_id.into(),
|
||||
shared_secret,
|
||||
jwks: Arc::default(),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -383,9 +512,17 @@ impl HeimdallClient {
|
|||
}),
|
||||
runtime_id: "ghostlight-test-runtime".into(),
|
||||
shared_secret: "fixture-secret".into(),
|
||||
jwks: Arc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<String>) -> Self {
|
||||
self.issuer = issuer.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn begin(&self, idempotency_key: &str) -> anyhow::Result<AuthBeginReceipt> {
|
||||
let payload = BeginCommand {
|
||||
provider: "discord",
|
||||
|
|
@ -501,28 +638,43 @@ impl HeimdallClient {
|
|||
)?))
|
||||
}
|
||||
|
||||
async fn fetch_jwks(&self) -> Result<JwkSet, reqwest::Error> {
|
||||
self.http
|
||||
.get(format!("{}/.well-known/jwks.json", self.issuer))
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.json()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn verify_access(&self, token: &str) -> anyhow::Result<AccessClaims> {
|
||||
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
|
||||
.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")?;
|
||||
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::of_fetch(&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::<AccessClaims>(token, &DecodingKey::from_jwk(jwk)?, &validation)?.claims;
|
||||
decode::<AccessClaims>(token, &DecodingKey::from_jwk(&jwk)?, &validation)?.claims;
|
||||
if claims.typ != "heimdall_access"
|
||||
|| claims.aud != APP_SLUG
|
||||
|| claims.iss != self.issuer
|
||||
|
|
@ -580,12 +732,7 @@ impl HeimdallClient {
|
|||
else {
|
||||
bail!("Heimdall returned a non-operation response");
|
||||
};
|
||||
if status == "denied" {
|
||||
bail!(
|
||||
"Heimdall denied the private command: {}",
|
||||
diagnostics.join("; ")
|
||||
);
|
||||
}
|
||||
refuse_denied(&status, &diagnostics)?;
|
||||
if payload_schema != PRIVATE_ENVELOPE_SCHEMA || payload_encoding != "messagepack-base64" {
|
||||
bail!("Heimdall returned the wrong private response contract");
|
||||
}
|
||||
|
|
@ -595,6 +742,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,
|
||||
|
|
@ -1015,10 +1174,190 @@ fn required_env(name: &str) -> anyhow::Result<String> {
|
|||
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<AtomicUsize>,
|
||||
}
|
||||
|
||||
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::<VerificationUnavailable>().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::<VerificationUnavailable>().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(),
|
||||
|
|
@ -1040,6 +1379,34 @@ 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()];
|
||||
let denial = refuse_denied("denied", &diagnostics).unwrap_err();
|
||||
assert!(denial.downcast_ref::<HeimdallDenied>().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";
|
||||
|
|
|
|||
|
|
@ -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, 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,70 +1863,129 @@ fn session_cookie(raw: &str, expires_at: DateTime<Utc>, now: DateTime<Utc>) -> 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()).await
|
||||
}
|
||||
|
||||
/// 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<AppSessionOwner>,
|
||||
heimdall: &impl SessionRefresher,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut interval = tokio::time::interval(SESSION_REFRESH_PERIOD);
|
||||
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
let mut unverified = HashMap::new();
|
||||
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");
|
||||
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<AppSessionOwner>,
|
||||
heimdall: &impl SessionRefresher,
|
||||
unverified: &mut HashMap<String, heimdall::AuthCompletionReceipt>,
|
||||
) -> 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 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::<HeimdallDenied>().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;
|
||||
}
|
||||
};
|
||||
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;
|
||||
}
|
||||
};
|
||||
let verified = match heimdall.verify_refresh(completion.clone()).await {
|
||||
Ok(value) => value,
|
||||
Err(error) if error.downcast_ref::<VerificationUnavailable>().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;
|
||||
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("invalid 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 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::<RefreshRefusal>()
|
||||
== Some(&RefreshRefusal::RevisionWentBackwards)
|
||||
&& let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash)
|
||||
{
|
||||
if sessions.is_healthy() {
|
||||
tracing::warn!(%error, "local app session rejected Heimdall refresh");
|
||||
} else {
|
||||
return Err(error).context("app-session refresh commit lost custody");
|
||||
}
|
||||
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
|
||||
|
|
@ -2487,6 +2546,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
|
||||
|
|
@ -6370,3 +6442,487 @@ 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, VerificationUnavailable, VerifiedSessionRefresh};
|
||||
use std::{collections::VecDeque, sync::Mutex as StdMutex};
|
||||
|
||||
enum Reply {
|
||||
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,
|
||||
}
|
||||
|
||||
/// 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<VecDeque<Reply>>,
|
||||
verdicts: StdMutex<VecDeque<Verdict>>,
|
||||
verifications: StdMutex<usize>,
|
||||
/// While answering a refresh, apply a newer revision to this store,
|
||||
/// as a concurrent refresh of the same session would.
|
||||
moving: Option<std::sync::Arc<Mutex<AppSessionOwner>>>,
|
||||
pending: StdMutex<Option<VerifiedSessionRefresh>>,
|
||||
calls: StdMutex<Vec<(String, String)>>,
|
||||
/// 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 {
|
||||
fn answering(replies: Vec<Reply>) -> Self {
|
||||
Self {
|
||||
replies: StdMutex::new(replies.into()),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn verifying(mut self, verdicts: Vec<Verdict>) -> Self {
|
||||
self.verdicts = StdMutex::new(verdicts.into());
|
||||
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()
|
||||
}
|
||||
|
||||
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<AuthCompletionReceipt> {
|
||||
self.calls
|
||||
.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(),
|
||||
}
|
||||
.into()),
|
||||
Reply::Timeout => bail!("Heimdall private command timed out"),
|
||||
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(
|
||||
account,
|
||||
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: self.real.as_ref().map(|(_, token)| token.clone()),
|
||||
refresh_token: None,
|
||||
refresh: None,
|
||||
shared_capabilities: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn verify_refresh(
|
||||
&self,
|
||||
completion: AuthCompletionReceipt,
|
||||
) -> anyhow::Result<VerifiedSessionRefresh> {
|
||||
*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::new("timed out").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, std::sync::Arc<Mutex<AppSessionOwner>>, 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, 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<AppSessionOwner>, heimdall: &ScriptedHeimdall) {
|
||||
refresh_due_sessions(sessions, heimdall, &mut HashMap::new())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn is_live(sessions: &Mutex<AppSessionOwner>, cookie: &str) -> bool {
|
||||
sessions
|
||||
.lock()
|
||||
.await
|
||||
.account_for_cookie(cookie, Utc::now())
|
||||
.unwrap()
|
||||
.is_some()
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Captured(std::sync::Arc<StdMutex<Vec<u8>>>);
|
||||
|
||||
impl std::io::Write for Captured {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
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,
|
||||
]);
|
||||
pass(&sessions, &heimdall).await;
|
||||
assert!(is_live(&sessions, &cookie).await);
|
||||
// The wrapped claim is the receipt's: the next refresh spends it.
|
||||
pass(&sessions, &heimdall).await;
|
||||
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]);
|
||||
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]);
|
||||
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,
|
||||
]);
|
||||
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)));
|
||||
}
|
||||
|
||||
#[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,
|
||||
]);
|
||||
pass(&sessions, &heimdall).await;
|
||||
assert!(!is_live(&sessions, &cookie).await);
|
||||
pass(&sessions, &heimdall).await;
|
||||
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]);
|
||||
pass(&sessions, &heimdall).await;
|
||||
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);
|
||||
let heimdall = ScriptedHeimdall::answering(vec![Reply::Deny, Reply::Timeout]);
|
||||
pass(&sessions, &heimdall).await;
|
||||
assert!(!is_live(&sessions, &cookie).await);
|
||||
pass(&sessions, &heimdall).await;
|
||||
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);
|
||||
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);
|
||||
// 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]
|
||||
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);
|
||||
}
|
||||
|
||||
/// 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..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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue