diff --git a/pkgs/id/crates/id-sync/src/federation/slices/b06_rejection_events.rs b/pkgs/id/crates/id-sync/src/federation/slices/b06_rejection_events.rs new file mode 100644 index 0000000000..cd87bdb525 --- /dev/null +++ b/pkgs/id/crates/id-sync/src/federation/slices/b06_rejection_events.rs @@ -0,0 +1,437 @@ +//! B06: observable, recordable rejection events at the universal +//! signed-ingest gate (#10247, statements S1.19 and S1.25). +//! +//! The B32 gate refuses an envelope fail-closed and changes no state. +//! That is safe but silent: an operator cannot see what was refused or +//! why. This slice wraps the gate so that every refusal also produces +//! one typed [`RejectionEvent`], appended to a local, hash-chained +//! [`RejectionLog`]: +//! +//! - **Observable.** Each event names the ingress path, the B32 +//! [`RejectReason`] and its stable class, the claimed signer and key, +//! the scope, the event id, the declared payload digest and the digest +//! of the bytes actually presented. Per-class counters summarise the +//! log. +//! - **Recordable.** Each event has a canonical, domain-separated byte +//! form and is chained to the previous event's digest, so a later edit, +//! drop or reorder of the local record is detectable +//! ([`RejectionLog::verify_chain`]). +//! - **Admission-time context.** Each event records the key status the +//! gate observed for the presented key (bound to whom, or unbound) and +//! a digest of the gate policy in force (signer table and freshness +//! window). A signed wall-clock time is never treated as proof of +//! historical validity; the event time is the gate's own logical time. +//! - **Not an accusation.** Events are [`Visibility::LocalOnly`]. Export +//! to anything else is an optional hook ([`RejectionExporter`]) that is +//! off unless installed, and disabling it is the rollback: rejection +//! stays fail-closed and locally observable either way. +//! - **Outcome-neutral.** Observation never changes the gate's answer. +//! The rejected payload bytes are not stored, only digests, and a +//! rejected envelope never reaches the admitted set. +//! +//! The federation roots record this slice path without declaring it +//! (slice 9110-02); the integration test includes this file and B32's +//! directly, and this module reaches B32 as `super::b32_ingest_gate`. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt; + +use sha2::{Digest, Sha256}; + +use super::b32_ingest_gate::{ + Admission, ED25519_PUBLIC_KEY_LEN, Envelope, EventId, FreshnessWindow, IngestGate, IngressPath, + LogicalTime, PayloadDigest, RejectReason, SignerAuthorization, payload_digest, +}; + +/// Digest of a rejection record or of the gate policy (SHA-256). +pub type RecordDigest = [u8; 32]; + +/// The chain value before the first event. +pub const GENESIS: RecordDigest = [0; 32]; + +const RECORD_DOMAIN: &[u8] = b"id-sync/b06-rejection-event/v1"; +const POLICY_DOMAIN: &[u8] = b"id-sync/b06-gate-policy/v1"; + +/// Who may see a rejection event. Rejection is auditable locally; it +/// never becomes a public accusation by itself. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Visibility { + /// Kept in this node's local record only. + LocalOnly, +} + +/// What the gate knew about the presented key when it refused. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum KeyStatus { + /// The key is bound to this identity in the gate's signer table. + BoundTo(String), + /// The key is bound to no identity the gate knows. + Unbound, +} + +/// The stable class name of a B32 rejection, for counters and export. +pub const fn reason_class(reason: &RejectReason) -> &'static str { + match reason { + RejectReason::Unsigned => "unsigned", + RejectReason::UnknownSigner => "unknown_signer", + RejectReason::SignerMismatch { .. } => "signer_mismatch", + RejectReason::InvalidSignature => "invalid_signature", + RejectReason::SemanticInvalid => "semantic_invalid", + RejectReason::NotAuthorized { .. } => "not_authorized", + RejectReason::Stale => "stale", + RejectReason::FutureSkew => "future_skew", + RejectReason::Replay => "replay", + } +} + +/// Every class [`reason_class`] can return, in gate-check order. +pub const REASON_CLASSES: [&str; 9] = [ + "unsigned", + "unknown_signer", + "signer_mismatch", + "invalid_signature", + "semantic_invalid", + "not_authorized", + "stale", + "future_skew", + "replay", +]; + +/// One refused envelope, as the gate observed it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RejectionEvent { + /// Position in the local log, from 0. + pub sequence: u64, + /// The gate's logical time when it refused. + pub observed_at: LogicalTime, + /// The path the envelope arrived by. + pub path: IngressPath, + /// Why the gate refused. + pub reason: RejectReason, + /// The signer identity the envelope claimed. + pub claimed_signer: String, + /// The verifying key the envelope presented. + pub verifying_key: [u8; ED25519_PUBLIC_KEY_LEN], + /// What the gate's signer table said about that key. + pub key_status: KeyStatus, + /// Whether a signature was presented at all. + pub signed: bool, + /// The scope the envelope asked for. + pub scope: String, + /// The envelope's event id. + pub event_id: EventId, + /// The `issued_at` the envelope claimed (unverified when the + /// signature did not verify). + pub claimed_issued_at: LogicalTime, + /// The payload digest the envelope declared. + pub declared_digest: PayloadDigest, + /// The digest of the payload bytes actually presented. The bytes + /// themselves are not kept. + pub presented_digest: PayloadDigest, + /// Digest of the gate policy in force. + pub policy_digest: RecordDigest, + /// Digest of the previous event's record, or [`GENESIS`]. + pub prev: RecordDigest, + /// Who may see this event. + pub visibility: Visibility, +} + +impl RejectionEvent { + /// The stable class of [`RejectionEvent::reason`]. + pub const fn class(&self) -> &'static str { + reason_class(&self.reason) + } + + /// The canonical record bytes: domain-separated, every field + /// length-prefixed, the chain link included. + pub fn record_bytes(&self) -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(RECORD_DOMAIN); + push(&mut out, &self.sequence.to_be_bytes()); + push(&mut out, &self.observed_at.to_be_bytes()); + push(&mut out, path_token(self.path).as_bytes()); + push(&mut out, self.class().as_bytes()); + match &self.reason { + RejectReason::SignerMismatch { claimed, bound_to } => { + push(&mut out, claimed.as_bytes()); + push(&mut out, bound_to.as_bytes()); + } + RejectReason::NotAuthorized { scope } => push(&mut out, scope.as_bytes()), + _ => {} + } + push(&mut out, self.claimed_signer.as_bytes()); + push(&mut out, &self.verifying_key); + match &self.key_status { + KeyStatus::BoundTo(identity) => { + push(&mut out, b"bound"); + push(&mut out, identity.as_bytes()); + } + KeyStatus::Unbound => push(&mut out, b"unbound"), + } + push(&mut out, &[u8::from(self.signed)]); + push(&mut out, self.scope.as_bytes()); + push(&mut out, &self.event_id); + push(&mut out, &self.claimed_issued_at.to_be_bytes()); + push(&mut out, &self.declared_digest); + push(&mut out, &self.presented_digest); + push(&mut out, &self.policy_digest); + push(&mut out, &self.prev); + push( + &mut out, + match self.visibility { + Visibility::LocalOnly => b"local-only", + }, + ); + out + } + + /// SHA-256 of [`RejectionEvent::record_bytes`]; the next event's + /// `prev`. + pub fn digest(&self) -> RecordDigest { + sha256(&self.record_bytes()) + } +} + +/// Where in the chain a local record stops verifying. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChainError { + /// The event at this position has the wrong sequence number. + Sequence(usize), + /// The event at this position does not link to its predecessor. + Link(usize), +} + +impl fmt::Display for ChainError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Sequence(at) => write!(f, "rejection log sequence breaks at {at}"), + Self::Link(at) => write!(f, "rejection log chain breaks at {at}"), + } + } +} + +impl std::error::Error for ChainError {} + +/// The local, append-only record of rejection events. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct RejectionLog { + events: Vec, +} + +impl RejectionLog { + /// Every recorded event, oldest first. + pub fn events(&self) -> &[RejectionEvent] { + &self.events + } + + /// How many events are recorded. + pub const fn len(&self) -> usize { + self.events.len() + } + + /// Whether nothing has been refused. + pub const fn is_empty(&self) -> bool { + self.events.is_empty() + } + + /// The digest the next event links to. + pub fn head(&self) -> RecordDigest { + self.events.last().map_or(GENESIS, RejectionEvent::digest) + } + + /// Count of events per class; every class is present, zero or not. + pub fn counts(&self) -> BTreeMap<&'static str, u64> { + let mut counts: BTreeMap<&'static str, u64> = + REASON_CLASSES.iter().map(|class| (*class, 0)).collect(); + for event in &self.events { + *counts.entry(event.class()).or_default() += 1; + } + counts + } + + /// Check sequence numbers and chain links from the first event. + pub fn verify_chain(&self) -> Result<(), ChainError> { + verify_chain(&self.events) + } +} + +/// Check that `events` is a gap-free chain starting at [`GENESIS`]. +pub fn verify_chain(events: &[RejectionEvent]) -> Result<(), ChainError> { + let mut prev = GENESIS; + for (index, event) in events.iter().enumerate() { + if event.sequence != index as u64 { + return Err(ChainError::Sequence(index)); + } + if event.prev != prev { + return Err(ChainError::Link(index)); + } + prev = event.digest(); + } + Ok(()) +} + +/// An optional sink for rejection events beyond the local record. It +/// sees each event after it is recorded and cannot change the gate's +/// outcome or the local record. +pub trait RejectionExporter { + /// Receive one recorded event. + fn export(&mut self, event: &RejectionEvent); +} + +/// The B32 gate with every refusal observed and recorded. +pub struct ObservedGate { + gate: IngestGate, + bindings: BTreeMap<[u8; ED25519_PUBLIC_KEY_LEN], String>, + policy_digest: RecordDigest, + log: RejectionLog, + exporter: Option>, +} + +impl fmt::Debug for ObservedGate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ObservedGate") + .field("gate", &self.gate) + .field("policy_digest", &self.policy_digest) + .field("log", &self.log) + .field("export_enabled", &self.exporter.is_some()) + .finish_non_exhaustive() + } +} + +impl ObservedGate { + /// Build the B32 gate from `signers` and `freshness`, observed. + /// Export is off. + pub fn new(signers: Vec, freshness: FreshnessWindow) -> Self { + let policy_digest = policy_digest(&signers, freshness); + let bindings = signers + .iter() + .map(|signer| (signer.verifying_key, signer.identity.clone())) + .collect(); + Self { + gate: IngestGate::new(signers, freshness), + bindings, + policy_digest, + log: RejectionLog::default(), + exporter: None, + } + } + + /// Install an exporter, replacing any other. + pub fn enable_export(&mut self, exporter: Box) { + self.exporter = Some(exporter); + } + + /// Remove the exporter. Rejection stays fail-closed and recorded. + pub fn disable_export(&mut self) -> Option> { + self.exporter.take() + } + + /// Whether an exporter is installed. + pub const fn export_enabled(&self) -> bool { + self.exporter.is_some() + } + + /// The digest of the gate policy every event records. + pub const fn policy_digest(&self) -> RecordDigest { + self.policy_digest + } + + /// The local rejection record. + pub const fn log(&self) -> &RejectionLog { + &self.log + } + + /// The wrapped gate, for its admission queries. + pub const fn gate(&self) -> &IngestGate { + &self.gate + } + + /// Run the B32 gate. The outcome is exactly the gate's; a refusal + /// is also recorded (and exported, when export is on) before it is + /// returned. + pub fn admit( + &mut self, + path: IngressPath, + envelope: &Envelope, + now: LogicalTime, + ) -> Result { + let reason = match self.gate.admit(path, envelope, now) { + Ok(admission) => return Ok(admission), + Err(reason) => reason, + }; + let key_status = self + .bindings + .get(&envelope.verifying_key) + .map_or(KeyStatus::Unbound, |identity| { + KeyStatus::BoundTo(identity.clone()) + }); + let event = RejectionEvent { + sequence: self.log.events.len() as u64, + observed_at: now, + path, + reason: reason.clone(), + claimed_signer: envelope.signer.clone(), + verifying_key: envelope.verifying_key, + key_status, + signed: envelope.signature.is_some(), + scope: envelope.scope.clone(), + event_id: envelope.event_id, + claimed_issued_at: envelope.issued_at, + declared_digest: envelope.payload_digest, + presented_digest: payload_digest(&envelope.payload), + policy_digest: self.policy_digest, + prev: self.log.head(), + visibility: Visibility::LocalOnly, + }; + self.log.events.push(event); + if let (Some(exporter), Some(event)) = (self.exporter.as_mut(), self.log.events.last()) { + exporter.export(event); + } + Err(reason) + } +} + +/// Digest of the gate policy: the signer table, in a canonical order, +/// and the freshness window. +pub fn policy_digest(signers: &[SignerAuthorization], freshness: FreshnessWindow) -> RecordDigest { + let mut ordered: Vec<&SignerAuthorization> = signers.iter().collect(); + ordered.sort_by(|a, b| { + (&a.identity, &a.verifying_key, &a.scopes).cmp(&(&b.identity, &b.verifying_key, &b.scopes)) + }); + let mut out = Vec::new(); + out.extend_from_slice(POLICY_DOMAIN); + push(&mut out, &(ordered.len() as u64).to_be_bytes()); + for signer in ordered { + push(&mut out, signer.identity.as_bytes()); + push(&mut out, &signer.verifying_key); + let scopes: &BTreeSet = &signer.scopes; + push(&mut out, &(scopes.len() as u64).to_be_bytes()); + for scope in scopes { + push(&mut out, scope.as_bytes()); + } + } + push(&mut out, &freshness.max_age.to_be_bytes()); + push(&mut out, &freshness.max_future_skew.to_be_bytes()); + sha256(&out) +} + +const fn path_token(path: IngressPath) -> &'static str { + match path { + IngressPath::Local => "local", + IngressPath::Loopback => "loopback", + IngressPath::Internal => "internal", + IngressPath::Hosted => "hosted", + IngressPath::Remote => "remote", + } +} + +fn push(out: &mut Vec, field: &[u8]) { + out.extend_from_slice(&(field.len() as u64).to_be_bytes()); + out.extend_from_slice(field); +} + +fn sha256(bytes: &[u8]) -> [u8; 32] { + let mut hasher = Sha256::new(); + hasher.update(bytes); + hasher.finalize().into() +} diff --git a/pkgs/id/crates/id-sync/tests/federation_b06.rs b/pkgs/id/crates/id-sync/tests/federation_b06.rs new file mode 100644 index 0000000000..2a33dbfc9d --- /dev/null +++ b/pkgs/id/crates/id-sync/tests/federation_b06.rs @@ -0,0 +1,399 @@ +//! B06 invariant test: observable, recordable rejection events at the +//! universal signed-ingest gate (#10247, statements S1.19 and S1.25). +//! +//! Oracle: **invariant** — every rejected ingest has typed observable +//! evidence and no rejected payload reaches accepted state. The +//! reference is an unobserved B32 gate run in lockstep over generated +//! envelope streams: the observed gate must return exactly its outcome, +//! append exactly one event per refusal and none per admission, leave the +//! admitted set exactly as the bare gate does, and keep a gap-free hash +//! chain. Event fields are checked against values the test computes +//! itself (payload digests with `sha2` directly, key bindings from the +//! test's own table), not against the implementation. +//! +//! Both slice modules are loaded by path: the federation roots record +//! them without declaring them (slice 9110-02), and B06 reaches B32 as +//! `super::b32_ingest_gate`. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[path = "../src/federation/slices/b32_ingest_gate.rs"] +mod b32_ingest_gate; + +#[path = "../src/federation/slices/b06_rejection_events.rs"] +mod b06; + +use std::cell::RefCell; +use std::collections::BTreeSet; +use std::rc::Rc; + +use b06::{ + ChainError, GENESIS, KeyStatus, ObservedGate, REASON_CLASSES, RejectionEvent, + RejectionExporter, Visibility, policy_digest, reason_class, verify_chain, +}; +use b32_ingest_gate::{ + Envelope, FreshnessWindow, IngestGate, IngressPath, RejectReason, SignerAuthorization, + sign_envelope, +}; +use ed25519_dalek::SigningKey; +use proptest::prelude::*; +use sha2::{Digest, Sha256}; + +const NOW: u64 = 10_000; +const FRESHNESS: FreshnessWindow = FreshnessWindow { + max_age: 600, + max_future_skew: 30, +}; + +fn key(seed: u8) -> SigningKey { + SigningKey::from_bytes(&[seed; 32]) +} + +fn signer(identity: &str, seed: u8, scopes: &[&str]) -> SignerAuthorization { + SignerAuthorization { + identity: identity.to_owned(), + verifying_key: key(seed).verifying_key().to_bytes(), + scopes: scopes + .iter() + .map(|s| (*s).to_owned()) + .collect::>(), + } +} + +/// alice (seed 7) may write sync and query; bob (seed 9) only sync; +/// carol (seed 11) is unknown to the gate. +fn signers() -> Vec { + vec![ + signer("alice", 7, &["sync", "query"]), + signer("bob", 9, &["sync"]), + ] +} + +fn sha(bytes: &[u8]) -> [u8; 32] { + let mut hasher = Sha256::new(); + hasher.update(bytes); + hasher.finalize().into() +} + +/// The test's own view of which identity each key is bound to. +fn expected_status(verifying_key: &[u8; 32]) -> KeyStatus { + if *verifying_key == key(7).verifying_key().to_bytes() { + KeyStatus::BoundTo("alice".into()) + } else if *verifying_key == key(9).verifying_key().to_bytes() { + KeyStatus::BoundTo("bob".into()) + } else { + KeyStatus::Unbound + } +} + +/// One generated envelope shape. +#[derive(Debug, Clone, Copy)] +enum Shape { + Valid, + BobValid, + Unsigned, + TamperedPayload, + WrongClaimedSigner, + UnknownKey, + Unauthorized, + Stale, + Future, + EmptyPayload, + BadSignature, +} + +const SHAPES: [Shape; 11] = [ + Shape::Valid, + Shape::BobValid, + Shape::Unsigned, + Shape::TamperedPayload, + Shape::WrongClaimedSigner, + Shape::UnknownKey, + Shape::Unauthorized, + Shape::Stale, + Shape::Future, + Shape::EmptyPayload, + Shape::BadSignature, +]; + +fn envelope(shape: Shape, id: u8) -> Envelope { + let event_id = [id; 32]; + let payload = [b'p', id]; + match shape { + Shape::Valid => sign_envelope(&key(7), "alice", "sync", &payload, event_id, NOW), + Shape::BobValid => sign_envelope(&key(9), "bob", "sync", &payload, event_id, NOW), + Shape::Unsigned => { + let mut e = sign_envelope(&key(7), "alice", "sync", &payload, event_id, NOW); + e.signature = None; + e + } + Shape::TamperedPayload => { + let mut e = sign_envelope(&key(7), "alice", "sync", &payload, event_id, NOW); + e.payload = b"swapped".to_vec(); + e + } + Shape::WrongClaimedSigner => { + sign_envelope(&key(9), "alice", "sync", &payload, event_id, NOW) + } + Shape::UnknownKey => sign_envelope(&key(11), "carol", "sync", &payload, event_id, NOW), + Shape::Unauthorized => sign_envelope(&key(9), "bob", "query", &payload, event_id, NOW), + Shape::Stale => sign_envelope(&key(7), "alice", "sync", &payload, event_id, NOW - 601), + Shape::Future => sign_envelope(&key(7), "alice", "sync", &payload, event_id, NOW + 31), + Shape::EmptyPayload => sign_envelope(&key(7), "alice", "sync", b"", event_id, NOW), + Shape::BadSignature => { + let mut e = sign_envelope(&key(7), "alice", "sync", &payload, event_id, NOW); + let mut sig = e.signature.unwrap(); + sig[0] ^= 1; + e.signature = Some(sig); + e + } + } +} + +/// An exporter that keeps what it is handed, shared with the test. +#[derive(Clone, Default)] +struct Capture(Rc>>); + +impl RejectionExporter for Capture { + fn export(&mut self, event: &RejectionEvent) { + self.0.borrow_mut().push(event.clone()); + } +} + +/// Run `ops` through an observed gate and a bare B32 gate in lockstep, +/// checking every invariant after every step. +fn check_stream(ops: &[(usize, usize, u8)], export_until: Option) { + let mut observed = ObservedGate::new(signers(), FRESHNESS); + let mut reference = IngestGate::new(signers(), FRESHNESS); + let capture = Capture::default(); + if export_until.is_some() { + observed.enable_export(Box::new(capture.clone())); + } + let mut exported_while_on = 0_usize; + for (step, &(shape, path, id)) in ops.iter().enumerate() { + if export_until == Some(step) { + assert!(observed.disable_export().is_some()); + } + let shape = SHAPES[shape % SHAPES.len()]; + let path = IngressPath::ALL[path % IngressPath::ALL.len()]; + let env = envelope(shape, id); + let before_len = observed.log().len(); + let was_admitted = reference.is_admitted(&env.event_id); + + let want = reference.admit(path, &env, NOW); + let got = observed.admit(path, &env, NOW); + assert_eq!(got, want, "observation changed the outcome at step {step}"); + + // The admitted set is exactly the bare gate's. + assert_eq!(observed.gate().admitted_count(), reference.admitted_count()); + assert_eq!( + observed.gate().is_admitted(&env.event_id), + reference.is_admitted(&env.event_id) + ); + + match want { + Ok(_) => assert_eq!(observed.log().len(), before_len, "admission was logged"), + Err(reason) => { + // A refusal never changes whether its event id is admitted. + assert_eq!(reference.is_admitted(&env.event_id), was_admitted); + assert_eq!(observed.log().len(), before_len + 1, "refusal not logged"); + let event = observed.log().events().last().unwrap(); + assert_eq!(event.sequence, before_len as u64); + assert_eq!(event.observed_at, NOW); + assert_eq!(event.path, path); + assert_eq!(event.class(), reason_class(&reason)); + assert_eq!(event.reason, reason); + assert_eq!(event.claimed_signer, env.signer); + assert_eq!(event.verifying_key, env.verifying_key); + assert_eq!(event.key_status, expected_status(&env.verifying_key)); + assert_eq!(event.signed, env.signature.is_some()); + assert_eq!(event.scope, env.scope); + assert_eq!(event.event_id, env.event_id); + assert_eq!(event.claimed_issued_at, env.issued_at); + assert_eq!(event.declared_digest, env.payload_digest); + assert_eq!(event.presented_digest, sha(&env.payload)); + assert_eq!(event.policy_digest, observed.policy_digest()); + assert_eq!(event.visibility, Visibility::LocalOnly); + if export_until.is_some_and(|until| step < until) { + exported_while_on += 1; + } + } + } + observed.log().verify_chain().unwrap(); + } + + // Counters tally the log, with every class present. + let counts = observed.log().counts(); + assert_eq!(counts.len(), REASON_CLASSES.len()); + for class in REASON_CLASSES { + let tally = observed + .log() + .events() + .iter() + .filter(|e| e.class() == class) + .count() as u64; + assert_eq!(counts[class], tally); + } + + // The exporter saw exactly the events recorded while it was on. + let exported = capture.0.borrow(); + assert_eq!(exported.len(), exported_while_on); + assert_eq!( + exported.as_slice(), + &observed.log().events()[..exported_while_on] + ); +} + +#[test] +fn every_rejection_class_is_observed_with_its_evidence() { + let ops: Vec<(usize, usize, u8)> = (0..SHAPES.len()) + .map(|i| (i, i, 100 + u8::try_from(i).unwrap())) + .collect(); + check_stream(&ops, None); + let mut gate = ObservedGate::new(signers(), FRESHNESS); + for (shape, path, id) in &ops { + let _ = gate.admit( + IngressPath::ALL[*path % 5], + &envelope(SHAPES[*shape], *id), + NOW, + ); + } + // Replay: the first valid envelope again. + let replay = envelope(Shape::Valid, 100); + assert_eq!( + gate.admit(IngressPath::Remote, &replay, NOW), + Err(RejectReason::Replay) + ); + let classes: BTreeSet<&str> = gate + .log() + .events() + .iter() + .map(RejectionEvent::class) + .collect(); + assert_eq!(classes, REASON_CLASSES.into_iter().collect()); +} + +#[test] +fn local_and_remote_refusals_are_recorded_alike() { + let mut gate = ObservedGate::new(signers(), FRESHNESS); + for path in IngressPath::ALL { + assert_eq!( + gate.admit(path, &envelope(Shape::Unsigned, 1), NOW), + Err(RejectReason::Unsigned) + ); + } + let paths: Vec = gate.log().events().iter().map(|e| e.path).collect(); + assert_eq!(paths, IngressPath::ALL.to_vec()); + assert!(gate.log().events().iter().all(|e| e.class() == "unsigned")); +} + +#[test] +fn misattributed_key_records_who_the_key_is_really_bound_to() { + let mut gate = ObservedGate::new(signers(), FRESHNESS); + let env = envelope(Shape::WrongClaimedSigner, 3); + assert_eq!( + gate.admit(IngressPath::Remote, &env, NOW), + Err(RejectReason::SignerMismatch { + claimed: "alice".into(), + bound_to: "bob".into() + }) + ); + let event = &gate.log().events()[0]; + assert_eq!(event.claimed_signer, "alice"); + assert_eq!(event.key_status, KeyStatus::BoundTo("bob".into())); + let unknown = envelope(Shape::UnknownKey, 4); + let _ = gate.admit(IngressPath::Remote, &unknown, NOW); + assert_eq!(gate.log().events()[1].key_status, KeyStatus::Unbound); +} + +#[test] +fn tampering_with_the_record_is_detected() { + let mut gate = ObservedGate::new(signers(), FRESHNESS); + for (i, shape) in [Shape::Unsigned, Shape::Stale, Shape::UnknownKey] + .into_iter() + .enumerate() + { + let _ = gate.admit( + IngressPath::Remote, + &envelope(shape, u8::try_from(i).unwrap()), + NOW, + ); + } + let events = gate.log().events().to_vec(); + assert_eq!(events[0].prev, GENESIS); + verify_chain(&events).unwrap(); + + let mut edited = events.clone(); + edited[1].scope = "query".into(); + assert_eq!(verify_chain(&edited), Err(ChainError::Link(2))); + + let mut dropped = events.clone(); + dropped.remove(1); + assert_eq!(verify_chain(&dropped), Err(ChainError::Sequence(1))); + + let mut reordered = events.clone(); + reordered.swap(0, 1); + assert_eq!(verify_chain(&reordered), Err(ChainError::Sequence(0))); + + let mut renumbered = events; + renumbered.remove(0); + for (i, event) in renumbered.iter_mut().enumerate() { + event.sequence = i as u64; + } + assert_eq!(verify_chain(&renumbered), Err(ChainError::Link(0))); +} + +#[test] +fn policy_digest_names_the_policy_not_the_table_order() { + let mut reversed = signers(); + reversed.reverse(); + assert_eq!( + policy_digest(&signers(), FRESHNESS), + policy_digest(&reversed, FRESHNESS) + ); + let wider = FreshnessWindow { + max_age: 601, + ..FRESHNESS + }; + assert_ne!( + policy_digest(&signers(), FRESHNESS), + policy_digest(&signers(), wider) + ); + let mut more_scope = signers(); + more_scope[1].scopes.insert("query".into()); + assert_ne!( + policy_digest(&signers(), FRESHNESS), + policy_digest(&more_scope, FRESHNESS) + ); +} + +#[test] +fn disabling_export_keeps_rejection_fail_closed_and_recorded() { + let ops: Vec<(usize, usize, u8)> = (0..40) + .map(|i| (i % SHAPES.len(), i, u8::try_from(i % 7).unwrap())) + .collect(); + check_stream(&ops, Some(15)); + let mut gate = ObservedGate::new(signers(), FRESHNESS); + assert!(gate.log().is_empty()); + assert!(!gate.export_enabled()); + gate.enable_export(Box::new(Capture::default())); + assert!(gate.export_enabled()); + gate.disable_export(); + assert_eq!( + gate.admit(IngressPath::Local, &envelope(Shape::Unsigned, 9), NOW), + Err(RejectReason::Unsigned) + ); + assert_eq!(gate.log().len(), 1); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(128))] + + #[test] + fn observed_gate_matches_the_bare_gate_and_records_every_refusal( + ops in proptest::collection::vec((0..SHAPES.len(), 0..5_usize, 0_u8..6), 0..48), + export_switch in proptest::option::of(0_usize..48), + ) { + check_stream(&ops, export_switch); + } +}