Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions crates/countersign-broker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
5 changes: 4 additions & 1 deletion crates/countersign-broker/src/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
87 changes: 77 additions & 10 deletions crates/countersign-broker/src/service/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,24 +161,91 @@ pub(super) async fn status(
Json(req): Json<Owned>,
) -> Result<Json<Value>> {
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<Value> {
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<String>>(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<String>>(1)?,r.get::<_,bool>(2)?,r.get::<_,i64>(3)?,r.get::<_,i64>(4)?,
r.get::<_,Option<i64>>(5)?,r.get::<_,Option<String>>(6)?,
(r.get::<_,Option<String>>(7)?,r.get::<_,Option<String>>(8)?,r.get::<_,Option<i64>>(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<Service>,
h: HeaderMap,
Json(req): Json<Lookup>,
) -> Result<Json<Value>> {
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<Service>,
Expand Down
3 changes: 3 additions & 0 deletions crates/countersign-broker/src/service/companion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
Expand Down
1 change: 1 addition & 0 deletions crates/countersign-broker/src/service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
23 changes: 20 additions & 3 deletions crates/countersign-broker/src/sqlite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
}
Expand Down Expand Up @@ -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"
Expand Down
6 changes: 6 additions & 0 deletions crates/countersign-broker/src/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self> {
Expand Down Expand Up @@ -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(),
})
}
}
Expand Down
44 changes: 44 additions & 0 deletions crates/countersign-broker/tests/approvals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
}
Expand Down Expand Up @@ -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(),
};
Expand Down Expand Up @@ -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<String> = db
.prepare("SELECT name FROM pragma_table_info('approved_grant')")
.unwrap()
.query_map([], |r| r.get(0))
.unwrap()
.collect::<rusqlite::Result<_>>()
.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");
}
Loading
Loading