diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c9090fe..9cd0c1a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,6 +25,8 @@ jobs: - uses: pnpm/action-setup@v4 - run: pnpm install --frozen-lockfile - run: pnpm lint + # The demo Integrator's page test drives its site in Playwright's Chromium. + - run: pnpm exec playwright install ${{ runner.os == 'Linux' && '--with-deps' || '' }} chromium - run: pnpm test - run: rustup show - name: Pre-commit hook tests diff --git a/crates/countersign-broker/src/lib.rs b/crates/countersign-broker/src/lib.rs index eb54c9f..30d306f 100644 --- a/crates/countersign-broker/src/lib.rs +++ b/crates/countersign-broker/src/lib.rs @@ -94,7 +94,13 @@ pub struct Offer { #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct ValidatedCertificate { pub sha256: [u8; 32], + /// The earliest not-after across the selected chain, which caps the grant. pub not_after_unix_seconds: i64, + /// The selected leaf's own subject, issuer and not-after, which the + /// approval status call reports. + pub subject: String, + pub issuer: String, + pub leaf_not_after_unix_seconds: i64, } #[derive(Debug, Clone, PartialEq, Eq, Serialize)] diff --git a/crates/countersign-broker/src/schema.sql b/crates/countersign-broker/src/schema.sql index 54b6f83..2b9649f 100644 --- a/crates/countersign-broker/src/schema.sql +++ b/crates/countersign-broker/src/schema.sql @@ -43,7 +43,10 @@ CREATE TABLE IF NOT EXISTS approved_grant ( approval TEXT NOT NULL UNIQUE REFERENCES approval(id), offer TEXT NOT NULL UNIQUE REFERENCES offer(id), certificate BLOB NOT NULL CHECK (length(certificate) = 32), - expires_at INTEGER NOT NULL + expires_at INTEGER NOT NULL, + -- The selected leaf's names and own not-after; NULL for grants recorded + -- before the Broker kept them. + subject TEXT, issuer TEXT, not_after INTEGER ) STRICT; CREATE TABLE IF NOT EXISTS decision ( diff --git a/crates/countersign-broker/src/service/backend.rs b/crates/countersign-broker/src/service/backend.rs index 162afd7..f82d47a 100644 --- a/crates/countersign-broker/src/service/backend.rs +++ b/crates/countersign-broker/src/service/backend.rs @@ -161,24 +161,91 @@ pub(super) async fn status( Json(req): Json, ) -> Result> { auth(&s, &h)?; - s.apply(move |a| { - let row = a.store.connection.query_row( + s.apply(move |a| view(a, req.id.as_str(), req.user.as_str()).map(Json)) + .await +} +/// The approval status view of approval `id`, owned by `user` under this Integrator. +fn view(a: &Authority, id: &str, user: &str) -> Result { + let row = a.store.connection.query_row( "SELECT CASE WHEN state='pending' AND pending_until<=unixepoch() THEN 'expired' WHEN state='approved' AND g.expires_at<=unixepoch() THEN 'expired' ELSE state END, g.id, EXISTS(SELECT 1 FROM gateway_observation o WHERE o.grant_id=g.id AND o.observation='mtls_accepted'), (SELECT count(*) FROM gateway_observation o WHERE o.grant_id=g.id AND o.observation='ingress_closed'), - (SELECT count(*) FROM gateway_observation o WHERE o.grant_id=g.id AND o.observation='egress_closed') + (SELECT count(*) FROM gateway_observation o WHERE o.grant_id=g.id AND o.observation='egress_closed'), + g.expires_at, lower(hex(g.certificate)), g.subject, g.issuer, g.not_after FROM approval a LEFT JOIN approved_grant g ON g.approval=a.id WHERE a.id=?1 AND a.integrator=?2 AND a.owner=?3", - params![req.id.as_str(),a.integrator.as_str(),req.user.as_str()], - |r|Ok((r.get::<_,String>(0)?,r.get::<_,Option>(1)?,r.get::<_,bool>(2)?,r.get::<_,i64>(3)?,r.get::<_,i64>(4)?)), + params![id,a.integrator.as_str(),user], + |r|Ok((r.get::<_,String>(0)?,r.get::<_,Option>(1)?,r.get::<_,bool>(2)?,r.get::<_,i64>(3)?,r.get::<_,i64>(4)?, + r.get::<_,Option>(5)?,r.get::<_,Option>(6)?, + (r.get::<_,Option>(7)?,r.get::<_,Option>(8)?,r.get::<_,Option>(9)?))), ).optional()?.ok_or(Fault::Unavailable)?; - let (state, grant, accepted, ingress_closed, egress_closed) = row; - let ready = state=="approved" && grant.and_then(|id|a.grants.get(&id)).is_some_and(|g|{ - g.acknowledged && a.peers.get(g.activation.grant.device.pairing.as_str()).is_some_and(|p|p.binding==g.activation.grant.device) + let ( + state, + grant, + accepted, + ingress_closed, + egress_closed, + expires_at, + certificate_sha256, + leaf, + ) = row; + let ready = state == "approved" + && grant.and_then(|id| a.grants.get(&id)).is_some_and(|g| { + g.acknowledged + && a.peers + .get(g.activation.grant.device.pairing.as_str()) + .is_some_and(|p| p.binding == g.activation.grant.device) }); - Ok(Json(json!({"id":req.id,"state":state,"ready":ready,"upstream_mtls_accepted":accepted,"ingress_closed_count":ingress_closed,"egress_closed_count":egress_closed}))) - }).await + let mut view = json!({"id":id,"state":state,"ready":ready,"upstream_mtls_accepted":accepted,"ingress_closed_count":ingress_closed,"egress_closed_count":egress_closed}); + // A grant row outlives its approval's end (expired, replaced, cancelled), so these + // keep describing the grant that was approved; an approval that never had one omits them. + if let (Some(expires_at), Some(sha256)) = (expires_at, certificate_sha256) { + view["expires_at_ms"] = json!(expires_at.checked_mul(1000).ok_or(Fault::Storage)?); + view["certificate"] = json!({"sha256": sha256}); + // A grant recorded before the Broker kept the leaf's names has none. + if let (Some(subject), Some(issuer), Some(not_after)) = leaf { + view["certificate"]["subject"] = json!(subject); + view["certificate"]["issuer"] = json!(issuer); + view["certificate"]["not_after_ms"] = + json!(not_after.checked_mul(1000).ok_or(Fault::Storage)?); + } + } + Ok(view) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Lookup { + binding: w::WorkloadBinding, + host: Origin, +} +/// The Workload's current approval for `host`, the one its Gateway traffic +/// uses, as the status call shows it. Unlike `requests`, it never creates one. +pub(super) async fn current( + State(s): State, + h: HeaderMap, + Json(req): Json, +) -> Result> { + auth(&s, &h)?; + s.apply(move |a| { + // Only this Integrator's own Workloads have a current approval here. + if req.binding.integrator != a.integrator { + return Err(Fault::Unavailable); + } + let scope = a.policy.scope_for(&req.host).ok_or(Fault::Unavailable)?; + let b = &req.binding; + let id: String = a.store.connection.query_row( + "SELECT id FROM approval WHERE current=1 AND integrator=?1 AND owner=?2 AND context=?3 + AND workload=?4 AND workload_generation=?5 AND entry_id=?6 AND entry_version=?7 AND scope=?8", + params![a.integrator.as_str(),b.user.as_str(),b.context.as_str(),b.workload.as_str(), + i64::try_from(b.workload_generation.get()).map_err(|_|Fault::Invalid)?, + scope.entry_id(),i64::try_from(scope.entry_version()).map_err(|_|Fault::Invalid)?, + scope.pattern().to_string()], + |r| r.get(0), + ).optional()?.ok_or(Fault::Unavailable)?; + view(a, &id, b.user.as_str()).map(Json) + }) + .await } pub(super) async fn revoke( State(s): State, diff --git a/crates/countersign-broker/src/service/companion.rs b/crates/countersign-broker/src/service/companion.rs index 8bfe952..e54862e 100644 --- a/crates/countersign-broker/src/service/companion.rs +++ b/crates/countersign-broker/src/service/companion.rs @@ -548,6 +548,9 @@ fn decide( certificate: ValidatedCertificate { sha256: hash, not_after_unix_seconds: expiry, + subject: valid.subject, + issuer: valid.issuer, + leaf_not_after_unix_seconds: valid.leaf_end, }, duration_seconds: duration_s, }, diff --git a/crates/countersign-broker/src/service/mod.rs b/crates/countersign-broker/src/service/mod.rs index 31244d3..83b3f92 100644 --- a/crates/countersign-broker/src/service/mod.rs +++ b/crates/countersign-broker/src/service/mod.rs @@ -213,6 +213,7 @@ impl Service { .route("/v1/backend/pairings/confirm", post(backend::confirm)) .route("/v1/backend/requests", post(backend::request)) .route("/v1/backend/status", post(backend::status)) + .route("/v1/backend/approvals/current", post(backend::current)) .route("/v1/backend/revoke", post(backend::revoke)) .route("/v1/backend/renew", post(backend::renew)) .route("/v1/backend/contexts/close", post(controls::close_context)) diff --git a/crates/countersign-broker/src/sqlite.rs b/crates/countersign-broker/src/sqlite.rs index 22a3d7c..792264c 100644 --- a/crates/countersign-broker/src/sqlite.rs +++ b/crates/countersign-broker/src/sqlite.rs @@ -36,6 +36,20 @@ impl SqliteApprovalStore { } tx.pragma_update(None, "user_version", 1)?; } + // Grants gained the leaf's names without a version bump, so a Broker + // that predates them can still open the store and ignores them. + let has_subject: bool = tx.query_row( + "SELECT EXISTS(SELECT 1 FROM pragma_table_info('approved_grant') WHERE name='subject')", + [], + |r| r.get(0), + )?; + if !has_subject { + tx.execute_batch( + "ALTER TABLE approved_grant ADD COLUMN subject TEXT; + ALTER TABLE approved_grant ADD COLUMN issuer TEXT; + ALTER TABLE approved_grant ADD COLUMN not_after INTEGER;", + )?; + } tx.commit()?; Ok(Self { connection }) } @@ -496,14 +510,17 @@ impl ApprovalStore for SqliteApprovalStore { .not_after_unix_seconds .min(at + i64::from(duration_seconds.get())); tx.execute( - "INSERT INTO approved_grant (id, approval, offer, certificate, expires_at) - VALUES (?1, ?2, ?3, ?4, ?5)", + "INSERT INTO approved_grant (id, approval, offer, certificate, expires_at, subject, issuer, not_after) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", params![ Uuid::new_v4().to_string(), approval_id.to_string(), offer_text, certificate.sha256, - expiry + expiry, + certificate.subject, + certificate.issuer, + certificate.leaf_not_after_unix_seconds ], )?; "approved" diff --git a/crates/countersign-broker/src/validation.rs b/crates/countersign-broker/src/validation.rs index 8ecc082..6427bf7 100644 --- a/crates/countersign-broker/src/validation.rs +++ b/crates/countersign-broker/src/validation.rs @@ -36,6 +36,9 @@ pub(crate) struct Validator { pub(crate) struct Verdict { pub certificate_end: i64, pub evidence_end: i64, + pub subject: String, + pub issuer: String, + pub leaf_end: i64, } impl Validator { pub(crate) fn new(profile: Profile, default_ca: &Path) -> Result { @@ -187,6 +190,9 @@ impl Validator { Ok(Verdict { certificate_end: cert_end, evidence_end: cert_end.min(until), + subject: client.subject().to_string(), + issuer: client.issuer().to_string(), + leaf_end: client.validity.not_after.timestamp(), }) } } diff --git a/crates/countersign-broker/tests/approvals.rs b/crates/countersign-broker/tests/approvals.rs index c94d5e9..cc2ab9f 100644 --- a/crates/countersign-broker/tests/approvals.rs +++ b/crates/countersign-broker/tests/approvals.rs @@ -72,6 +72,9 @@ fn approve(cert: u8, seconds: u32) -> Decision { certificate: ValidatedCertificate { sha256: [cert; 32], not_after_unix_seconds: i64::MAX, + subject: "CN=user".into(), + issuer: "CN=issuer".into(), + leaf_not_after_unix_seconds: i64::MAX, }, duration_seconds: NonZeroU32::new(seconds).unwrap(), } @@ -260,6 +263,9 @@ fn expired_requests_cannot_create_grants_and_validation_cannot_extend_consent() certificate: ValidatedCertificate { sha256: [9; 32], not_after_unix_seconds: expiry, + subject: "CN=user".into(), + issuer: "CN=issuer".into(), + leaf_not_after_unix_seconds: expiry, }, duration_seconds: NonZeroU32::new(7200).unwrap(), }; @@ -449,3 +455,41 @@ fn opening_preview_database_migrates_lease_fences_transactionally() { inspect.pragma_update(None, "user_version", 99).unwrap(); assert!(SqliteApprovalStore::open(&path).is_err()); } + +#[test] +fn opening_an_older_store_adds_the_leaf_columns_to_existing_grants() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("authority.db"); + { + let old = Connection::open(&path).unwrap(); + old.execute_batch( + "CREATE TABLE approved_grant ( + id TEXT PRIMARY KEY NOT NULL, + approval TEXT NOT NULL UNIQUE REFERENCES approval(id), + offer TEXT NOT NULL UNIQUE REFERENCES offer(id), + certificate BLOB NOT NULL CHECK (length(certificate) = 32), + expires_at INTEGER NOT NULL + ) STRICT; + PRAGMA user_version = 1;", + ) + .unwrap(); + } + for _ in 0..2 { + drop(SqliteApprovalStore::open(&path).unwrap()); + } + let db = Connection::open(&path).unwrap(); + let columns: Vec = db + .prepare("SELECT name FROM pragma_table_info('approved_grant')") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .collect::>() + .unwrap(); + for column in ["subject", "issuer", "not_after"] { + assert!(columns.iter().any(|c| c == column), "{columns:?}"); + } + let version: i64 = db + .query_row("PRAGMA user_version", [], |r| r.get(0)) + .unwrap(); + assert_eq!(version, 1, "an older Broker can still open the store"); +} diff --git a/crates/countersign-broker/tests/service.rs b/crates/countersign-broker/tests/service.rs index 36031be..4100cec 100644 --- a/crates/countersign-broker/tests/service.rs +++ b/crates/countersign-broker/tests/service.rs @@ -29,6 +29,8 @@ use uuid::Uuid; const ADMIN: &str = "test-only-dedicated-administrator-secret"; const BACKEND: &str = "integration-test-dedicated-service-secret"; +/// 2099-01-01T00:00:00Z, the harness leaf's own not-after. +const LEAF_NOT_AFTER_MS: u64 = 4_070_908_800_000; type Socket = tokio_tungstenite::WebSocketStream>; struct Harness { @@ -59,6 +61,10 @@ impl Harness { let client_key = KeyPair::generate().unwrap(); let mut identity = CertificateParams::default(); identity.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth]; + identity + .distinguished_name + .push(rcgen::DnType::CommonName, "Broker integration test user"); + identity.not_after = rcgen::date_time_ymd(2099, 1, 1); let leaf = identity .signed_by(&client_key, &issuer) .unwrap() @@ -462,6 +468,9 @@ async fn authenticated_consent_signing_reconnect_and_revocation() { assert_eq!(ended["state"], "cancelled"); assert_eq!(ended["ready"], false); assert_eq!(ended["egress_closed_count"], 1); + assert_eq!(ended["expires_at_ms"], view["expires_at_ms"]); + assert_eq!(ended["certificate"], view["certificate"]); + assert!(ended["certificate"]["sha256"].is_string(), "{ended}"); assert!( !h.post("gateway/lease", token, lease(3)) .await @@ -628,3 +637,257 @@ async fn admin_authority_and_context_tombstones_gate_workload_admission() { 403 ); } + +async fn status(h: &Harness, id: &Value) -> Value { + h.post("backend/status", BACKEND, json!({"user":"u","id":id})) + .await + .error_for_status() + .unwrap() + .json() + .await + .unwrap() +} +async fn current(h: &Harness, lookup: &Value) -> Value { + h.post("backend/approvals/current", BACKEND, lookup.clone()) + .await + .error_for_status() + .unwrap() + .json() + .await + .unwrap() +} +/// Approves the pending approval `id` with the harness leaf and returns the activation's deadline. +/// A renewal's approval also retires its predecessor's grant on this Companion. +async fn approve( + h: &Harness, + sock: &mut Socket, + id: &Value, + duration_s: u64, + renewal: bool, +) -> u64 { + let hash = digest::digest(&digest::SHA256, &h.leaf); + send(sock, frame("fetch", json!({"id":id}))).await; + let offered = receive(sock, "offer").await["body"].clone(); + send( + sock, + frame( + "decide", + json!({"binding":offered["binding"],"answer":{"approve":{ + "duration_s":duration_s,"chain":[STANDARD.encode(&h.leaf)], + "cert_sha256":STANDARD.encode(hash.as_ref()) + }}}), + ), + ) + .await; + let activation = receive(sock, "activate").await["body"].clone(); + if renewal { + receive(sock, "retire").await; + } + send(sock, frame("activated", activation.clone())).await; + send(sock, frame("inbox", json!({}))).await; + receive(sock, "inbox").await; + activation["expires_at_ms"].as_u64().unwrap() +} +#[tokio::test] +async fn status_reports_grant_expiry_and_certificate_once_a_grant_exists() { + let h = Harness::start().await; + let (mut sock, _) = pair(&h, "u").await; + let credentials: Value = h + .post( + "backend/workloads", + BACKEND, + json!({"user":"u","context":"job","workload":"instance","workload_generation":1}), + ) + .await + .error_for_status() + .unwrap() + .json() + .await + .unwrap(); + let token = credentials["token"].as_str().unwrap(); + let lookup = json!({"binding":credentials["binding"],"host":"upstream.test:443"}); + let none = h + .post("backend/approvals/current", BACKEND, lookup.clone()) + .await; + assert_eq!(none.status(), 404); + let db = rusqlite::Connection::open(h._dir.path().join("store.db")).unwrap(); + let approvals = |db: &rusqlite::Connection| { + db.query_row("SELECT count(*) FROM approval", [], |r| r.get::<_, i64>(0)) + .unwrap() + }; + assert_eq!(approvals(&db), 0, "the lookup creates no approval"); + let pending: Value = h + .post( + "gateway/admit", + token, + frame( + "connect", + json!({"workload":credentials["binding"],"host":"upstream.test:443"}), + ), + ) + .await + .error_for_status() + .unwrap() + .json() + .await + .unwrap(); + let first = pending["body"]["id"].clone(); + assert_eq!(current(&h, &lookup).await["id"], first); + let view = status(&h, &first).await; + assert_eq!(view["state"], "pending"); + assert!(view.get("expires_at_ms").is_none(), "{view}"); + assert!(view.get("certificate").is_none(), "{view}"); + + let hash = digest::digest(&digest::SHA256, &h.leaf); + let sha256: String = hash.as_ref().iter().map(|b| format!("{b:02x}")).collect(); + let before = millis(); + let first_expiry = approve(&h, &mut sock, &first, 900, false).await; + let view = status(&h, &first).await; + assert_eq!(view["state"], "approved"); + let leaf = json!({ + "sha256": sha256, + "subject": "CN=Broker integration test user", + "issuer": "CN=Broker integration test CA", + "not_after_ms": LEAF_NOT_AFTER_MS, + }); + assert_eq!(view["certificate"], leaf); + assert_eq!( + current(&h, &lookup).await, + view, + "the lookup returns the status view" + ); + let expires = view["expires_at_ms"].as_u64().unwrap(); + assert_eq!(expires % 1000, 0, "whole seconds, as the grant stores them"); + assert!( + (before + 899_000..=millis() + 900_000).contains(&expires), + "{expires}" + ); + assert_eq!( + expires, first_expiry, + "the deadline the Companion was given" + ); + + let renewed: Value = h + .post( + "backend/renew", + BACKEND, + json!({"binding":credentials["binding"],"id":first}), + ) + .await + .error_for_status() + .unwrap() + .json() + .await + .unwrap(); + let second = renewed["id"].clone(); + assert_ne!(second, first); + assert!(status(&h, &second).await.get("certificate").is_none()); + assert_eq!( + current(&h, &lookup).await["id"], + first, + "a pending renewal is not yet current" + ); + approve(&h, &mut sock, &second, 600, true).await; + let replaced = status(&h, &first).await; + assert_eq!(replaced["state"], "replaced"); + assert_eq!( + replaced["expires_at_ms"], expires, + "predecessor keeps its own deadline" + ); + assert_eq!(replaced["certificate"], leaf); + let successor = status(&h, &second).await; + assert_eq!(successor["state"], "approved"); + assert_eq!(current(&h, &lookup).await["id"], second); + let mut stranger = lookup.clone(); + stranger["binding"]["integrator"] = "someone-else".into(); + assert_eq!( + h.post("backend/approvals/current", BACKEND, stranger) + .await + .status(), + 404 + ); + assert!(successor["expires_at_ms"].as_u64().unwrap() < expires); + + let refused: Value = h + .post( + "backend/renew", + BACKEND, + json!({"binding":credentials["binding"],"id":second}), + ) + .await + .error_for_status() + .unwrap() + .json() + .await + .unwrap(); + send(&mut sock, frame("fetch", json!({"id":refused["id"]}))).await; + let offered = receive(&mut sock, "offer").await["body"].clone(); + send( + &mut sock, + frame( + "decide", + json!({"binding":offered["binding"],"answer":"deny"}), + ), + ) + .await; + send(&mut sock, frame("inbox", json!({}))).await; + receive(&mut sock, "inbox").await; + let denied = status(&h, &refused["id"]).await; + assert_eq!(denied["state"], "denied"); + assert!(denied.get("expires_at_ms").is_none(), "{denied}"); + assert!(denied.get("certificate").is_none(), "{denied}"); + assert_eq!(status(&h, &second).await["state"], "approved"); + + let lapsed: Value = h + .post( + "backend/renew", + BACKEND, + json!({"binding":credentials["binding"],"id":second}), + ) + .await + .error_for_status() + .unwrap() + .json() + .await + .unwrap(); + assert_ne!(lapsed["id"], refused["id"]); + db.execute( + "UPDATE approval SET pending_until=unixepoch()-5 WHERE id=?1", + [lapsed["id"].as_str().unwrap()], + ) + .unwrap(); + let never_granted = status(&h, &lapsed["id"]).await; + assert_eq!(never_granted["state"], "expired"); + assert!( + never_granted.get("expires_at_ms").is_none(), + "{never_granted}" + ); + assert!( + never_granted.get("certificate").is_none(), + "{never_granted}" + ); + + let expired_at_s = db + .query_row( + "UPDATE approved_grant SET expires_at=unixepoch()-5 WHERE approval=?1 RETURNING expires_at", + [second.as_str().unwrap()], + |r| r.get::<_, i64>(0), + ) + .unwrap(); + let expired = status(&h, &second).await; + assert_eq!(expired["state"], "expired"); + assert_eq!(expired["ready"], false); + assert_eq!(expired["expires_at_ms"], expired_at_s * 1000); + assert_eq!(expired["certificate"], leaf); + + // A grant recorded before the Broker kept the leaf's names reports its digest alone. + db.execute( + "UPDATE approved_grant SET subject=NULL, issuer=NULL, not_after=NULL WHERE approval=?1", + [second.as_str().unwrap()], + ) + .unwrap(); + assert_eq!( + status(&h, &second).await["certificate"], + json!({"sha256": sha256}) + ); +} diff --git a/docs/assets/screenshots/access-active-dark.png b/docs/assets/screenshots/access-active-dark.png index 5ae95d6..0d0e0a6 100644 Binary files a/docs/assets/screenshots/access-active-dark.png and b/docs/assets/screenshots/access-active-dark.png differ diff --git a/docs/assets/screenshots/access-active.png b/docs/assets/screenshots/access-active.png index 021a68e..b40b775 100644 Binary files a/docs/assets/screenshots/access-active.png and b/docs/assets/screenshots/access-active.png differ diff --git a/docs/assets/screenshots/job-result-dark.png b/docs/assets/screenshots/job-result-dark.png index bc2f959..527884c 100644 Binary files a/docs/assets/screenshots/job-result-dark.png and b/docs/assets/screenshots/job-result-dark.png differ diff --git a/docs/assets/screenshots/job-result.png b/docs/assets/screenshots/job-result.png index 6757649..0be43ba 100644 Binary files a/docs/assets/screenshots/job-result.png and b/docs/assets/screenshots/job-result.png differ diff --git a/docs/assets/screenshots/raw/access-active-dark.png b/docs/assets/screenshots/raw/access-active-dark.png index fd4b81f..c6b991c 100644 Binary files a/docs/assets/screenshots/raw/access-active-dark.png and b/docs/assets/screenshots/raw/access-active-dark.png differ diff --git a/docs/assets/screenshots/raw/access-active.png b/docs/assets/screenshots/raw/access-active.png index 9c78146..a53ae9f 100644 Binary files a/docs/assets/screenshots/raw/access-active.png and b/docs/assets/screenshots/raw/access-active.png differ diff --git a/docs/assets/screenshots/raw/boxes.json b/docs/assets/screenshots/raw/boxes.json index fe5a95f..2f16997 100644 --- a/docs/assets/screenshots/raw/boxes.json +++ b/docs/assets/screenshots/raw/boxes.json @@ -2,26 +2,38 @@ "access-active-dark.png": { "scale": 2, "width": 960, - "height": 764, + "height": 824, "boxes": { "progress": [ 49, 409.3, 574.8, 448.3 + ], + "ends": [ + 49, + 542.3, + 307.9, + 588.3 ] } }, "access-active.png": { "scale": 2, "width": 960, - "height": 764, + "height": 824, "boxes": { "progress": [ 49, 409.3, 574.8, 448.3 + ], + "ends": [ + 49, + 542.3, + 307.9, + 588.3 ] } }, @@ -418,38 +430,38 @@ "job-result-dark.png": { "scale": 2, "width": 960, - "height": 663, + "height": 630, "boxes": { "compare": [ 49, 296.3, 911, - 451.4 + 417.5 ], "match": [ 49, - 467.4, + 433.5, 462.5, - 506.4 + 472.5 ] } }, "job-result.png": { "scale": 2, "width": 960, - "height": 663, + "height": 630, "boxes": { "compare": [ 49, 296.3, 911, - 451.4 + 417.5 ], "match": [ 49, - 467.4, + 433.5, 462.5, - 506.4 + 472.5 ] } }, diff --git a/docs/assets/screenshots/raw/job-result-dark.png b/docs/assets/screenshots/raw/job-result-dark.png index ac8eb6f..78de183 100644 Binary files a/docs/assets/screenshots/raw/job-result-dark.png and b/docs/assets/screenshots/raw/job-result-dark.png differ diff --git a/docs/assets/screenshots/raw/job-result.png b/docs/assets/screenshots/raw/job-result.png index fa3e13c..7a4515c 100644 Binary files a/docs/assets/screenshots/raw/job-result.png and b/docs/assets/screenshots/raw/job-result.png differ diff --git a/docs/integrate.md b/docs/integrate.md index 1a2a420..8725340 100644 --- a/docs/integrate.md +++ b/docs/integrate.md @@ -70,12 +70,12 @@ The widget draws only the pairing, request and launch controls in its own Counte ## Show progress and end access -Query `status` with the session-derived user ID and the approval ID. Show “Approved” for a committed decision, “Ready for handshakes” when `ready` is true, and “Upstream accepted mTLS” only after `upstream_mtls_accepted` is true. Closing the Companion can leave an existing leased connection usable until its authority expires. A fresh handshake needs the winning Companion online. [Status fields and failure handling](reference/api.md#read-approval-status) +Query `status` with the session-derived user ID and the approval ID. Show “Approved” for a committed decision, “Ready for handshakes” when `ready` is true, and “Upstream accepted mTLS” only after `upstream_mtls_accepted` is true. While the grant is active, `expires_at_ms` gives the deadline the user approved, so the page can count down to it. Closing the Companion can leave an existing leased connection usable until its authority expires. A fresh handshake needs the winning Companion online. [Status fields and failure handling](reference/api.md#read-approval-status) -![The demo Integrator's access page with the three progress steps Approved, Ready for handshakes and Upstream accepted mTLS, and Renew and Revoke access controls.](assets/screenshots/access-active.png#gh-light-mode-only)![The demo Integrator's access page with the three progress steps Approved, Ready for handshakes and Upstream accepted mTLS, and Renew and Revoke access controls.](assets/screenshots/access-active-dark.png#gh-dark-mode-only) +![The demo Integrator's access page with the three progress steps Approved, Ready for handshakes and Upstream accepted mTLS, a countdown to when access ends, and Renew and Revoke access controls.](assets/screenshots/access-active.png#gh-light-mode-only)![The demo Integrator's access page with the three progress steps Approved, Ready for handshakes and Upstream accepted mTLS, a countdown to when access ends, and Renew and Revoke access controls.](assets/screenshots/access-active-dark.png#gh-dark-mode-only) Retire the Workload when the job exits. Close the Context when the reconciliation itself ends. To withdraw one grant earlier, revoke its approval ID. After a denial, expiry or revocation, say how access ended and offer a fresh request. ![The demo Integrator's page after revocation, explaining that open connections close by their lease deadline and pointing to the widget's Request access button for a fresh approval.](assets/screenshots/access-ended.png#gh-light-mode-only)![The demo Integrator's page after revocation, explaining that open connections close by their lease deadline and pointing to the widget's Request access button for a fresh approval.](assets/screenshots/access-ended-dark.png#gh-dark-mode-only) - In the demo, the upstream requires a client certificate and returns the leaf fingerprint it actually received. Compare it with the identity selected in the Companion. [Demo upstream](https://github.com/zeroae/countersign/blob/fbb5aa7c951f8b70a238f3351140aa44a6184adf/examples/demo-integrator/upstream.js) + In the demo, the upstream requires a client certificate and returns the leaf fingerprint it actually received. Compare it with `certificate.sha256`, the certificate the user selected in the Companion. When the job's own connection started the approval, the backend finds it with `approvals/current`. Look it up as soon as the job's result lands and keep its ID, since a later renewal can make another approval current; the demo's Job result page does this. [Demo upstream](https://github.com/zeroae/countersign/blob/fbb5aa7c951f8b70a238f3351140aa44a6184adf/examples/demo-integrator/upstream.js) diff --git a/docs/reference/api.md b/docs/reference/api.md index 192d0fa..30b88b8 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -51,6 +51,7 @@ All paths in this table start with `/v1/backend/` and use POST. A 204 response h | `pairings/forget` | `user`, `targets` array of current device bindings | 200 with the remaining devices. Removes the target pairings and withdraws their grants. | | `requests` | `binding`, `host` such as `ledger.partner.example:443` | 200 with `{"id":"…","state":"pending"}` or an existing matching approved record. An explicit request can retry a previously denied, cancelled or expired scope. | | `status` | `user`, `id` | 200 with the status and observations described below. | +| `approvals/current` | `binding`, `host` | 200 with the `status` view of that Workload's current approval for the host: the one its Gateway traffic uses, including one the Workload's own connection started. 404 `unavailable` when it has none. Unlike `requests`, it never creates an approval. A pending renewal becomes current only once approved. | | `renew` | `binding`, `id` of the live approved request | 200 with the new pending approval ID. The previous grant remains usable until its deadline or a successful replacement. | | `revoke` | `user`, `id` | 204. Records withdrawal and cancels an outstanding renewal for that approval. Repeat calls for the same owned record are idempotent. | | `workloads/retire` | `binding` | 204. Retires that Workload generation. | @@ -67,6 +68,13 @@ Take device bindings directly from a fresh `devices` response. Each contains `pa "id": "85b80155-ac10-487f-a024-5216ec7f8ced", "state": "approved", "ready": true, + "expires_at_ms": 1795470000000, + "certificate": { + "sha256": "c64a4b8b8bcdac1a7ac2bedcd13c520f4abfc07d5765d68df67f56ed0058f00b", + "subject": "CN=Demo user", + "issuer": "CN=Countersign demo client-ca", + "not_after_ms": 1795635570000 + }, "upstream_mtls_accepted": false, "ingress_closed_count": 0, "egress_closed_count": 0 @@ -75,6 +83,10 @@ Take device bindings directly from a fresh `devices` response. Each contains `pa - `state` is `pending`, `approved`, `denied`, `cancelled`, `expired` or `replaced`. A pending offer has a ten-minute deadline. A successful renewal changes the predecessor's state to `replaced`. - `ready` means the winning Companion acknowledged activation and its matching channel is currently connected. An approved grant can have `ready: false` while that Companion is offline. +- `expires_at_ms` and `certificate` describe the grant the user approved. They appear once an approval has a grant, and stay after it ends (`expired`, `cancelled` or `replaced`); a renewal's successor has its own approval ID and its own values. They are absent when the approval never had a grant: it is `pending`, `denied`, or it was `expired` or `cancelled` before anyone approved it. They are also absent once the [audit retention](config.md) period removes an ended approval's grant record. +- `expires_at_ms` is the deadline the user approved, in milliseconds since the Unix epoch, in whole seconds. It is not always when access ends: a revocation, a renewal or a Gateway lease can end it sooner, and `state` says whether the grant is still in force. +- `certificate.sha256` is the lowercase hex SHA-256 of the client certificate the user selected (its DER encoding). It is the fingerprint the Companion shows, without its spaces, of the certificate the protected site receives in the handshake. +- `certificate.subject` and `certificate.issuer` are that certificate's distinguished names, written in the order the certificate encodes them and joined with `, ` (often most general first, such as `C=US, O=Acme, CN=Jane`, the reverse of RFC 4514), and `certificate.not_after_ms` is its own expiry, in milliseconds since the Unix epoch. A grant recorded by a Broker older than these fields has `sha256` alone. A matching subject does not identify the key; compare `sha256`. - `upstream_mtls_accepted` is historical. It becomes true after the Gateway reports receiving upstream HTTP response headers on an authenticated connection. - `ingress_closed_count` and `egress_closed_count` count distinct reported socket closures on the two legs. Reports are best effort. Enforcers cut traffic at their local lease deadline even if they cannot report back. [Gateway observations](https://github.com/zeroae/countersign/blob/fbb5aa7c951f8b70a238f3351140aa44a6184adf/crates/countersign-broker/src/service/observations.rs) diff --git a/docs/try.md b/docs/try.md index 75b0fd9..9c21e69 100644 --- a/docs/try.md +++ b/docs/try.md @@ -43,9 +43,9 @@ Read **Integrator**, **Account**, **Context**, **Requested host** and **Approval {"fingerprint":"c64a4b8b8bcdac1a7ac2bedcd13c520f4abfc07d5765d68df67f56ed0058f00b","subject":"Demo user"} ``` -Each launch creates fresh certificates. Compare the response to the fingerprint you selected in **your** run. Matching subject names alone cannot identify the key that signed the handshake. The launcher also hands the result to the Integrator: open **Job result** on the demo page, paste the SHA-256 from the approval in your Companion and choose **Compare**. +Each launch creates fresh certificates. Compare the response to the fingerprint you selected in **your** run. Matching subject names alone cannot identify the key that signed the handshake. The launcher also hands the result to the Integrator: open **Job result** on the demo page. It compares the fingerprint the site received with the certificate you approved, which the Integrator reads from the Broker's approval status. -![Harbor Ledger's job result page showing the fingerprint the site received and a confirmation that it matches the pasted SHA-256 of the approved certificate.](assets/screenshots/job-result.png#gh-light-mode-only)![Harbor Ledger's job result page showing the fingerprint the site received and a confirmation that it matches the pasted SHA-256 of the approved certificate.](assets/screenshots/job-result-dark.png#gh-dark-mode-only) +![Harbor Ledger's job result page showing the fingerprint the site received and the certificate approved in the Companion, and a confirmation that the two SHA-256 fingerprints match.](assets/screenshots/job-result.png#gh-light-mode-only)![Harbor Ledger's job result page showing the fingerprint the site received and the certificate approved in the Companion, and a confirmation that the two SHA-256 fingerprints match.](assets/screenshots/job-result-dark.png#gh-dark-mode-only) ## End access diff --git a/examples/demo-integrator/Dockerfile b/examples/demo-integrator/Dockerfile index 2afc51d..edca9dd 100644 --- a/examples/demo-integrator/Dockerfile +++ b/examples/demo-integrator/Dockerfile @@ -1,7 +1,7 @@ FROM node:24-bookworm-slim WORKDIR /app COPY packages/widget/src ./packages/widget/src -COPY examples/demo-integrator/integrator.js examples/demo-integrator/site-files.js examples/demo-integrator/upstream.js examples/demo-integrator/package.json ./examples/demo-integrator/ +COPY examples/demo-integrator/integrator.js examples/demo-integrator/job-approval.js examples/demo-integrator/site-files.js examples/demo-integrator/upstream.js examples/demo-integrator/package.json ./examples/demo-integrator/ COPY examples/demo-integrator/site ./examples/demo-integrator/site USER node WORKDIR /app/examples/demo-integrator diff --git a/examples/demo-integrator/compose_demo.py b/examples/demo-integrator/compose_demo.py index 383adb1..1da3b65 100644 --- a/examples/demo-integrator/compose_demo.py +++ b/examples/demo-integrator/compose_demo.py @@ -169,10 +169,10 @@ def verify(desktop, browser, origin, fixture, curl, state, url): job=web.new_page() job.goto(origin+"/job") expect(job.locator("#job-fingerprint")).to_have_text(fingerprint) - job.get_by_label("SHA-256 you selected in the Companion").fill(fingerprint) - job.get_by_role("button",name="Compare").click() + # The Integrator finds the job's approval through the Broker and compares by itself. + expect(job.locator("#job-approved")).to_have_text(fingerprint) expect(job.locator("#match")).to_be_visible() - print("Job page shows the fingerprint the site received",flush=True) + print("Job page matched the fingerprint the site received with the approval",flush=True) finally: if workload.poll() is None: workload.terminate() diff --git a/examples/demo-integrator/integrator.js b/examples/demo-integrator/integrator.js index b907ef1..e874002 100644 --- a/examples/demo-integrator/integrator.js +++ b/examples/demo-integrator/integrator.js @@ -2,9 +2,11 @@ // are server-side. A fresh random login secret is provisioned for each demo. import https from 'node:https'; import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; -import { readFile, rename, writeFile } from 'node:fs/promises'; +import { watchFile } from 'node:fs'; +import { readFile, rename, stat, writeFile } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; import { contentSecurityPolicy, files, manifest } from './site-files.js'; +import { jobApproval } from './job-approval.js'; const env = process.env; const secrets = env.DEMO_SECRETS || '/demo'; @@ -32,14 +34,29 @@ async function broker(path, body) { } // Pass through only the fields the job page shows. -async function lastJob() { - const job=await readFile(jobFile,'utf8').then(JSON.parse,()=>null); +function lastJob(raw) { + let job=null; + try { job=JSON.parse(raw); } catch { /* no result yet */ } if(!job||typeof job.url!=='string')return null; const text=v=>typeof v==='string'?v.slice(0,512):null; return {url:text(job.url),ok:job.ok===true,http_status:Number.isInteger(job.http_status)?job.http_status:null, fingerprint:text(job.fingerprint),subject:text(job.subject),error:text(job.error)}; } +// The approval each job ran under: the Workload's current approval for the +// host when the launcher records the job's result. The lookup never creates +// an approval; a failed lookup leaves the result shown without one. +const jobs=jobApproval({ + // The mtime tells a rerun that wrote the same text from the last job. + read:async()=>{ + try{const {mtimeMs}=await stat(jobFile);return {text:await readFile(jobFile,'utf8'),stamp:mtimeMs};} + catch{return null;} + }, + current:()=>broker('approvals/current',{binding,host}), + status:id=>broker('status',{user:workload.user,id}), +}); +watchFile(jobFile,{interval:1000},()=>void jobs.landed().catch(()=>{})).unref(); + async function issueToken() { const path=env.WORKLOAD_TOKEN_FILE; if (!path) return; @@ -98,7 +115,7 @@ const server=https.createServer({ca,cert,key,maxHeaderSize:8192},async (req,res) case '/api/revoke':result=await broker('revoke',{user:workload.user,id:body.id});break; case '/api/devices':result=await broker('devices',{user:workload.user});break; case '/api/forget':result=await broker('pairings/forget',{user:workload.user,targets:body.targets});break; - case '/api/job':result={result:await lastJob()};break; + case '/api/job':{const {text,approval}=await jobs.forJob();result={result:lastJob(text),approval};break;} case '/api/subscribe':result=await broker('push/subscribe',{user:workload.user,subscription:body.subscription});break; case '/api/logout': if(body.endpoint)await broker('push/unsubscribe',{user:workload.user,endpoint:body.endpoint}); diff --git a/examples/demo-integrator/job-approval.js b/examples/demo-integrator/job-approval.js new file mode 100644 index 0000000..13409ab --- /dev/null +++ b/examples/demo-integrator/job-approval.js @@ -0,0 +1,34 @@ +// Pins the approval a job ran under: the Workload's current approval when the +// job's result lands. A renewal approved later, or a fresh request after the +// approval ends, then does not change which certificate the Job page compares. +// +// read() the job result as { text, stamp }, where stamp changes each time +// the result is written (its mtime), or null when there is none +// current() the Workload's current approval (Broker approvals/current) +// status(id) that approval's status (Broker status), which keeps its +// certificate after it is replaced or ends +export function jobApproval({ read, current, status }) { + let pinned = null; // { text, stamp, id } for the job result last seen + // A rerun can write the same text again, so a result is known by both. + const same = job => job.text === pinned?.text && job.stamp === pinned.stamp; + async function pin(job) { + const approval = await current().catch(() => null); + pinned = { text: job.text, stamp: job.stamp, id: approval?.id ?? null }; + return approval; + } + return { + // Call when the job's result may have changed. + async landed() { + const job = await read(); + if (job !== null && !same(job)) await pin(job); + }, + // The job's result text and the approval it ran under, or null when unknown. + async forJob() { + const job = await read(); + if (job === null) return { text: null, approval: null }; + // A job nobody pinned yet, or one whose lookup failed, pins at this read. + if (!same(job) || !pinned.id) return { text: job.text, approval: await pin(job) }; + return { text: job.text, approval: await status(pinned.id).catch(() => null) }; + }, + }; +} diff --git a/examples/demo-integrator/package.json b/examples/demo-integrator/package.json index 72594ae..746bf48 100644 --- a/examples/demo-integrator/package.json +++ b/examples/demo-integrator/package.json @@ -2,5 +2,5 @@ "name": "@countersign/demo-integrator", "private": true, "type": "module", - "scripts": { "start": "node integrator.js", "lint": "eslint *.js site/*.js", "test": "node --test" } + "scripts": { "start": "node integrator.js", "lint": "eslint *.js site/*.js test/*.js", "test": "node --test" } } diff --git a/examples/demo-integrator/site/app.js b/examples/demo-integrator/site/app.js index 16ee7da..da2af21 100644 --- a/examples/demo-integrator/site/app.js +++ b/examples/demo-integrator/site/app.js @@ -8,12 +8,19 @@ const widget = document.querySelector('countersign-widget'); const PENDING_MS = 10 * 60 * 1000; // the Broker's deadline for a pending offer const REMEMBER = 'harbor-ledger-approval'; const page = { session: null, devices: [], id: null, status: null, requestedAt: null, - revoked: false, renewal: false, justPaired: false, requestShown: false, timer: 0 }; + revoked: false, renewal: false, justPaired: false, requestShown: false, timer: 0, tick: 0 }; const show = msg => { $('message').textContent = msg; }; const fill = (selector, value) => { for (const node of document.querySelectorAll(selector)) node.textContent = value; }; const short = id => String(id).slice(0, 8); const clock = ms => new Date(ms).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }); +const pad = n => String(n).padStart(2, '0'); +// Time left as h:mm:ss, or m:ss under an hour. +function left(ms) { + const s = Math.max(0, Math.ceil(ms / 1000)); + const h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60); + return (h ? h + ':' + pad(m) : m) + ':' + pad(s % 60); +} async function post(path, body = {}) { const res = await fetch('/api/' + path, { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -112,12 +119,24 @@ function render() { forget.href = '/countersign/devices?pairing=' + encodeURIComponent(device.binding.pairing); forget.textContent = 'Forget Companion ' + short(device.binding.pairing) + ' and revoke its grants'; } + renderDeadline(current); const [title, body] = ending(status?.state, host); $('ended-title').textContent = title; $('ended-body').textContent = body; renderDevices(); } +// The grant's approved deadline. The Broker's status says when it ends early. +function renderDeadline(current) { + clearInterval(page.tick); + const until = current === 'active' ? page.status?.expires_at_ms : null; + $('access-ends-row').hidden = !until; + if (!until) return; + const tick = () => { $('access-ends').textContent = left(until - Date.now()) + ' left · until ' + clock(until); }; + tick(); + page.tick = setInterval(tick, 1000); +} + function renderDevices() { const target = new URL(location.href).searchParams.get('pairing'); $('devices').replaceChildren(...page.devices.map(d => { @@ -164,7 +183,7 @@ async function refresh() { async function showJob() { const { session } = page; - const { result } = await post('job'); + const { result, approval } = await post('job'); $('job-eyebrow').textContent = 'Job ' + session.workload + ' · ' + (session.title || session.context); $('job-empty').hidden = !!result; $('job-peer').hidden = !result?.ok; @@ -185,6 +204,16 @@ async function showJob() { } $('job-fingerprint').textContent = result.fingerprint; $('job-subject').textContent = 'Subject: ' + result.subject; + // The backend reads the Workload's current approval from the Broker, which + // names the certificate the user approved; compare it with the one the site + // received, so nobody has to copy a fingerprint. + const approved = approval?.certificate; + $('job-approved').textContent = approved?.sha256 ?? ''; + $('job-approved-subject').textContent = approved?.subject ? 'Subject: ' + approved.subject : ''; + const same = approved?.sha256 === result.fingerprint; + $('no-compare').hidden = !!approved; + $('match').hidden = !approved || !same; + $('mismatch').hidden = !approved || same; } async function load() { @@ -228,13 +257,6 @@ $('pair').onsubmit = perform(async () => { render(); show('Confirm the account in Countersign.'); }); -$('compare').onsubmit = e => { - e.preventDefault(); - const typed = $('selected').value.replace(/[^0-9a-f]/gi, '').toLowerCase(); - const same = typed === $('job-fingerprint').textContent; - $('match').hidden = !same; - $('mismatch').hidden = same || !typed; -}; for (const button of document.querySelectorAll('[data-act=status]')) button.onclick = perform(refresh); document.querySelector('[data-act=renew]').onclick = perform(async () => { const { id } = await post('renew', { id: page.id }); diff --git a/examples/demo-integrator/site/index.html b/examples/demo-integrator/site/index.html index 71e43f1..3691e63 100644 --- a/examples/demo-integrator/site/index.html +++ b/examples/demo-integrator/site/index.html @@ -97,6 +97,7 @@

