diff --git a/apps/auth-service/src/audit/routes.rs b/apps/auth-service/src/audit/routes.rs index bc4ca72c4..c25959615 100644 --- a/apps/auth-service/src/audit/routes.rs +++ b/apps/auth-service/src/audit/routes.rs @@ -14,9 +14,10 @@ use axum::{ routing::get, }; use chrono::{DateTime, Utc}; -use piquel_repository::{ChainLink, Checkpoint, Database}; +use piquel_repository::{ChainLink, Checkpoint, Database, DatabaseError}; use serde::{Deserialize, Serialize}; use std::sync::Arc; +use tokio::sync::Mutex; /// Public, cacheable checkpoint routes. Checkpoints hold only positions and /// hashes, so serving them reveals nothing but how many events were recorded. @@ -26,6 +27,24 @@ pub(crate) struct AuditApplication { database: Database, /// Verifies the latest checkpoint before it is served. keys: Arc, + /// The last checkpoint [`Self::latest`] found, reused until another is + /// stored where it could change the answer. Stored checkpoints never change, + /// so only a new one can. + latest: Arc>>, +} + +/// The newest checkpoint that verified, and what it was found among. +#[derive(Clone)] +struct LatestCheckpoint { + /// The lowest position the search read; see + /// [`TrustedCheckpoint::floor`](super::TrustedCheckpoint::floor). + floor: u64, + /// How many checkpoints were stored at or after `floor`. Someone with auth's + /// database role can add one at any position, even above one still being + /// signed, so only a count tells that another was stored. + stored: u64, + /// The signed note of the newest that verifies, if any does. + note: Option, } /// The query of [`audit::CHECKPOINTS`]. @@ -75,8 +94,12 @@ impl AuditApplication { /// Builds the routes over `database`, serving only a latest checkpoint `keys` /// verify. - pub(crate) const fn new(database: Database, keys: Arc) -> Self { - Self { database, keys } + pub(crate) fn new(database: Database, keys: Arc) -> Self { + Self { + database, + keys, + latest: Arc::default(), + } } /// Returns the checkpoint routes with this application as state. @@ -88,27 +111,59 @@ impl AuditApplication { } /// The signed note of the newest checkpoint that verifies, as `text/plain`. - /// Newer ones that do not are never served; `audit verify` reports them. + /// Newer ones that do not are never served; `audit verify` reports them. A + /// request counts the checkpoints stored since the last answer was found, + /// and searches again only if another was stored. async fn latest(State(app): State) -> Result { - let checkpoint = app - .keys - .newest_trusted(&mut app.database.audit()) - .await - .map_err(ApiError::internal)? - .trusted - .ok_or_else(|| { - ApiError::not_found("no checkpoint that verifies has been signed yet") - })?; + let found = app.latest.lock().await.clone(); + let note = match found { + Some(found) if app.is_current(&found).await? => found.note, + _ => app.find_latest().await?, + } + .ok_or_else(|| ApiError::not_found("no checkpoint that verifies has been signed yet"))?; Ok(Cached( Self::CACHE, - ( - [(header::CONTENT_TYPE, "text/plain; charset=utf-8")], - checkpoint.note, - ), + ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], note), ) .into_response()) } + /// Whether no checkpoint was stored where it could change `found`. + async fn is_current(&self, found: &LatestCheckpoint) -> Result { + let stored = self.database.audit().count_checkpoints(found.floor).await?; + Ok(stored == found.stored) + } + + /// Finds the newest checkpoint that verifies, and remembers it. One request + /// searches at a time; those that waited reuse its answer. + async fn find_latest(&self) -> Result, ApiError> { + let mut latest = self.latest.lock().await; + if let Some(found) = latest.as_ref() + && self.is_current(found).await? + { + return Ok(found.note.clone()); + } + // One snapshot, so a checkpoint stored during the search is counted only + // if the search saw it. + let mut tx = self.database.begin().await?; + tx.audit().read_snapshot().await?; + let search = self + .keys + .newest_trusted(&mut tx.audit()) + .await + .map_err(ApiError::internal)?; + let floor = search.floor(); + let stored = tx.audit().count_checkpoints(floor).await?; + tx.commit().await?; + let note = search.trusted.map(|checkpoint| checkpoint.note); + *latest = Some(LatestCheckpoint { + floor, + stored, + note: note.clone(), + }); + Ok(note) + } + /// Up to 100 checkpoints after `after`, oldest first. An empty page is the end. async fn list( State(app): State, diff --git a/apps/auth-service/src/audit/tests.rs b/apps/auth-service/src/audit/tests.rs index 67b23886b..25950818a 100644 --- a/apps/auth-service/src/audit/tests.rs +++ b/apps/auth-service/src/audit/tests.rs @@ -183,6 +183,13 @@ impl Fixture { /// key and dated `ahead` of now, as someone with auth's database role but not /// its audit key can: a trigger allows up to a minute. async fn forge_checkpoint(&self, position: u64, ahead: TimeDelta) { + let other = NoteKey::generate("auth.example/audit").expect("another key"); + self.store_checkpoint(&other, position, ahead).await; + } + + /// Stores a checkpoint of the stored head at `position`, signed by `key` and + /// dated `ahead` of now. + async fn store_checkpoint(&self, key: &NoteKey, position: u64, ahead: TimeDelta) { let head = self .database .audit() @@ -197,14 +204,13 @@ impl Fixture { head, time, }; - let other = NoteKey::generate("auth.example/audit").expect("another key"); self.database .audit() .insert_checkpoint(&Checkpoint { position, head: head.hash, created_at: time, - note: other.sign(&text.render()).expect("forged note"), + note: key.sign(&text.render()).expect("signed note"), }) .await .expect("a checkpoint the database cannot check"); @@ -746,6 +752,65 @@ async fn forged_checkpoints_are_passed_over_and_not_served() { ); } +/// The latest checkpoint is verified once per checkpoint stored: a replica keeps +/// serving the note it verified until another checkpoint is stored, at any +/// position, even below a forged one, and then serves the newest that verifies. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn the_latest_checkpoint_is_verified_once_per_checkpoint() { + use axum::{ + body::{Body, to_bytes}, + http::Request, + }; + use tower::ServiceExt; + + let mut fixture = Fixture::sealed_six().await; + let router = fixture.router().await; + let keys = Arc::clone(&fixture.keys); + let latest = async |router: &axum::Router| { + let response = router + .clone() + .oneshot( + Request::get("/audit/checkpoints/latest") + .body(Body::empty()) + .expect("request"), + ) + .await + .expect("response"); + let body = to_bytes(response.into_body(), usize::MAX) + .await + .expect("body"); + let note = String::from_utf8(body.to_vec()).expect("UTF-8"); + let text = keys + .verifiers + .open(¬e) + .expect("a signed note") + .to_owned(); + (note, text) + }; + assert!(latest(&router).await.1.contains("\nposition 6\n")); + // A forged checkpoint holds the top position while a genuine one below it is + // still being signed; once that one is stored, it is served. + fixture.record(2).await; + let mut lock = fixture.lock().await; + fixture.seal_with(&mut lock).await; + lock.release().await.expect("release"); + fixture.forge_checkpoint(8, TimeDelta::zero()).await; + assert!(latest(&router).await.1.contains("\nposition 6\n")); + let key = fixture.audit.key.clone(); + fixture.store_checkpoint(&key, 7, TimeDelta::zero()).await; + let (verified, text) = latest(&router).await; + assert!(text.contains("\nposition 7\n"), "{text}"); + // No checkpoint was stored since, so the replica does not read it again, and + // a fresh one finds the one before. + fixture + .tamper(Tamper::EditCheckpointNote(7, "forged".into())) + .await; + assert_eq!(latest(&router).await.0, verified); + let text = latest(&fixture.router().await).await.1; + assert!(text.contains("\nposition 6\n"), "{text}"); +} + /// A forged checkpoint over a tampered event, as someone with auth's database /// role can seal one, is never built on: the sealer recomputes from the newest /// checkpoint that verifies and refuses to sign the broken chain. diff --git a/apps/auth-service/src/audit/verify.rs b/apps/auth-service/src/audit/verify.rs index 970399d21..ef9c94590 100644 --- a/apps/auth-service/src/audit/verify.rs +++ b/apps/auth-service/src/audit/verify.rs @@ -32,6 +32,21 @@ pub(crate) struct TrustedCheckpoint { pub(crate) untrusted: Vec, } +impl TrustedCheckpoint { + /// The lowest position the search read: the trusted checkpoint's, or the + /// oldest it passed over once it stopped at its limit, or 0 when it read every + /// checkpoint. No checkpoint stored below it can change what it finds. + pub(crate) fn floor(&self) -> u64 { + match (&self.trusted, self.untrusted.last()) { + (Some(trusted), _) => trusted.position, + (None, Some(oldest)) if self.untrusted.len() == AuditKeys::UNTRUSTED_LIMIT => { + oldest.position + } + (None, _) => 0, + } + } +} + impl AuditKeys { /// The most checkpoints that do not verify [`Self::newest_trusted`] passes over. const UNTRUSTED_LIMIT: usize = 1_000; diff --git a/crates/database/.sqlx/query-f698134e33daba0560c63590843ab964b14d779d33dd1b16e626cd6bb9b7c113.json b/crates/database/.sqlx/query-f698134e33daba0560c63590843ab964b14d779d33dd1b16e626cd6bb9b7c113.json new file mode 100644 index 000000000..60c9425a6 --- /dev/null +++ b/crates/database/.sqlx/query-f698134e33daba0560c63590843ab964b14d779d33dd1b16e626cd6bb9b7c113.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT count(*) AS \"count!: Unsigned\" FROM audit_checkpoints\n WHERE position >= $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count!: Unsigned", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [ + null + ] + }, + "hash": "f698134e33daba0560c63590843ab964b14d779d33dd1b16e626cd6bb9b7c113" +} diff --git a/crates/database/src/repositories/audit/mod.rs b/crates/database/src/repositories/audit/mod.rs index 9b2a8fac7..0a404a7ad 100644 --- a/crates/database/src/repositories/audit/mod.rs +++ b/crates/database/src/repositories/audit/mod.rs @@ -268,6 +268,26 @@ impl AuditRepository<'_> { .map(Into::into) } + /// Counts the stored checkpoints at or after position `from`. No checkpoint + /// is ever deleted or changed, so the count changes exactly when one is added + /// there. + /// + /// # Errors + /// + /// Returns [`DatabaseError`] if the query fails or `from` is not a position. + pub async fn count_checkpoints(&mut self, from: u64) -> Result { + run!( + self, + fetch_one, + sqlx::query_scalar!( + r#"SELECT count(*) AS "count!: Unsigned" FROM audit_checkpoints + WHERE position >= $1"#, + Unsigned::bind(from)?, + ) + ) + .map(Into::into) + } + /// Whether this connection's role may delete events, as pruning must: the /// schema owner may, and auth's runtime role may not. /// diff --git a/docs/dev/security/audit-history.md b/docs/dev/security/audit-history.md index 145406500..fa0a7db2d 100644 --- a/docs/dev/security/audit-history.md +++ b/docs/dev/security/audit-history.md @@ -142,7 +142,10 @@ hashes: - `GET /audit/checkpoints/latest`: the signed note of the newest checkpoint that verifies, as the sealer checks them, as `text/plain`. A newer one that does - not is never served as the latest. + not is never served as the latest. Each replica checks signatures again only + when another checkpoint is stored at or above the oldest one its last search + read, whatever its position: stored checkpoints never change, so nothing else + can change the answer. - `GET /audit/checkpoints?after=`: up to 100 checkpoints after a position, oldest first, as JSON `{position, hash, time, note}`, every stored one, for readers to verify. A position past 2^63 − 1 is refused with `400`.