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
89 changes: 72 additions & 17 deletions apps/auth-service/src/audit/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -26,6 +27,24 @@ pub(crate) struct AuditApplication {
database: Database,
/// Verifies the latest checkpoint before it is served.
keys: Arc<AuditKeys>,
/// 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<Mutex<Option<LatestCheckpoint>>>,
}

/// 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<String>,
}

/// The query of [`audit::CHECKPOINTS`].
Expand Down Expand Up @@ -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<AuditKeys>) -> Self {
Self { database, keys }
pub(crate) fn new(database: Database, keys: Arc<AuditKeys>) -> Self {
Self {
database,
keys,
latest: Arc::default(),
}
}

/// Returns the checkpoint routes with this application as state.
Expand All @@ -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<Self>) -> Result<Response, ApiError> {
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<bool, DatabaseError> {
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<Option<String>, 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<Self>,
Expand Down
69 changes: 67 additions & 2 deletions apps/auth-service/src/audit/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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");
Expand Down Expand Up @@ -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(&note)
.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.
Expand Down
15 changes: 15 additions & 0 deletions apps/auth-service/src/audit/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,21 @@ pub(crate) struct TrustedCheckpoint {
pub(crate) untrusted: Vec<Checkpoint>,
}

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;
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions crates/database/src/repositories/audit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u64, DatabaseError> {
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.
///
Expand Down
5 changes: 4 additions & 1 deletion docs/dev/security/audit-history.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<position>`: 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`.
Expand Down
Loading