From 78b24df60c11af3cc5304e53764f30c773673d5b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 09:56:19 +0000 Subject: [PATCH 1/5] fix(verify): judge an evidence pack's signer as of when it was generated verify_pack checked the signing control plane's certificate against the current time. That certificate lives about a day, so every genuine pack stopped verifying offline a day after export, which is when an auditor checks it. Judge it as of the manifest's signed generated_at instead, as the audit bucket verifier already does for manifests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SEiXYXpNCrqYnNbKiHVaey --- Cargo.lock | 3 + crates/limen-verify/Cargo.toml | 3 + crates/limen-verify/src/pack.rs | 110 ++++++++++++++++++++++++++++++-- 3 files changed, 110 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3df561be..bba48896 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3041,8 +3041,11 @@ dependencies = [ "base64 0.23.1", "flate2", "limen-audit", + "limen-ca", + "limen-core", "limen-proto", "limen-session", + "rcgen", "rustls-pki-types", "serde", "serde_json", diff --git a/crates/limen-verify/Cargo.toml b/crates/limen-verify/Cargo.toml index b8849b48..274027eb 100644 --- a/crates/limen-verify/Cargo.toml +++ b/crates/limen-verify/Cargo.toml @@ -24,6 +24,9 @@ uuid.workspace = true [dev-dependencies] limen-audit.workspace = true +limen-ca.workspace = true +limen-core.workspace = true +rcgen.workspace = true tokio = { workspace = true, features = ["rt-multi-thread", "macros"] } [lints] diff --git a/crates/limen-verify/src/pack.rs b/crates/limen-verify/src/pack.rs index a4e85f8b..708aaeea 100644 --- a/crates/limen-verify/src/pack.rs +++ b/crates/limen-verify/src/pack.rs @@ -7,7 +7,7 @@ use std::fmt::Write as _; use base64::Engine as _; use limen_proto::v1::Signed; -use limen_session::envelope::{Purpose, verify}; +use limen_session::envelope::{Purpose, verify_at}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; @@ -100,15 +100,23 @@ pub fn verify_pack( signature: sig, signer_cert_der: cert, }; - if let Err(e) = verify(&signed, Purpose::EvidencePack, internal_ca) { - out.problems - .push(format!("the manifest's signature is not valid: {e}")); - return out; - } let Ok(manifest) = serde_json::from_str::(manifest_json) else { out.problems.push("the manifest is unreadable".into()); return out; }; + // The signer's certificate lives about a day and a pack is checked long + // after, so the certificate is judged as of the time the signed manifest + // records, as for audit manifests (bucket.rs). + let Ok(generated_at) = time::OffsetDateTime::from_unix_timestamp(manifest.generated_at) else { + out.problems + .push("the manifest's generation time is out of range".into()); + return out; + }; + if let Err(e) = verify_at(&signed, Purpose::EvidencePack, internal_ca, generated_at) { + out.problems + .push(format!("the manifest's signature is not valid: {e}")); + return out; + } let empty = serde_json::Map::new(); let sections = v["sections"].as_object().unwrap_or(&empty); for (name, entry) in &manifest.files { @@ -146,4 +154,94 @@ mod tests { assert!(!verify_pack(junk, &ca).ok()); } } + + /// A pack signed with a certificate that expires in a second, generated + /// at `generated_at` seconds from now. + async fn pack_signed_by_a_short_lived_cert(generated_at: i64) -> (Vec, Vec) { + use limen_ca::{CaPurpose, CertificateAuthority, ComponentCertRequest, FileSigner}; + use limen_core::identity::ComponentKind; + use limen_session::envelope::EnvelopeSigner; + use rcgen::{CertificateParams, KeyPair, PKCS_ECDSA_P256_SHA256}; + + let ca = CertificateAuthority::create_self_signed( + CaPurpose::Internal, + std::sync::Arc::new(FileSigner::generate().expect("key")), + ) + .await + .expect("ca"); + let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).expect("key"); + let csr = CertificateParams::default() + .serialize_request(&key) + .expect("csr"); + let cert = ca + .issue_component(ComponentCertRequest { + csr_der: csr.der().to_vec(), + kind: ComponentKind::ControlPlane, + id: "cp".into(), + dns_names: vec![], + labels: BTreeMap::new(), + ttl: std::time::Duration::from_secs(1), + }) + .await + .expect("issue"); + let signer = EnvelopeSigner::new(&key.serialize_pem(), cert.der.to_vec()).expect("signer"); + let section = json!({"rows": [1, 2, 3]}); + let bytes = serde_json::to_vec(§ion).expect("section"); + let manifest = Manifest { + format: FORMAT.to_owned(), + generated_at: time::OffsetDateTime::now_utc().unix_timestamp() + generated_at, + from: 0, + to: 1, + requested_by: "auditor@example.com".into(), + control_plane: "cp".into(), + files: BTreeMap::from([( + "sessions".to_owned(), + FileEntry { + sha256: sha(&bytes), + bytes: bytes.len(), + }, + )]), + }; + let manifest_json = serde_json::to_string(&manifest).expect("manifest"); + let envelope = signer + .sign(Purpose::EvidencePack, manifest_json.clone().into_bytes()) + .expect("sign"); + let b64 = base64::engine::general_purpose::STANDARD; + let pack = json!({ + "format": FORMAT, + "manifest_sha256": sha(manifest_json.as_bytes()), + "manifest_json": manifest_json, + "signature_b64": b64.encode(&envelope.signature), + "signer_cert_b64": b64.encode(&envelope.signer_cert_der), + "sections": {"sessions": section}, + }); + ( + serde_json::to_vec(&pack).expect("pack"), + ca.cert_der().to_vec(), + ) + } + + #[tokio::test] + async fn a_pack_still_verifies_after_its_signers_certificate_expires() { + let (pack, ca) = pack_signed_by_a_short_lived_cert(0).await; + tokio::time::sleep(std::time::Duration::from_millis(2100)).await; + let ca = rustls_pki_types::CertificateDer::from(ca); + let checked = verify_pack(&pack, &ca); + assert!(checked.ok(), "{:?}", checked.problems); + } + + #[tokio::test] + async fn a_pack_dated_after_its_signers_certificate_expired_is_refused() { + // The certificate lives a second; a manifest claiming an hour from now + // was not signed while it was valid. + let (pack, ca) = pack_signed_by_a_short_lived_cert(3600).await; + let ca = rustls_pki_types::CertificateDer::from(ca); + let checked = verify_pack(&pack, &ca); + assert!(!checked.ok()); + assert!( + checked.problems[0].contains("signature is not valid"), + "{:?}", + checked.problems + ); + } } From cbb520849aaa1fecf6acf33a245a2dc91b5466fd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 09:56:19 +0000 Subject: [PATCH 2/5] fix(audit): fail a spool read when a fsynced segment comes up short read_from ignored scan's short result, so a closed segment damaged after open returned a batch with a gap; the consumer committed past it and the missing records were never shipped. Return a corruption error instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SEiXYXpNCrqYnNbKiHVaey --- crates/limen-audit/src/spool.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/crates/limen-audit/src/spool.rs b/crates/limen-audit/src/spool.rs index 2f7e83b0..20a69448 100644 --- a/crates/limen-audit/src/spool.rs +++ b/crates/limen-audit/src/spool.rs @@ -547,6 +547,15 @@ impl Spool { let mut file = File::open(&seg.path)?; let want = Self::end(seg).min(synced) - seg.first; let (records, _, _) = scan(&mut file, &seg.path, Some(want))?; + // Everything below `synced` was fsynced, so a segment that now + // holds fewer records was damaged after the fact. Returning what + // is left would leave a gap that a consumer commits past. + if records.len() as u64 != want { + return Err(corrupt( + &seg.path, + "segment holds fewer records than were written to it", + )); + } for (i, payload) in records.into_iter().enumerate() { let index = seg.first + i as u64; if index >= start && index < synced && out.len() < max { @@ -833,6 +842,30 @@ mod tests { assert!(next >= 1); } + #[tokio::test] + async fn a_closed_segment_damaged_after_open_fails_the_read_instead_of_skipping() { + let dir = tempfile::tempdir().expect("dir"); + let spool = Spool::open(config(dir.path())).expect("open"); + spool.start(); + for _ in 0..30 { + spool.append(&[7; 20]).await.expect("append"); + } + let mut segs: Vec<_> = std::fs::read_dir(dir.path().join("segments")) + .expect("ls") + .filter_map(Result::ok) + .map(|e| e.path()) + .collect(); + segs.sort(); + assert!(segs.len() > 2, "small segments roll"); + // Cut the last record off the first (closed, fsynced) segment. + let bytes = std::fs::read(&segs[0]).expect("read"); + std::fs::write(&segs[0], &bytes[..bytes.len() - 5]).expect("write"); + assert!( + matches!(spool.read("a", 100), Err(SpoolError::Corrupt { .. })), + "a read must not return a batch with a gap a consumer would commit past" + ); + } + #[tokio::test] async fn a_bad_checksum_before_the_tail_is_corruption_not_a_torn_write() { let dir = tempfile::tempdir().expect("dir"); From 39e94f50786889223a9bdff6260ec59dc2f81980 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 09:56:19 +0000 Subject: [PATCH 3/5] fix(proxy): refuse a session whose expiry overflows instead of panicking max_session_ttl has no upper bound in policy validation, and now + ttl panics past year 9999, so one oversized role broke every session open for its holders. Compute the expiry with checked_add and deny on overflow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SEiXYXpNCrqYnNbKiHVaey --- crates/limen-proxy/src/sessions.rs | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/limen-proxy/src/sessions.rs b/crates/limen-proxy/src/sessions.rs index e27ec04e..9cbeb29a 100644 --- a/crates/limen-proxy/src/sessions.rs +++ b/crates/limen-proxy/src/sessions.rs @@ -270,6 +270,13 @@ pub(crate) struct Denial { pub(crate) code: Option<&'static str>, } +/// When a session opened at `now` and lasting `ttl` ends, in Unix seconds, or +/// `None` if that is past what a timestamp can hold. +fn session_expiry(now: OffsetDateTime, ttl: Duration) -> Option { + let ttl = time::Duration::try_from(ttl).ok()?; + now.checked_add(ttl).map(OffsetDateTime::unix_timestamp) +} + pub(crate) fn denied(reason: impl Into) -> Denial { Denial { reason: reason.into(), @@ -621,6 +628,11 @@ pub(crate) async fn open_session( } ttl = ttl.min(Duration::from_secs(left)); } + // A role's `max_session_ttl` is not capped, and adding one that reaches + // past year 9999 to `now` would panic on every session open. + let expires_at = session_expiry(now, ttl).ok_or_else(|| { + denied("the role's max_session_ttl is too long to compute an expiry".to_owned()) + })?; let creds = proxy.credentials(); // Load figures are a little stale, so the chosen worker (or the peer // proxy holding it) may turn out to be full, or to have started @@ -650,7 +662,7 @@ pub(crate) async fn open_session( principal: target.principal.to_owned(), issued_at_unix: now.unix_timestamp(), establish_by_unix: (now + ESTABLISH_WITHIN).unix_timestamp(), - session_expires_at_unix: (now + ttl).unix_timestamp(), + session_expires_at_unix: expires_at, nonce: rand::random::<[u8; 32]>().to_vec(), user_cert_der: user_cert_der.to_vec(), proxy_id: creds.id.clone(), @@ -1049,7 +1061,20 @@ async fn relay( #[cfg(test)] mod tests { - use super::connection_group; + use super::{connection_group, session_expiry}; + + #[test] + fn a_session_ttl_past_year_9999_is_refused_not_a_panic() { + let now = time::OffsetDateTime::from_unix_timestamp(1_800_000_000).expect("time"); + assert_eq!( + session_expiry(now, std::time::Duration::from_secs(3600)), + Some(1_800_003_600) + ); + // `max_session_ttl: 3000000d` passes policy validation. + let huge = limen_policy::duration::DurationStr::parse("3000000d").expect("parses"); + assert_eq!(session_expiry(now, huge.0), None); + assert_eq!(session_expiry(now, std::time::Duration::MAX), None); + } #[test] fn group_ids_are_labels_only() { From 16c75c586d85dc022144d45896232e97dc3f9459 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 09:56:19 +0000 Subject: [PATCH 4/5] fix(worker): wrap the ElastiCache STS session token in Secret redis::target::Credentials derives Debug and held the session token as a plain String, unlike db/sigv4.rs. Nothing logs it today; this keeps it that way. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SEiXYXpNCrqYnNbKiHVaey --- crates/limen-worker/src/redis/target.rs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/limen-worker/src/redis/target.rs b/crates/limen-worker/src/redis/target.rs index 3cf6e123..9bfc11b4 100644 --- a/crates/limen-worker/src/redis/target.rs +++ b/crates/limen-worker/src/redis/target.rs @@ -258,7 +258,7 @@ pub async fn iam_token(target: &RedisTarget, user: &str) -> anyhow::Result anyhow::Result, - pub session_token: Option, + /// An STS session token is as live a credential as the secret key. + pub session_token: Option>, } /// The `SigV4` query-signed `connect` request `ElastiCache` takes as a password, @@ -313,7 +314,7 @@ pub fn presign_connect( ("X-Amz-SignedHeaders".into(), "host".into()), ]; if let Some(token) = &creds.session_token { - params.push(("X-Amz-Security-Token".into(), token.clone())); + params.push(("X-Amz-Security-Token".into(), token.expose().clone())); } let mut encoded: Vec<(String, String)> = params .iter() @@ -384,7 +385,7 @@ mod tests { let creds = Credentials { access_key: "AKIDEXAMPLE".into(), secret_key: Secret::new("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY".into()), - session_token: Some("TOKEN/abc+=".into()), + session_token: Some(Secret::new("TOKEN/abc+=".into())), }; let now = time::macros::datetime!(2026-10-17 12:00:00 UTC); let token = presign_connect(&creds, "us-east-1", "my-group", "read", now); @@ -394,6 +395,18 @@ mod tests { ); } + #[test] + fn debug_output_hides_the_secret_key_and_session_token() { + let creds = Credentials { + access_key: "AKIDEXAMPLE".into(), + secret_key: Secret::new("the-secret-key".into()), + session_token: Some(Secret::new("the-session-token".into())), + }; + let debug = format!("{creds:?}"); + assert!(!debug.contains("the-secret-key"), "{debug}"); + assert!(!debug.contains("the-session-token"), "{debug}"); + } + #[test] fn derives_the_documented_signing_key() { // From "Examples of how to derive a signing key" in the AWS docs. From 9419f046e00f4cad91a422d5c2672c7dbfffa46d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 09:56:19 +0000 Subject: [PATCH 5/5] fix(demos): make the skipped-test guards able to fire demo-idp-offboarding ran cargo test without --nocapture, so libtest swallowed the SKIPPED line a passing-but-skipped test prints and the guard could never trigger. Both demos now grep a here-string rather than a pipe, which pipefail plus grep -q could turn into a miss. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SEiXYXpNCrqYnNbKiHVaey --- demos/demo-idp-offboarding.sh | 8 +++++--- demos/demo-shadow.sh | 4 +++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/demos/demo-idp-offboarding.sh b/demos/demo-idp-offboarding.sh index 7464e281..3ce905f0 100755 --- a/demos/demo-idp-offboarding.sh +++ b/demos/demo-idp-offboarding.sh @@ -35,9 +35,11 @@ pass "Dex is up at $LIMEN_TEST_DEX_REFRESH_URL" step "Offboarding and onboarding against Dex" cd "$root" -out="$(cargo test -p limen-control-plane --test dex_offboarding --test idp_offboarding 2>&1)" || { echo "$out"; fail "tests failed"; } -echo "$out" | grep -E '^test |test result' -echo "$out" | grep -q '^SKIPPED' && fail "a test was skipped" +# --nocapture: libtest swallows a passing test's stderr, which is where a +# skipped test says so. +out="$(cargo test -p limen-control-plane --test dex_offboarding --test idp_offboarding -- --nocapture 2>&1)" || { echo "$out"; fail "tests failed"; } +grep -E '^test |test result' <<<"$out" +if grep -q 'SKIPPED' <<<"$out"; then fail "a test was skipped"; fi pass "groups became roles; a revoked session ended the login and locked the person; signing in lifted the lock" if [ "${1:-}" = "--down" ]; then "${stack[@]}" down -v >/dev/null; fi diff --git a/demos/demo-shadow.sh b/demos/demo-shadow.sh index 7420e570..0c245e1b 100755 --- a/demos/demo-shadow.sh +++ b/demos/demo-shadow.sh @@ -57,7 +57,9 @@ run() { # run step "$1" out="$(cargo test -p "$2" --test "$3" -- --nocapture --test-threads=1 2>&1)" || { echo "$out" | tail -n 30; fail "$1"; } # A skipped test is not a pass. - if echo "$out" | grep -q SKIPPED; then fail "$1 was skipped"; fi + # A here-string, not a pipe: under pipefail, grep -q exiting early can + # SIGPIPE the echo and turn a match into a miss. + if grep -q SKIPPED <<<"$out"; then fail "$1 was skipped"; fi echo "$out" | tail -n 4 pass "$1" }