Skip to content

Commit 19086fd

Browse files
committed
feat(auth): a gauge says whether the newest audit verification found the chain broken
After each run, the verifier sets piquel.auth.audit.broken from the newest recorded verification, whoever made it: 1 when broken, 0 when intact, so monitoring can alert on it beside the in-app alert. The purge job's way of reporting a count after each run, while it is fresh, is now JobCount, which both share.
1 parent 527eb8f commit 19086fd

9 files changed

Lines changed: 165 additions & 69 deletions

File tree

‎apps/auth-service/src/audit/tests.rs‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use piquel_common::{
1717
use piquel_crypto::NoteKey;
1818
use piquel_repository::{
1919
Checkpoint, DatabaseTransaction, EventFilter, ExclusiveConnection, LockKey, Tamper,
20+
Verifications,
2021
};
2122
use std::{sync::Arc, time::Duration};
2223

@@ -612,24 +613,34 @@ async fn the_audit_page_shows_the_newest_recorded_verification() {
612613
}
613614

614615
/// The verifier job verifies the chain when no verification was recorded lately,
615-
/// and records what it found as itself, which then holds off its next pass.
616+
/// one with keys given with `--key` aside, and records what it found as itself,
617+
/// which then holds off its next pass.
616618
#[tokio::test]
617619
#[ignore = "requires TEST_DATABASE_URL"]
618620
async fn the_verifier_verifies_when_no_verification_is_recent() {
619621
let fixture = Fixture::sealed_six().await;
620-
let verifier = Verifier::new((*fixture.keys).clone());
622+
// The server's own keys: what it records with them holds off its next pass.
623+
let keys = AuditKeys::for_server(&Fixture::origin(), fixture.audit.verifier()).expect("keys");
624+
let verifier = Verifier::new(keys);
621625
let mut lock = fixture
622626
.database
623627
.try_exclusive(LockKey::AuditVerification)
624628
.await
625629
.expect("lock")
626630
.expect("no other test verifies");
627-
let intact = fixture.verify().await;
631+
AdminService::new(fixture.database.clone(), false)
632+
.verify_audit_chain(&operator(), &fixture.keys)
633+
.await
634+
.expect("a verification with given keys");
635+
let intact = AuditVerification {
636+
keys: VerificationKeys::Uncommitted,
637+
..fixture.verify().await
638+
};
628639
assert_eq!(verifier.pass(&mut lock).await.expect("pass"), Some(intact));
629640
let newest = fixture
630641
.database
631642
.events()
632-
.newest_audit_verification()
643+
.newest_audit_verification(Verifications::Any)
633644
.await
634645
.expect("newest")
635646
.expect("recorded");

‎apps/auth-service/src/audit/verifier.rs‎

Lines changed: 43 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,28 @@
22
//! verification without an operator asking for one.
33
44
use super::{AuditChain, AuditError, AuditKeys, AuditVerification};
5-
use crate::jobs::{ExclusiveJob, Shutdown};
5+
use crate::jobs::{ExclusiveJob, JobCount, Shutdown};
66
use chrono::{TimeDelta, Utc};
7-
use piquel_common::events::{EventContext, JobName};
8-
use piquel_repository::{ExclusiveConnection, LockKey};
7+
use piquel_common::events::{DomainEvent, EventContext, JobName};
8+
use piquel_repository::{ExclusiveConnection, LockKey, RecordedEvent, Verifications};
9+
use piquel_telemetry::Gauge;
910
use std::time::Duration;
1011

12+
/// Whether the newest recorded verification found the chain broken, read after
13+
/// each run of the verifier.
14+
static BROKEN: JobCount = JobCount::new(
15+
Gauge::new(
16+
"piquel.auth.audit.broken",
17+
"1",
18+
"1 when the newest recorded verification of the audit chain found it broken, 0 when \
19+
intact.",
20+
),
21+
Verifier::EVERY,
22+
);
23+
1124
/// Verifies the whole chain, on one replica at a time, once the newest recorded
12-
/// verification, whoever made it, is [`Self::VERIFY_EVERY`] old, and records
25+
/// verification, whoever made it, other than one with keys given with `--key`,
26+
/// is [`Self::VERIFY_EVERY`] old, and records
1327
/// what it found as [`JobName::AuditVerification`].
1428
pub(crate) struct Verifier {
1529
/// The keys it verifies with, the dashboard's (see [`AuditKeys::for_server`]).
@@ -25,19 +39,41 @@ impl Verifier {
2539
Self { keys }
2640
}
2741

42+
/// Registers the [`BROKEN`] gauge.
43+
pub(crate) fn observe() {
44+
BROKEN.observe();
45+
}
46+
2847
/// Verifies and records the chain, unless a verification was recorded in the
29-
/// last [`Self::VERIFY_EVERY`]. Returns what it found, if it verified.
48+
/// last [`Self::VERIFY_EVERY`], and keeps whether the newest one found it
49+
/// broken. Returns what it found, if it verified.
3050
pub(super) async fn pass(
3151
&self,
3252
connection: &mut ExclusiveConnection,
3353
) -> Result<Option<AuditVerification>, AuditError> {
34-
let newest = connection.events().newest_audit_verification().await?;
35-
if newest.is_some_and(|newest| Utc::now() - newest.occurred_at < Self::VERIFY_EVERY) {
54+
// One with keys given with `--key` says nothing of this environment's
55+
// checkpoints, as for its alert, so it neither postpones this one nor
56+
// sets the gauge.
57+
let newest = connection
58+
.events()
59+
.newest_audit_verification(Verifications::OwnKeys)
60+
.await?;
61+
if let Some(newest) = newest
62+
&& Utc::now() - newest.occurred_at < Self::VERIFY_EVERY
63+
{
64+
// A verification a newer release recorded reads as unknown, and
65+
// leaves the gauge as it was.
66+
if let RecordedEvent::Known(DomainEvent::AuditChainVerified(verification)) =
67+
newest.event
68+
{
69+
BROKEN.set(u64::from(verification.broken.is_some()));
70+
}
3671
return Ok(None);
3772
}
3873
let verification = AuditChain::verify_in(connection.begin().await?, &self.keys).await?;
3974
let context = EventContext::system(JobName::AuditVerification);
4075
AuditChain::record(connection.begin().await?, &context, &verification).await?;
76+
BROKEN.set(u64::from(verification.broken.is_some()));
4177
Ok(Some(verification))
4278
}
4379
}

‎apps/auth-service/src/audit/verify.rs‎

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use piquel_common::events::{DomainEvent, EventContext};
1313
use piquel_crypto::CryptoError;
1414
use piquel_repository::{
1515
AuditRepository, ChainLink, ChainedEvent, Checkpoint, DatabaseTransaction, RecordedEvent,
16+
Verifications,
1617
};
1718
use std::collections::BTreeMap;
1819

@@ -212,19 +213,19 @@ impl AuditChain {
212213
unsealed: tx.audit().unsealed_count().await?,
213214
};
214215
// A verification a newer release recorded reads as unknown, so as none.
215-
let verified =
216-
tx.events()
217-
.newest_audit_verification()
218-
.await?
219-
.and_then(|stored| match stored.event {
220-
RecordedEvent::Known(DomainEvent::AuditChainVerified(verification)) => {
221-
Some(RecordedVerification {
222-
at: stored.occurred_at,
223-
verification,
224-
})
225-
}
226-
_ => None,
227-
});
216+
let verified = tx
217+
.events()
218+
.newest_audit_verification(Verifications::Any)
219+
.await?
220+
.and_then(|stored| match stored.event {
221+
RecordedEvent::Known(DomainEvent::AuditChainVerified(verification)) => {
222+
Some(RecordedVerification {
223+
at: stored.occurred_at,
224+
verification,
225+
})
226+
}
227+
_ => None,
228+
});
228229
let after =
229230
after.unwrap_or_else(|| chain.anchor.as_ref().map_or(0, |anchor| anchor.position));
230231
// One more than a page tells whether another follows.

‎apps/auth-service/src/jobs/mod.rs‎

Lines changed: 53 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -99,11 +99,12 @@ impl Jobs {
9999
) -> Result<Self, StartupError> {
100100
let mut jobs = Self::new();
101101
jobs.exclusive(Cleanup::new(), database.clone());
102-
AccountPurge::observe();
102+
FAILING_PURGES.observe();
103103
jobs.exclusive(AccountPurge, database.clone());
104104
jobs.exclusive(Sealer::new(&config.audit), database.clone());
105105
let audit_keys = AuditKeys::for_server(&config.passkey.origin, config.audit.verifier())
106106
.map_err(StartupError::AuditKeys)?;
107+
Verifier::observe();
107108
jobs.exclusive(Verifier::new(audit_keys), database.clone());
108109
let (store, reloaded) = (store.clone(), keys.clone());
109110
jobs.spawn(|shutdown| store.run(reloaded, shutdown));
@@ -398,15 +399,57 @@ impl ExclusiveJob for Cleanup {
398399
}
399400
}
400401

401-
/// Accounts whose purge keeps failing, from [`FAILING_PURGES_COUNT`].
402-
static FAILING_PURGES: Gauge = Gauge::new(
403-
"piquel.auth.account_purge.failing",
404-
"{account}",
405-
"Accounts scheduled for deletion whose purge failed at least 3 times in a row.",
402+
/// A count the replica running a periodic job takes after each run, which its
403+
/// gauge reports. Every replica runs the job in turn, so each reports the count
404+
/// of its own latest run, at most one run older than the newest; one whose count
405+
/// is older than two runs, because it stopped running the job, reports none.
406+
/// Alerts read the minimum across replicas, or wait one run, before taking a
407+
/// count as current.
408+
pub(crate) struct JobCount {
409+
/// The gauge reporting it.
410+
gauge: Gauge,
411+
/// How often the job runs.
412+
every: Duration,
413+
/// The latest count on this replica, and when it was taken.
414+
counted: Mutex<Option<(u64, Instant)>>,
415+
}
416+
417+
impl JobCount {
418+
/// A count `gauge` reports, of a job that runs `every` so often.
419+
pub(crate) const fn new(gauge: Gauge, every: Duration) -> Self {
420+
Self {
421+
gauge,
422+
every,
423+
counted: Mutex::new(None),
424+
}
425+
}
426+
427+
/// Registers the gauge.
428+
pub(crate) fn observe(&'static self) {
429+
self.gauge.observe(|| {
430+
let counted = *self.counted.lock().unwrap_or_else(PoisonError::into_inner);
431+
counted
432+
.filter(|(_, at)| at.elapsed() < self.every * 2)
433+
.map(|(count, _)| (count, ()))
434+
});
435+
}
436+
437+
/// Keeps `count`, taken now.
438+
pub(crate) fn set(&self, count: u64) {
439+
*self.counted.lock().unwrap_or_else(PoisonError::into_inner) =
440+
Some((count, Instant::now()));
441+
}
442+
}
443+
444+
/// Accounts whose purge keeps failing, counted after each purge run.
445+
static FAILING_PURGES: JobCount = JobCount::new(
446+
Gauge::new(
447+
"piquel.auth.account_purge.failing",
448+
"{account}",
449+
"Accounts scheduled for deletion whose purge failed at least 3 times in a row.",
450+
),
451+
AccountPurge::EVERY,
406452
);
407-
/// The latest count of [`FAILING_PURGES`] on this replica, and when it was taken.
408-
/// The replica running the purge counts after each run.
409-
static FAILING_PURGES_COUNT: Mutex<Option<(u64, Instant)>> = Mutex::new(None);
410453

411454
/// Purges the accounts whose deletion grace period ended, each in a transaction of
412455
/// its own, attributed to [`JobName::AccountPurge`]. One run purges at most
@@ -425,22 +468,6 @@ impl AccountPurge {
425468
/// Failures in a row after which [`FAILING_PURGES`] counts an account.
426469
const FAILING_ATTEMPTS: u16 = 3;
427470

428-
/// Registers [`FAILING_PURGES`]. Every replica runs the job in turn, so each
429-
/// reports the count of its own latest run, at most one run older than the
430-
/// newest; one whose count is older than two runs, because it stopped running
431-
/// the job, reports none. Alerts read the minimum across replicas, or wait one
432-
/// run, before taking a count as current.
433-
fn observe() {
434-
FAILING_PURGES.observe(|| {
435-
let counted = *FAILING_PURGES_COUNT
436-
.lock()
437-
.unwrap_or_else(PoisonError::into_inner);
438-
counted
439-
.filter(|(_, at)| at.elapsed() < Self::EVERY * 2)
440-
.map(|(count, _)| (count, ()))
441-
});
442-
}
443-
444471
/// Purges `user_id` in `tx` if it is still scheduled for deletion and due,
445472
/// rechecked under the account lock, since it may have been restored meanwhile.
446473
pub(crate) async fn purge(
@@ -496,9 +523,7 @@ impl ExclusiveJob for AccountPurge {
496523
.deletions()
497524
.count_failing(Self::FAILING_ATTEMPTS)
498525
.await?;
499-
*FAILING_PURGES_COUNT
500-
.lock()
501-
.unwrap_or_else(PoisonError::into_inner) = Some((failing, Instant::now()));
526+
FAILING_PURGES.set(failing);
502527
let mut tx = connection.begin().await?;
503528
let context = EventContext::system(JobName::AccountPurge);
504529
let mut alerts = Alerts::new(&mut tx, &context);

crates/database/.sqlx/query-f46ef9ce938c2e884dfdcdf1ae8f796cb5ac9b954e0fc00afcc5953473b0ba70.json renamed to crates/database/.sqlx/query-8ab388b864d430df0e3537b3a8959fbac7aa3cbd84a42b94e93be16b47a6f0f5.json

Lines changed: 5 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/database/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ pub use repositories::{
3939
NewDelivery, PendingAddress, PendingRecovery,
4040
},
4141
emails::{InsertUnverifiedEmail, InsertVerifiedEmail, PendingVerification, StoredEmail},
42-
events::{EventCursor, EventFilter, RecordedEvent, StoredEvent},
42+
events::{EventCursor, EventFilter, RecordedEvent, StoredEvent, Verifications},
4343
federation::{
4444
ConsumedFederationTransaction, InsertExternalIdentity, InsertFederationTransaction,
4545
PendingFederation, StoredExternalIdentity,

‎crates/database/src/repositories/events/mod.rs‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,17 @@ struct TaggedEvent {
221221
data: Value,
222222
}
223223

224+
/// Which verifications of the audit chain
225+
/// [`EventRepository::newest_audit_verification`] reads.
226+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
227+
pub enum Verifications {
228+
/// Every one.
229+
Any,
230+
/// Those made with the environment's own keys, not keys given with `--key`,
231+
/// which say nothing of its checkpoints.
232+
OwnKeys,
233+
}
234+
224235
/// The [`Personal`] values of one payload, keyed by their JSON pointer, as stored
225236
/// in `event_personal_data.details`.
226237
#[derive(Default, Serialize, Deserialize)]
@@ -435,17 +446,19 @@ impl EventRepository<'_> {
435446
.collect()
436447
}
437448

438-
/// The newest `audit_chain_verified` event, by when it was recorded. The kind
439-
/// is written into the query, not bound, so every plan reads the `(kind,
440-
/// occurred_at)` index: one entry, however many events there are. After the
441-
/// clock steps back, an older verification can read as the newest until the
442-
/// next one is recorded.
449+
/// The newest `audit_chain_verified` event of those `counted`, by when it was
450+
/// recorded. The kind is written into the query, not bound, so every plan
451+
/// reads the `(kind, occurred_at)` index: one entry, however many events
452+
/// there are, or as many as the newest verifications that were left out.
453+
/// After the clock steps back, an older verification can read as the newest
454+
/// until the next one is recorded.
443455
///
444456
/// # Errors
445457
///
446458
/// Returns [`DatabaseError`] if the query fails or the stored event does not decode.
447459
pub async fn newest_audit_verification(
448460
&mut self,
461+
counted: Verifications,
449462
) -> Result<Option<StoredEvent>, DatabaseError> {
450463
run!(
451464
self,
@@ -464,8 +477,10 @@ impl EventRepository<'_> {
464477
FROM domain_events e
465478
LEFT JOIN event_personal_data p ON p.event_id = e.id
466479
WHERE e.kind = 'audit_chain_verified'
480+
AND ($1 OR e.payload ->> 'keys' IS DISTINCT FROM 'given')
467481
ORDER BY e.occurred_at DESC
468-
LIMIT 1"#
482+
LIMIT 1"#,
483+
counted == Verifications::Any,
469484
)
470485
)?
471486
.map(StoredEvent::try_from)

‎docs/dev/operations/administration.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -344,10 +344,11 @@ auth-service audit verify # recompute the tamper-evident ch
344344

345345
On the dashboard, the **Events** page lists events, and **Show views** adds the
346346
views. The **Audit** page shows the last verification, and **Verify now** runs
347-
another. Auth also verifies the chain on its own once no verification has been
348-
recorded for six hours, so the page always shows a recent one; `audit verify`
349-
and **Verify now** push the next automatic run back. A verification that finds
350-
the chain broken, other than one with `--key`, raises an alert (see
347+
another. Auth also verifies the chain on its own once no verification, other
348+
than one with `--key`, has been recorded for six hours, so the page always shows
349+
a recent one; `audit verify` and **Verify now** push the next automatic run
350+
back. A verification that finds the chain broken, other than one with `--key`,
351+
raises an alert (see
351352
[respond to an alert](#respond-to-an-alert)). See
352353
[audit history](../security/audit-history.md), which also explains pruning.
353354

0 commit comments

Comments
 (0)