From a73bafb2f4ef3c6e4632b3e6460bbe8b59283fc6 Mon Sep 17 00:00:00 2001 From: piquel Date: Sat, 7 Nov 2026 12:44:55 +0100 Subject: [PATCH 1/3] perf(auth): /audit/checkpoints/latest checks signatures once per stored checkpoint, not on every request --- apps/auth-service/src/audit/routes.rs | 70 ++++++++++++++++++++------- apps/auth-service/src/audit/tests.rs | 54 +++++++++++++++++++++ docs/dev/security/audit-history.md | 4 +- 3 files changed, 110 insertions(+), 18 deletions(-) diff --git a/apps/auth-service/src/audit/routes.rs b/apps/auth-service/src/audit/routes.rs index bc4ca72c4..4773f6bef 100644 --- a/apps/auth-service/src/audit/routes.rs +++ b/apps/auth-service/src/audit/routes.rs @@ -16,7 +16,7 @@ use axum::{ use chrono::{DateTime, Utc}; use piquel_repository::{ChainLink, Checkpoint, Database}; use serde::{Deserialize, Serialize}; -use std::sync::Arc; +use std::sync::{Arc, Mutex, PoisonError}; /// Public, cacheable checkpoint routes. Checkpoints hold only positions and /// hashes, so serving them reveals nothing but how many events were recorded. @@ -26,6 +26,19 @@ 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. Stored checkpoints never change, so only a new one can change + /// which is the newest that verifies. + latest: Arc>>, +} + +/// The newest checkpoint that verified, as of the newest one stored. +#[derive(Clone)] +struct LatestCheckpoint { + /// The position of the newest checkpoint stored when it was found. + newest: u64, + /// The signed note of the newest that verifies, if any does. + note: Option, } /// The query of [`audit::CHECKPOINTS`]. @@ -75,8 +88,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,23 +105,42 @@ 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. Each + /// request reads only the newest stored position, and checks signatures again + /// only once another checkpoint 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 mut audit = app.database.audit(); + let newest = audit + .newest_checkpoints(None, 1) + .await? + .first() + .map(|checkpoint| checkpoint.position); + let remembered = || app.latest.lock().unwrap_or_else(PoisonError::into_inner); + let found = remembered() + .clone() + .filter(|latest| Some(latest.newest) == newest); + let note = match (found, newest) { + (Some(latest), _) => latest.note, + (None, None) => None, + (None, Some(newest)) => { + let note = app + .keys + .newest_trusted(&mut audit) + .await + .map_err(ApiError::internal)? + .trusted + .map(|checkpoint| checkpoint.note); + *remembered() = Some(LatestCheckpoint { + newest, + note: note.clone(), + }); + note + } + } + .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()) } diff --git a/apps/auth-service/src/audit/tests.rs b/apps/auth-service/src/audit/tests.rs index 67b23886b..876c47d37 100644 --- a/apps/auth-service/src/audit/tests.rs +++ b/apps/auth-service/src/audit/tests.rs @@ -746,6 +746,60 @@ 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, 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 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"); + String::from_utf8(body.to_vec()).expect("UTF-8") + }; + let verified = latest(&router).await; + assert!( + fixture + .keys + .verifiers + .open(&verified) + .expect("a signed note") + .contains("\nposition 6\n") + ); + // 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(6, "forged".into())) + .await; + assert_eq!(latest(&router).await, verified); + let fresh = latest(&fixture.router().await).await; + let text = fixture.keys.verifiers.open(&fresh).expect("a signed note"); + assert!(text.contains("\nposition 3\n"), "{text}"); + fixture.record(1).await; + fixture.seal().await; + let text = latest(&router).await; + let text = fixture.keys.verifiers.open(&text).expect("a signed note"); + assert!(text.contains("\nposition 7\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/docs/dev/security/audit-history.md b/docs/dev/security/audit-history.md index 145406500..ba23be67b 100644 --- a/docs/dev/security/audit-history.md +++ b/docs/dev/security/audit-history.md @@ -142,7 +142,9 @@ 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 only once + per checkpoint stored: stored checkpoints never change, so it reuses the note + it found until another is stored. - `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`. From ea810eab747df567c1bbf0f253902c71a9eff37c Mon Sep 17 00:00:00 2001 From: piquel Date: Sat, 7 Nov 2026 13:12:14 +0100 Subject: [PATCH 2/3] fix(auth): the latest checkpoint is found again whenever one is stored at any position, and once for concurrent requests --- apps/auth-service/src/audit/routes.rs | 48 ++++++++-------- apps/auth-service/src/audit/tests.rs | 57 +++++++++++-------- ...2fc0624ff45c22116b521b97eb5349820a4c0.json | 20 +++++++ crates/database/src/repositories/audit/mod.rs | 15 +++++ docs/dev/security/audit-history.md | 2 +- 5 files changed, 93 insertions(+), 49 deletions(-) create mode 100644 crates/database/.sqlx/query-b39b215e96281da37898c31ebb92fc0624ff45c22116b521b97eb5349820a4c0.json diff --git a/apps/auth-service/src/audit/routes.rs b/apps/auth-service/src/audit/routes.rs index 4773f6bef..7fed90df9 100644 --- a/apps/auth-service/src/audit/routes.rs +++ b/apps/auth-service/src/audit/routes.rs @@ -16,7 +16,8 @@ use axum::{ use chrono::{DateTime, Utc}; use piquel_repository::{ChainLink, Checkpoint, Database}; use serde::{Deserialize, Serialize}; -use std::sync::{Arc, Mutex, PoisonError}; +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. @@ -28,15 +29,17 @@ pub(crate) struct AuditApplication { keys: Arc, /// The last checkpoint [`Self::latest`] found, reused until another is /// stored. Stored checkpoints never change, so only a new one can change - /// which is the newest that verifies. + /// which is the newest that verifies. Requests take turns with it, so + /// signatures are checked once per checkpoint stored. latest: Arc>>, } -/// The newest checkpoint that verified, as of the newest one stored. -#[derive(Clone)] +/// The newest checkpoint that verified, as of a number of stored checkpoints. struct LatestCheckpoint { - /// The position of the newest checkpoint stored when it was found. - newest: u64, + /// How many checkpoints were stored when it was found. Someone with auth's + /// database role can add one at any position, even above one still being + /// signed, so only the count tells that another was stored. + stored: u64, /// The signed note of the newest that verifies, if any does. note: Option, } @@ -106,23 +109,15 @@ 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. Each - /// request reads only the newest stored position, and checks signatures again - /// only once another checkpoint was stored. + /// request counts the stored checkpoints, and checks signatures again only + /// once another was stored. async fn latest(State(app): State) -> Result { let mut audit = app.database.audit(); - let newest = audit - .newest_checkpoints(None, 1) - .await? - .first() - .map(|checkpoint| checkpoint.position); - let remembered = || app.latest.lock().unwrap_or_else(PoisonError::into_inner); - let found = remembered() - .clone() - .filter(|latest| Some(latest.newest) == newest); - let note = match (found, newest) { - (Some(latest), _) => latest.note, - (None, None) => None, - (None, Some(newest)) => { + let mut latest = app.latest.lock().await; + let stored = audit.checkpoint_count().await?; + let note = match latest.as_ref() { + Some(found) if found.stored == stored => found.note.clone(), + _ => { let note = app .keys .newest_trusted(&mut audit) @@ -130,14 +125,17 @@ impl AuditApplication { .map_err(ApiError::internal)? .trusted .map(|checkpoint| checkpoint.note); - *remembered() = Some(LatestCheckpoint { - newest, + *latest = Some(LatestCheckpoint { + stored, note: note.clone(), }); note } - } - .ok_or_else(|| ApiError::not_found("no checkpoint that verifies has been signed yet"))?; + }; + drop(latest); + let note = note.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")], note), diff --git a/apps/auth-service/src/audit/tests.rs b/apps/auth-service/src/audit/tests.rs index 876c47d37..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"); @@ -747,8 +753,8 @@ 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, and then -/// serves the newest that verifies. +/// 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() { @@ -760,6 +766,7 @@ async fn the_latest_checkpoint_is_verified_once_per_checkpoint() { 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() @@ -773,31 +780,35 @@ async fn the_latest_checkpoint_is_verified_once_per_checkpoint() { let body = to_bytes(response.into_body(), usize::MAX) .await .expect("body"); - String::from_utf8(body.to_vec()).expect("UTF-8") - }; - let verified = latest(&router).await; - assert!( - fixture - .keys + let note = String::from_utf8(body.to_vec()).expect("UTF-8"); + let text = keys .verifiers - .open(&verified) + .open(¬e) .expect("a signed note") - .contains("\nposition 6\n") - ); + .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(6, "forged".into())) + .tamper(Tamper::EditCheckpointNote(7, "forged".into())) .await; - assert_eq!(latest(&router).await, verified); - let fresh = latest(&fixture.router().await).await; - let text = fixture.keys.verifiers.open(&fresh).expect("a signed note"); - assert!(text.contains("\nposition 3\n"), "{text}"); - fixture.record(1).await; - fixture.seal().await; - let text = latest(&router).await; - let text = fixture.keys.verifiers.open(&text).expect("a signed note"); - assert!(text.contains("\nposition 7\n"), "{text}"); + 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 diff --git a/crates/database/.sqlx/query-b39b215e96281da37898c31ebb92fc0624ff45c22116b521b97eb5349820a4c0.json b/crates/database/.sqlx/query-b39b215e96281da37898c31ebb92fc0624ff45c22116b521b97eb5349820a4c0.json new file mode 100644 index 000000000..80e961d24 --- /dev/null +++ b/crates/database/.sqlx/query-b39b215e96281da37898c31ebb92fc0624ff45c22116b521b97eb5349820a4c0.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT count(*) AS \"count!: Unsigned\" FROM audit_checkpoints", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count!: Unsigned", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null + ] + }, + "hash": "b39b215e96281da37898c31ebb92fc0624ff45c22116b521b97eb5349820a4c0" +} diff --git a/crates/database/src/repositories/audit/mod.rs b/crates/database/src/repositories/audit/mod.rs index 9b2a8fac7..4ac8e0f32 100644 --- a/crates/database/src/repositories/audit/mod.rs +++ b/crates/database/src/repositories/audit/mod.rs @@ -268,6 +268,21 @@ impl AuditRepository<'_> { .map(Into::into) } + /// Counts the stored checkpoints. No checkpoint is ever deleted or changed, so + /// the count changes exactly when one is added, at whatever position. + /// + /// # Errors + /// + /// Returns [`DatabaseError`] if the query fails. + pub async fn checkpoint_count(&mut self) -> Result { + run!( + self, + fetch_one, + sqlx::query_scalar!(r#"SELECT count(*) AS "count!: Unsigned" FROM audit_checkpoints"#) + ) + .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 ba23be67b..dd19cc3e3 100644 --- a/docs/dev/security/audit-history.md +++ b/docs/dev/security/audit-history.md @@ -144,7 +144,7 @@ hashes: verifies, as the sealer checks them, as `text/plain`. A newer one that does not is never served as the latest. Each replica checks signatures only once per checkpoint stored: stored checkpoints never change, so it reuses the note - it found until another is stored. + it found until the number stored changes, whatever position a new one has. - `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`. From d028e11f93160ea66f888bb72bf3078b28e390c9 Mon Sep 17 00:00:00 2001 From: piquel Date: Sat, 7 Nov 2026 13:23:14 +0100 Subject: [PATCH 3/3] perf(auth): the latest checkpoint's cache counts only checkpoints above its search, and hits take no lock --- apps/auth-service/src/audit/routes.rs | 89 ++++++++++++------- apps/auth-service/src/audit/verify.rs | 15 ++++ ...b964b14d779d33dd1b16e626cd6bb9b7c113.json} | 8 +- crates/database/src/repositories/audit/mod.rs | 15 ++-- docs/dev/security/audit-history.md | 7 +- 5 files changed, 89 insertions(+), 45 deletions(-) rename crates/database/.sqlx/{query-b39b215e96281da37898c31ebb92fc0624ff45c22116b521b97eb5349820a4c0.json => query-f698134e33daba0560c63590843ab964b14d779d33dd1b16e626cd6bb9b7c113.json} (64%) diff --git a/apps/auth-service/src/audit/routes.rs b/apps/auth-service/src/audit/routes.rs index 7fed90df9..c25959615 100644 --- a/apps/auth-service/src/audit/routes.rs +++ b/apps/auth-service/src/audit/routes.rs @@ -14,7 +14,7 @@ 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; @@ -28,17 +28,20 @@ pub(crate) struct AuditApplication { /// Verifies the latest checkpoint before it is served. keys: Arc, /// The last checkpoint [`Self::latest`] found, reused until another is - /// stored. Stored checkpoints never change, so only a new one can change - /// which is the newest that verifies. Requests take turns with it, so - /// signatures are checked once per checkpoint stored. + /// stored where it could change the answer. Stored checkpoints never change, + /// so only a new one can. latest: Arc>>, } -/// The newest checkpoint that verified, as of a number of stored checkpoints. +/// The newest checkpoint that verified, and what it was found among. +#[derive(Clone)] struct LatestCheckpoint { - /// How many checkpoints were stored when it was found. Someone with auth's + /// 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 the count tells that another was stored. + /// 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, @@ -108,34 +111,16 @@ 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. Each - /// request counts the stored checkpoints, and checks signatures again only - /// once another was stored. + /// 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 mut audit = app.database.audit(); - let mut latest = app.latest.lock().await; - let stored = audit.checkpoint_count().await?; - let note = match latest.as_ref() { - Some(found) if found.stored == stored => found.note.clone(), - _ => { - let note = app - .keys - .newest_trusted(&mut audit) - .await - .map_err(ApiError::internal)? - .trusted - .map(|checkpoint| checkpoint.note); - *latest = Some(LatestCheckpoint { - stored, - note: note.clone(), - }); - note - } - }; - drop(latest); - let note = note.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")], note), @@ -143,6 +128,42 @@ impl AuditApplication { .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/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-b39b215e96281da37898c31ebb92fc0624ff45c22116b521b97eb5349820a4c0.json b/crates/database/.sqlx/query-f698134e33daba0560c63590843ab964b14d779d33dd1b16e626cd6bb9b7c113.json similarity index 64% rename from crates/database/.sqlx/query-b39b215e96281da37898c31ebb92fc0624ff45c22116b521b97eb5349820a4c0.json rename to crates/database/.sqlx/query-f698134e33daba0560c63590843ab964b14d779d33dd1b16e626cd6bb9b7c113.json index 80e961d24..60c9425a6 100644 --- a/crates/database/.sqlx/query-b39b215e96281da37898c31ebb92fc0624ff45c22116b521b97eb5349820a4c0.json +++ b/crates/database/.sqlx/query-f698134e33daba0560c63590843ab964b14d779d33dd1b16e626cd6bb9b7c113.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT count(*) AS \"count!: Unsigned\" FROM audit_checkpoints", + "query": "SELECT count(*) AS \"count!: Unsigned\" FROM audit_checkpoints\n WHERE position >= $1", "describe": { "columns": [ { @@ -10,11 +10,13 @@ } ], "parameters": { - "Left": [] + "Left": [ + "Int8" + ] }, "nullable": [ null ] }, - "hash": "b39b215e96281da37898c31ebb92fc0624ff45c22116b521b97eb5349820a4c0" + "hash": "f698134e33daba0560c63590843ab964b14d779d33dd1b16e626cd6bb9b7c113" } diff --git a/crates/database/src/repositories/audit/mod.rs b/crates/database/src/repositories/audit/mod.rs index 4ac8e0f32..0a404a7ad 100644 --- a/crates/database/src/repositories/audit/mod.rs +++ b/crates/database/src/repositories/audit/mod.rs @@ -268,17 +268,22 @@ impl AuditRepository<'_> { .map(Into::into) } - /// Counts the stored checkpoints. No checkpoint is ever deleted or changed, so - /// the count changes exactly when one is added, at whatever position. + /// 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. - pub async fn checkpoint_count(&mut self) -> Result { + /// 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"#) + sqlx::query_scalar!( + r#"SELECT count(*) AS "count!: Unsigned" FROM audit_checkpoints + WHERE position >= $1"#, + Unsigned::bind(from)?, + ) ) .map(Into::into) } diff --git a/docs/dev/security/audit-history.md b/docs/dev/security/audit-history.md index dd19cc3e3..fa0a7db2d 100644 --- a/docs/dev/security/audit-history.md +++ b/docs/dev/security/audit-history.md @@ -142,9 +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. Each replica checks signatures only once - per checkpoint stored: stored checkpoints never change, so it reuses the note - it found until the number stored changes, whatever position a new one has. + 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`.