Access approved

Requested host
Approval ID
+

Your Companion shows the certificate, its SHA-256 fingerprint and when this approval ends.

@@ -150,14 +151,15 @@

Which key signed the handshake?

-
- - - -
+
+ Certificate you approved in the Companion + + +
+

Matching subject names alone can’t identify the key. Compare the full SHA-256 fingerprint.

diff --git a/examples/demo-integrator/site/site.css b/examples/demo-integrator/site/site.css index 4f64104..f991ff9 100644 --- a/examples/demo-integrator/site/site.css +++ b/examples/demo-integrator/site/site.css @@ -59,7 +59,6 @@ button:focus-visible, a:focus-visible, input:focus-visible, textarea:focus-visib .btn.ghost { background: transparent; color: var(--brand); } .btn.danger { background: transparent; border-color: var(--bad-line); color: var(--bad-ink); } .btn:disabled { opacity: .55; cursor: default; } -.small-btn { min-height: 36px; align-self: flex-start; } .card { background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 24px; } .stack { display: flex; flex-direction: column; gap: 16px; } @@ -118,7 +117,6 @@ countersign-widget { --countersign-font: var(--sans); } .pair-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 12px; } .peer { padding: 14px 16px; border-radius: 10px; border: 1px solid var(--line); display: flex; flex-direction: column; gap: 6px; } .fp { font: 400 13px/1.5 var(--mono); word-break: break-all; } -.fp-input { font: 400 13px/1.5 var(--mono); padding: 8px 12px; resize: vertical; word-break: break-all; } .verdict { display: inline-flex; align-items: center; gap: 8px; align-self: flex-start; padding: 8px 12px; border-radius: 8px; border: 1px solid; font-size: 14px; font-weight: 600; } .verdict svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 2.6; stroke-linecap: round; stroke-linejoin: round; } diff --git a/examples/demo-integrator/test/dockerfile.test.js b/examples/demo-integrator/test/dockerfile.test.js new file mode 100644 index 0000000..df4e641 --- /dev/null +++ b/examples/demo-integrator/test/dockerfile.test.js @@ -0,0 +1,23 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const here = fileURLToPath(new URL('..', import.meta.url)); +const read = name => readFileSync(here + name, 'utf8'); + +// The image's servers fail at startup on a local module the Dockerfile leaves out. +test('the image copies every local module the servers import', () => { + const copied = new Set(read('Dockerfile').split('\n').filter(line => line.startsWith('COPY ')) + .flatMap(line => line.split(/\s+/).slice(1, -1)) + .map(path => path.replace('examples/demo-integrator/', ''))); + const seen = new Set(); + const visit = name => { + if (seen.has(name)) return; + seen.add(name); + for (const [, local] of read(name).matchAll(/from '\.\/([^']+)'/g)) visit(local); + }; + visit('integrator.js'); + visit('upstream.js'); + assert.deepEqual([...seen].filter(name => !copied.has(name)), []); +}); diff --git a/examples/demo-integrator/test/job-approval.test.js b/examples/demo-integrator/test/job-approval.test.js new file mode 100644 index 0000000..1af1f17 --- /dev/null +++ b/examples/demo-integrator/test/job-approval.test.js @@ -0,0 +1,78 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { jobApproval } from '../job-approval.js'; + +// A Broker stand-in: `current` is the Workload's current approval, and +// `status` answers for any approval it has seen, as the real one does. +function broker() { + const approvals = new Map(); + const b = { + current: null, + approve(id, sha256) { approvals.set(id, { id, state: 'approved', certificate: { sha256 } }); b.current = id; }, + replace(id) { approvals.get(id).state = 'replaced'; }, + lookups: 0, + async lookup() { b.lookups++; if (!b.current) throw new Error('404'); return approvals.get(b.current); }, + async status(id) { return approvals.get(id); }, + }; + return b; +} +// A job result as read() returns it: the file's text and when it was written. +let written = 0; +const job = fingerprint => ({ text: JSON.stringify({ url: 'https://site.test:9444/', ok: true, fingerprint }), + stamp: ++written }); + +test('a job keeps the approval that was current when its result landed', async () => { + const b = broker(); + let file = null; + const jobs = jobApproval({ read: async () => file, current: b.lookup, status: b.status }); + b.approve('A', 'aaaa'); + file = job('aaaa'); + await jobs.landed(); + b.replace('A'); + b.approve('B', 'bbbb'); // a renewal approved with another certificate + const { approval } = await jobs.forJob(); + assert.equal(approval.id, 'A'); + assert.equal(approval.certificate.sha256, 'aaaa'); + file = job('bbbb'); // the next job runs under B + await jobs.landed(); + assert.equal((await jobs.forJob()).approval.id, 'B'); +}); + +test('a job read before anything noticed it pins the approval current at that read', async () => { + const b = broker(); + b.approve('A', 'aaaa'); + const ran = job('aaaa'); + const jobs = jobApproval({ read: async () => ran, current: b.lookup, status: b.status }); + assert.equal((await jobs.forJob()).approval.id, 'A'); + b.approve('B', 'bbbb'); + assert.equal((await jobs.forJob()).approval.id, 'A'); +}); + +test('no job, or a Broker that could not answer, leaves nothing pinned for good', async () => { + const b = broker(); + let file = null; + const jobs = jobApproval({ read: async () => file, current: b.lookup, status: b.status }); + assert.deepEqual(await jobs.forJob(), { text: null, approval: null }); + assert.equal(b.lookups, 0); + file = job('aaaa'); + await jobs.landed(); // no current approval: the lookup fails + assert.equal((await jobs.forJob()).approval, null); + b.approve('A', 'aaaa'); + assert.equal((await jobs.forJob()).approval.id, 'A', 'the next read tries again'); +}); + +test('a rerun that writes the same result again pins the approval current then', async () => { + const b = broker(); + let file = null; + const jobs = jobApproval({ read: async () => file, current: b.lookup, status: b.status }); + b.approve('A', 'aaaa'); + file = job('bbbb'); // ran under A with another certificate: the fingerprints differ + await jobs.landed(); + b.replace('A'); + b.approve('B', 'bbbb'); // a renewal approves the job's certificate + file = job('bbbb'); // the rerun writes the same text + await jobs.landed(); + const { text, approval } = await jobs.forJob(); + assert.equal(text, file.text); + assert.equal(approval.id, 'B'); +}); diff --git a/examples/demo-integrator/test/page.test.js b/examples/demo-integrator/test/page.test.js new file mode 100644 index 0000000..a045723 --- /dev/null +++ b/examples/demo-integrator/test/page.test.js @@ -0,0 +1,84 @@ +// The demo page in Chromium, its /api routes answered from fixtures (as +// scripts/capture_screenshots.mjs does), with the page clock fixed. +import { after, before, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { chromium } from 'playwright'; +import { contentSecurityPolicy, files } from '../site-files.js'; + +const PORTAL = 'https://portal.example'; +const DEMO_DIR = new URL('../', import.meta.url); +const NOW = Date.parse('2026-11-17T18:39:41-05:00'); +const ID = '85b80155-ac10-487f-a024-5216ec7f8ced'; +const SHA256 = 'c64a4b8b8bcdac1a7ac2bedcd13c520f4abfc07d5765d68df67f56ed0058f00b'; +const OTHER = '778cf24949d2479a234335d05d81d8b9d578b616e63388254c5650c1d0ab5ec6'; +const session = { csrf: 'fixture', vapid: null, user: 'u-42', context: 'close-q3', title: 'Q3 close', + workload: 'export-981', workload_generation: 1, host: 'ledger.partner.example:443' }; +const approved = extra => ({ id: ID, state: 'approved', ready: true, upstream_mtls_accepted: true, + ingress_closed_count: 0, egress_closed_count: 0, ...extra }); + +let browser; +before(async () => { browser = await chromium.launch(); }); +after(async () => { await browser?.close(); }); + +async function open(api, path) { + const context = await browser.newContext({ locale: 'en-US', timezoneId: 'America/New_York' }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + await page.clock.install({ time: NOW }); + const replies = { session: () => session, devices: () => ({ devices: [] }), job: () => ({ result: null }), ...api }; + await page.route(PORTAL + '/**', async route => { + const url = new URL(route.request().url()); + const headers = { 'Content-Security-Policy': contentSecurityPolicy }; + if (url.pathname.startsWith('/api/')) { + const reply = replies[url.pathname.slice(5)]; + if (!reply) return route.fulfill({ status: 404, headers, json: {} }); + return route.fulfill({ headers, json: reply() }); + } + const file = files.get(url.pathname); + if (!file) return route.fulfill({ status: 404, headers }); + await route.fulfill({ headers, contentType: file[1], body: await readFile(new URL(file[0], DEMO_DIR)) }); + }); + await page.goto(PORTAL + path); + return page; +} + +test('the Access approved page counts down to the grant deadline', async () => { + const page = await open({ status: () => approved({ expires_at_ms: NOW + 14 * 60_000 + 30_000 }) }, + '/#countersign=' + ID); + const ends = page.locator('#access-ends'); + await ends.getByText('14:30 left').waitFor(); + assert.match(await ends.innerText(), /6:54 PM/); + await page.clock.runFor(60_000); + await ends.getByText('13:30 left').waitFor(); + await page.context().close(); +}); + +// /api/job as integrator.js answers it: the last job's result and the +// Workload's current approval, which the Broker lookup returns. +const ran = (fingerprint, approval) => () => ({ result: { url: 'https://ledger.partner.example/statements/latest', + ok: true, http_status: 200, fingerprint, subject: 'Demo user', error: null }, approval }); +const certificate = { sha256: SHA256, subject: 'CN=Demo user', issuer: 'CN=Countersign demo client-ca', + not_after_ms: NOW + 86_400_000 }; + +test('the Job result page compares the fingerprints without a paste box', async () => { + for (const [fingerprint, shown, hidden] of [[SHA256, '#match', '#mismatch'], [OTHER, '#mismatch', '#match']]) { + // No approval in this tab: the job's own request started it. + const page = await open({ job: ran(fingerprint, approved({ expires_at_ms: NOW + 60_000, certificate })) }, '/job'); + await page.locator(shown).waitFor(); + assert.equal(await page.locator(hidden).isVisible(), false, fingerprint); + assert.equal(await page.locator('textarea').count(), 0, 'no paste box'); + assert.match(await page.locator('#job-approved').innerText(), /c64a\s*4b8b/); + await page.context().close(); + } +}); + +test('the Job result page says when the job has no approved certificate to compare', async () => { + for (const approval of [null, { id: ID, state: 'pending', ready: false }]) { + const page = await open({ job: ran(SHA256, approval) }, '/job'); + await page.locator('#no-compare').waitFor(); + assert.equal(await page.locator('#match').isVisible(), false); + assert.equal(await page.locator('#mismatch').isVisible(), false); + await page.context().close(); + } +}); diff --git a/scripts/annotate_screenshots.py b/scripts/annotate_screenshots.py index d8f9a48..9a24c8a 100644 --- a/scripts/annotate_screenshots.py +++ b/scripts/annotate_screenshots.py @@ -85,12 +85,13 @@ ]), "access-active.png": ("access-active.png", [ ("progress", "Status from the Broker", "above-end"), + ("ends", "Grant deadline from the Broker", "right"), ]), "access-ended.png": ("access-ended.png", [ ("again", "Starts a fresh approval", "right"), ]), "job-result.png": ("job-result.png", [ - ("match", "Same SHA-256 as the approval", "right"), + ("match", "Same SHA-256 as the approval, from the Broker", "right"), ]), } diff --git a/scripts/capture_screenshots.mjs b/scripts/capture_screenshots.mjs index efab8e7..3fd3e51 100644 --- a/scripts/capture_screenshots.mjs +++ b/scripts/capture_screenshots.mjs @@ -162,6 +162,13 @@ async function portal(browser, colorScheme, api) { return page; } +// An approved status as the Broker returns it: the grant's deadline and the +// certificate the user approved. +const approvedStatus = () => ({ id: approvalId, state: 'approved', ready: true, upstream_mtls_accepted: true, + ingress_closed_count: 0, egress_closed_count: 0, expires_at_ms: NOW.getTime() + 3570000, + certificate: { sha256: fingerprints.selected, subject: 'CN=Demo user', issuer: 'CN=Countersign demo client-ca', + not_after_ms: Date.parse('2026-11-19T18:39:30-05:00') } }); + function demoApi(extra = {}) { return { session: () => ({ csrf: 'fixture', vapid: null, ...job }), @@ -342,18 +349,15 @@ const portalShots = { } }); }, async 'access-active'(browser, scheme, name) { - const page = await portal(browser, scheme, demoApi({ - status: () => ({ id: approvalId, state: 'approved', ready: true, upstream_mtls_accepted: true, - ingress_closed_count: 0, egress_closed_count: 0 }), - })); + const page = await portal(browser, scheme, demoApi({ status: approvedStatus })); await page.goto(PORTAL + '/#countersign=' + approvalId); await page.getByRole('heading', { name: 'Access approved' }).waitFor(); - await capture(page, name, { clip: content, selectors: { progress: '.progress li' } }); + await page.locator('#access-ends').getByText('59:30 left').waitFor(); + await capture(page, name, { clip: content, selectors: { progress: '.progress li', ends: '#access-ends-row' } }); }, async 'access-ended'(browser, scheme, name) { const page = await portal(browser, scheme, demoApi({ - status: () => ({ id: approvalId, state: 'approved', ready: true, upstream_mtls_accepted: true, - ingress_closed_count: 0, egress_closed_count: 0 }), + status: approvedStatus, revoke: () => null, })); await page.goto(PORTAL + '/#countersign=' + approvalId); @@ -364,11 +368,9 @@ const portalShots = { async 'job-result'(browser, scheme, name) { const page = await portal(browser, scheme, demoApi({ job: () => ({ result: { url: 'https://ledger.partner.example/statements/latest', ok: true, http_status: 200, - fingerprint: fingerprints.selected, subject: 'Demo user', error: null } }), + fingerprint: fingerprints.selected, subject: 'Demo user', error: null }, approval: approvedStatus() }), })); await page.goto(PORTAL + '/job'); - await page.getByLabel('SHA-256 you selected in the Companion').fill(fingerprints.selected); - await page.getByRole('button', { name: 'Compare' }).click(); await page.locator('#match').waitFor(); await capture(page, name, { clip: content, selectors: { compare: '.pair-cards', match: '#match' } }); },