From d569ec1a7cba21a8cf1d1bb28928d0c4461df94d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 22:52:40 +0000 Subject: [PATCH] id-sync: B23 signed, expiring routing observations Routing state holds only observers' signed statements about their own links, admitted through the B32 gate and refused when poisoned, with newer statements replacing older ones and expired ones reported stale. The topology is explicitly partial (unobserved and stale peers named), validation_due lists peers to re-probe, and changes() reports appeared, vanished and lost-from-sight peers and link changes. Static mode is the rollback. Refs #10251 Co-Authored-By: Claude Opus 5.5 --- .../federation/slices/b23_routing_state.rs | 464 +++++++++++++ .../id/crates/id-sync/tests/federation_b23.rs | 632 ++++++++++++++++++ 2 files changed, 1096 insertions(+) create mode 100644 pkgs/id/crates/id-sync/src/federation/slices/b23_routing_state.rs create mode 100644 pkgs/id/crates/id-sync/tests/federation_b23.rs diff --git a/pkgs/id/crates/id-sync/src/federation/slices/b23_routing_state.rs b/pkgs/id/crates/id-sync/src/federation/slices/b23_routing_state.rs new file mode 100644 index 0000000000..8f86777e13 --- /dev/null +++ b/pkgs/id/crates/id-sync/src/federation/slices/b23_routing_state.rs @@ -0,0 +1,464 @@ +//! B23: routing-state freshness, periodic validation and detection of +//! peer and topology changes (#10251, statements S1.73-S1.76; design +//! "Resource/security invariants"). +//! +//! A server may keep routing state (S1.73), but only as signed, +//! expiring, partial observations, never as a trusted global map: +//! +//! - A [`RouteObservation`] is one observer's statement about its own +//! links: which peers it reached and which it tried and could not +//! reach, in one scope, when, and until when the statement holds. An +//! observer can speak only for its own links, so a claim about two +//! other peers is not expressible. +//! - Observations arrive only as B32 envelopes: [`RoutingState::ingest`] +//! runs the B32 gate (signature, B05-style signer binding, scope +//! authorization, freshness, replay) before it decodes anything, then +//! refuses a poisoned observation: bytes that do not decode exactly, +//! an observer other than the signer, another scope, a time other +//! than the envelope's, an expiry not after the observation or past +//! the policy's maximum lifetime. +//! - Staleness is expected (S1.75). A newer observation from the same +//! observer replaces the older one; an older or conflicting one never +//! replaces a newer one. An observation past its expiry is reported +//! as stale and contributes nothing to the current topology. +//! - [`RoutingState::topology`] is a [`PartialTopology`]: the links that +//! current observations vouch for, the observers whose statements went +//! stale, and the configured peers no current observation covers. It +//! has no notion of completeness; nothing in it says the graph is +//! whole. +//! - Periodic validation (S1.74): [`RoutingState::validation_due`] names +//! the configured peers whose own observation is missing, expired or +//! older than the revalidation interval, so the caller probes them. +//! - Change detection (S1.76): [`changes`] compares two topologies and +//! reports peers that appeared, peers that vanished (a current +//! observer reports them unreachable and none reaches them), peers +//! that were only lost from sight because the statements about them +//! went stale, observers that went stale, and links gained and lost. +//! +//! Rollback: [`RoutingMode::Static`] ignores dynamic observations and +//! uses the explicit static links; dynamic state still expires and is +//! pruned. +//! +//! Observation payload (integers big-endian, strings as a u32 length +//! and UTF-8 bytes): +//! +//! ```text +//! "id-sync/b23-route-observation/v1" observer scope observed_at:u64 +//! expires_at:u64 link_count:u32 (peer status:u8)* +//! ``` +//! +//! Links are sorted by peer with no repeats, never name the observer, +//! and status is 1 (reachable) or 2 (unreachable). +//! +//! This module is deliberately self-contained: the federation roots +//! record slice paths without declaring them (slice 9110-02), so the +//! slice's integration test includes this file directly and no shared +//! root names it yet; #9110-09 wires versioned public exports after +//! module outputs land. + +use std::collections::{BTreeMap, BTreeSet}; + +use super::b32_ingest_gate::{Envelope, IngestGate, IngressPath, LogicalTime, RejectReason}; + +/// Domain prefix of an observation payload. +pub const OBSERVATION_DOMAIN: &[u8] = b"id-sync/b23-route-observation/v1"; + +/// A peer's identity, as bound in the B32 signer table. +pub type PeerId = String; + +/// A directed link: (observer, peer). +pub type Link = (PeerId, PeerId); + +/// What an observer saw of one peer. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum LinkStatus { + /// The observer reached the peer. + Reachable, + /// The observer tried and could not reach the peer. + Unreachable, +} + +impl LinkStatus { + const fn tag(self) -> u8 { + match self { + Self::Reachable => 1, + Self::Unreachable => 2, + } + } + + const fn from_tag(tag: u8) -> Option { + match tag { + 1 => Some(Self::Reachable), + 2 => Some(Self::Unreachable), + _ => None, + } + } +} + +/// One observer's signed statement about its own links. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RouteObservation { + /// Who observed, and signs. + pub observer: PeerId, + /// The scope the observation is about. + pub scope: String, + /// When it observed, in logical seconds. + pub observed_at: LogicalTime, + /// When the statement stops holding. + pub expires_at: LogicalTime, + /// What it saw of each peer. + pub links: BTreeMap, +} + +fn push_str(out: &mut Vec, value: &str) { + out.extend_from_slice(&u32::try_from(value.len()).unwrap_or(u32::MAX).to_be_bytes()); + out.extend_from_slice(value.as_bytes()); +} + +struct Reader<'a> { + rest: &'a [u8], +} + +impl<'a> Reader<'a> { + const fn take(&mut self, n: usize) -> Option<&'a [u8]> { + if self.rest.len() < n { + return None; + } + let (head, tail) = self.rest.split_at(n); + self.rest = tail; + Some(head) + } + + fn u32(&mut self) -> Option { + self.take(4)?.try_into().ok().map(u32::from_be_bytes) + } + + fn u64(&mut self) -> Option { + self.take(8)?.try_into().ok().map(u64::from_be_bytes) + } + + fn string(&mut self) -> Option { + let len = usize::try_from(self.u32()?).ok()?; + String::from_utf8(self.take(len)?.to_vec()).ok() + } +} + +impl RouteObservation { + /// The canonical payload bytes. + pub fn encode(&self) -> Vec { + let mut out = OBSERVATION_DOMAIN.to_vec(); + push_str(&mut out, &self.observer); + push_str(&mut out, &self.scope); + out.extend_from_slice(&self.observed_at.to_be_bytes()); + out.extend_from_slice(&self.expires_at.to_be_bytes()); + out.extend_from_slice( + &u32::try_from(self.links.len()) + .unwrap_or(u32::MAX) + .to_be_bytes(), + ); + for (peer, status) in &self.links { + push_str(&mut out, peer); + out.push(status.tag()); + } + out + } + + /// Decode canonical payload bytes, refusing anything else: another + /// domain, trailing bytes, unsorted or repeated peers, a link to the + /// observer itself, an unknown status or a count that does not fit. + pub fn decode(bytes: &[u8]) -> Option { + let mut reader = Reader { + rest: bytes.strip_prefix(OBSERVATION_DOMAIN)?, + }; + let observer = reader.string()?; + let scope = reader.string()?; + let observed_at = reader.u64()?; + let expires_at = reader.u64()?; + let count = reader.u32()?; + let mut links = BTreeMap::new(); + let mut previous: Option = None; + for _ in 0..count { + let peer = reader.string()?; + let status = LinkStatus::from_tag(*reader.take(1)?.first()?)?; + if peer == observer || previous.as_ref().is_some_and(|p| *p >= peer) { + return None; + } + previous = Some(peer.clone()); + links.insert(peer, status); + } + if !reader.rest.is_empty() || observer.is_empty() { + return None; + } + Some(Self { + observer, + scope, + observed_at, + expires_at, + links, + }) + } +} + +/// Where the topology comes from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RoutingMode { + /// Signed, expiring observations. + Dynamic, + /// Only the explicit static links (the rollback). + Static, +} + +/// Local routing policy. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RoutingPolicy { + /// Dynamic or static. + pub mode: RoutingMode, + /// The longest lifetime an observation may claim. + pub max_ttl: LogicalTime, + /// How old a peer's own observation may get before it is due for + /// validation again. + pub revalidate_after: LogicalTime, + /// The peers this server expects to know about. + pub configured_peers: BTreeSet, + /// The static links used in [`RoutingMode::Static`]. + pub static_links: BTreeSet, +} + +/// Why an observation was refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Refusal { + /// The B32 gate refused the envelope. + Gate(RejectReason), + /// The payload is not a canonical observation. + Malformed, + /// The observation names an observer other than its signer. + ObserverMismatch, + /// The observation is for another scope than its envelope or state. + ScopeMismatch, + /// The observation time is not the envelope's issue time. + TimeMismatch, + /// The expiry is not after the observation time. + BadExpiry, + /// The expiry is further out than the policy allows. + TtlTooLong, + /// A newer (or the same) observation from this observer is held. + Superseded, + /// A different observation with the same time is held. + Conflict, +} + +/// One scope's routing state. +#[derive(Debug, Clone)] +pub struct RoutingState { + scope: String, + gate: IngestGate, + policy: RoutingPolicy, + latest: BTreeMap, +} + +/// What current observations say, with the gaps named. It never claims +/// to be the whole graph. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PartialTopology { + /// Links some current statement says are up. + pub links: BTreeSet, + /// Links some current statement says are down. + pub down: BTreeSet, + /// Observers with a current statement. + pub current_observers: BTreeSet, + /// Observers whose latest statement has expired. + pub stale_observers: BTreeSet, + /// Configured peers that no current statement mentions. + pub unobserved: BTreeSet, +} + +impl PartialTopology { + /// Peers known to be up: current observers and the peers their + /// up links reach. + pub fn reachable(&self) -> BTreeSet { + let mut out = self.current_observers.clone(); + out.extend(self.links.iter().flat_map(|(a, b)| [a.clone(), b.clone()])); + out + } +} + +impl RoutingState { + /// Routing state for `scope`, admitting through `gate` under `policy`. + pub const fn new(scope: String, gate: IngestGate, policy: RoutingPolicy) -> Self { + Self { + scope, + gate, + policy, + latest: BTreeMap::new(), + } + } + + /// Switch between dynamic observations and the static links. + pub const fn set_mode(&mut self, mode: RoutingMode) { + self.policy.mode = mode; + } + + /// The observation held for `observer`, current or stale. + pub fn observation(&self, observer: &str) -> Option<&RouteObservation> { + self.latest.get(observer) + } + + /// Admit one observation envelope at `now`. + pub fn ingest( + &mut self, + path: IngressPath, + envelope: &Envelope, + now: LogicalTime, + ) -> Result<(), Refusal> { + let admission = self + .gate + .admit(path, envelope, now) + .map_err(Refusal::Gate)?; + let observation = RouteObservation::decode(&envelope.payload).ok_or(Refusal::Malformed)?; + if observation.observer != admission.signer { + return Err(Refusal::ObserverMismatch); + } + if observation.scope != admission.scope || observation.scope != self.scope { + return Err(Refusal::ScopeMismatch); + } + if observation.observed_at != envelope.issued_at { + return Err(Refusal::TimeMismatch); + } + if observation.expires_at <= observation.observed_at { + return Err(Refusal::BadExpiry); + } + if observation.expires_at - observation.observed_at > self.policy.max_ttl { + return Err(Refusal::TtlTooLong); + } + if let Some(held) = self.latest.get(&observation.observer) { + if held.observed_at > observation.observed_at || *held == observation { + return Err(Refusal::Superseded); + } + if held.observed_at == observation.observed_at { + return Err(Refusal::Conflict); + } + } + self.latest + .insert(observation.observer.clone(), observation); + Ok(()) + } + + /// The topology at `now`. + pub fn topology(&self, now: LogicalTime) -> PartialTopology { + let mut topology = PartialTopology::default(); + match self.policy.mode { + RoutingMode::Static => topology.links.clone_from(&self.policy.static_links), + RoutingMode::Dynamic => { + for (observer, observation) in &self.latest { + if now >= observation.expires_at { + topology.stale_observers.insert(observer.clone()); + continue; + } + topology.current_observers.insert(observer.clone()); + for (peer, status) in &observation.links { + let link = (observer.clone(), peer.clone()); + match status { + LinkStatus::Reachable => topology.links.insert(link), + LinkStatus::Unreachable => topology.down.insert(link), + }; + } + } + } + } + let mentioned: BTreeSet<&PeerId> = topology + .links + .iter() + .chain(&topology.down) + .flat_map(|(a, b)| [a, b]) + .chain(&topology.current_observers) + .collect(); + topology.unobserved = self + .policy + .configured_peers + .iter() + .filter(|peer| !mentioned.contains(peer)) + .cloned() + .collect(); + topology + } + + /// Configured peers due for validation at `now`: no observation of + /// their own, an expired one, or one older than the revalidation + /// interval. Static mode validates nothing. + pub fn validation_due(&self, now: LogicalTime) -> BTreeSet { + if self.policy.mode == RoutingMode::Static { + return BTreeSet::new(); + } + self.policy + .configured_peers + .iter() + .filter(|peer| { + self.latest.get(*peer).is_none_or(|o| { + now >= o.expires_at + || now >= o.observed_at.saturating_add(self.policy.revalidate_after) + }) + }) + .cloned() + .collect() + } + + /// Drop every observation expired at `now`; returns how many. + pub fn prune(&mut self, now: LogicalTime) -> usize { + let before = self.latest.len(); + self.latest.retain(|_, o| now < o.expires_at); + before - self.latest.len() + } +} + +/// What changed between two topologies. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct TopologyChange { + /// Peers up now that were not up before. + pub appeared: BTreeSet, + /// Peers up before that a current observer now reports down and no + /// current observer reaches. + pub vanished: BTreeSet, + /// Peers up before that nothing current speaks for any more. + pub lost_sight: BTreeSet, + /// Observers whose statements went stale. + pub went_stale: BTreeSet, + /// Links up now that were not before. + pub links_added: BTreeSet, + /// Links up before that are not now. + pub links_lost: BTreeSet, +} + +impl TopologyChange { + /// Whether nothing changed that affects fan-out. + pub fn is_empty(&self) -> bool { + self.appeared.is_empty() + && self.vanished.is_empty() + && self.lost_sight.is_empty() + && self.went_stale.is_empty() + && self.links_added.is_empty() + && self.links_lost.is_empty() + } +} + +/// Compare two topologies. +pub fn changes(before: &PartialTopology, after: &PartialTopology) -> TopologyChange { + let up_before = before.reachable(); + let up_after = after.reachable(); + let reported_down: BTreeSet<&PeerId> = after.down.iter().map(|(_, peer)| peer).collect(); + let gone: BTreeSet = up_before.difference(&up_after).cloned().collect(); + let (vanished, lost_sight) = gone + .into_iter() + .partition(|peer| reported_down.contains(peer)); + TopologyChange { + appeared: up_after.difference(&up_before).cloned().collect(), + vanished, + lost_sight, + went_stale: after + .stale_observers + .difference(&before.stale_observers) + .cloned() + .collect(), + links_added: after.links.difference(&before.links).cloned().collect(), + links_lost: before.links.difference(&after.links).cloned().collect(), + } +} diff --git a/pkgs/id/crates/id-sync/tests/federation_b23.rs b/pkgs/id/crates/id-sync/tests/federation_b23.rs new file mode 100644 index 0000000000..e38623ceef --- /dev/null +++ b/pkgs/id/crates/id-sync/tests/federation_b23.rs @@ -0,0 +1,632 @@ +//! B23 golden and model test: routing-state freshness, periodic +//! validation and change detection (#10251, statements S1.73-S1.76). +//! +//! Oracle: **golden** — an expired or poisoned route observation is +//! never treated as current trusted topology, and the partial graph +//! stays explicitly partial. The observation encoding is pinned to hex +//! computed independently (Python, from the documented layout), and a +//! fixed fixture of signed observations is replayed step by step against +//! expected outcomes and topologies written out by hand. A reference +//! model then replays random streams of honest, poisoned, replayed, +//! reordered and expiring observations and predicts every admission and +//! every topology by brute force from the latest valid statement of each +//! observer. +//! +//! The slice modules are loaded by path: the federation roots record +//! them without declaring them (slice 9110-02), and B23 reaches B32 +//! through `super::`. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[path = "../src/federation/slices/b32_ingest_gate.rs"] +#[allow(dead_code)] +mod b32_ingest_gate; + +#[path = "../src/federation/slices/b23_routing_state.rs"] +mod b23_routing_state; + +use std::collections::{BTreeMap, BTreeSet}; + +use b23_routing_state::{ + LinkStatus, PartialTopology, PeerId, Refusal, RouteObservation, RoutingMode, RoutingPolicy, + RoutingState, TopologyChange, changes, +}; +use b32_ingest_gate::{ + Envelope, FreshnessWindow, IngestGate, IngressPath, RejectReason, SignerAuthorization, + sign_envelope, +}; +use ed25519_dalek::SigningKey; +use proptest::prelude::*; + +const SCOPE: &str = "routing/public"; +const NAMES: [&str; 4] = ["alice", "bob", "carol", "dave"]; + +fn key(name: &str) -> SigningKey { + let seed = NAMES + .iter() + .position(|n| *n == name) + .map_or(99, |i| u8::try_from(i).unwrap() + 1); + SigningKey::from_bytes(&[seed; 32]) +} + +fn gate() -> IngestGate { + let signer = |name: &str, scope: &str| SignerAuthorization { + identity: name.to_owned(), + verifying_key: key(name).verifying_key().to_bytes(), + scopes: BTreeSet::from([scope.to_owned()]), + }; + IngestGate::new( + vec![ + signer("alice", SCOPE), + signer("bob", SCOPE), + signer("carol", SCOPE), + signer("dave", "routing/other"), + ], + FreshnessWindow { + max_age: 1000, + max_future_skew: 5, + }, + ) +} + +fn policy() -> RoutingPolicy { + RoutingPolicy { + mode: RoutingMode::Dynamic, + max_ttl: 100, + revalidate_after: 40, + configured_peers: ["alice", "bob", "carol", "erin"] + .into_iter() + .map(String::from) + .collect(), + static_links: BTreeSet::from([("alice".to_owned(), "erin".to_owned())]), + } +} + +fn state() -> RoutingState { + RoutingState::new(SCOPE.to_owned(), gate(), policy()) +} + +fn obs(observer: &str, at: u64, ttl: u64, links: &[(&str, LinkStatus)]) -> RouteObservation { + RouteObservation { + observer: observer.to_owned(), + scope: SCOPE.to_owned(), + observed_at: at, + expires_at: at + ttl, + links: links + .iter() + .map(|(peer, status)| ((*peer).to_owned(), *status)) + .collect(), + } +} + +fn envelope(signer: &str, o: &RouteObservation, event: u8) -> Envelope { + sign_envelope( + &key(signer), + signer, + &o.scope, + &o.encode(), + [event; 32], + o.observed_at, + ) +} + +fn set(items: &[&str]) -> BTreeSet { + items.iter().map(|s| (*s).to_owned()).collect() +} + +fn links(items: &[(&str, &str)]) -> BTreeSet<(PeerId, PeerId)> { + items + .iter() + .map(|(a, b)| ((*a).to_owned(), (*b).to_owned())) + .collect() +} + +use LinkStatus::{Reachable as Up, Unreachable as Down}; + +// ----- encoding -------------------------------------------------------- + +#[test] +fn the_payload_encoding_is_pinned() { + let o = obs("alice", 10, 50, &[("bob", Up), ("carol", Down)]); + assert_eq!(hex(&o.encode()), GOLDEN_PAYLOAD); + assert_eq!(RouteObservation::decode(&o.encode()), Some(o)); +} + +const GOLDEN_PAYLOAD: &str = "69642d73796e632f6232332d726f7574652d6f62736572766174696f6e2f763100000005616c6963650000000e726f7574696e672f7075626c6963000000000000000a000000000000003c0000000200000003626f6201000000056361726f6c02"; + +fn hex(bytes: &[u8]) -> String { + use std::fmt::Write as _; + bytes.iter().fold(String::new(), |mut out, b| { + write!(out, "{b:02x}").unwrap(); + out + }) +} + +#[test] +fn only_canonical_payloads_decode() { + let good = obs("alice", 10, 50, &[("bob", Up), ("carol", Down)]).encode(); + let decode = RouteObservation::decode; + assert!(decode(&good).is_some()); + + let mut trailing = good.clone(); + trailing.push(0); + assert_eq!(decode(&trailing), None); + assert_eq!(decode(&good[..good.len() - 1]), None); + + let mut bad_status = good.clone(); + *bad_status.last_mut().unwrap() = 3; + assert_eq!(decode(&bad_status), None); + + let mut domain = good; + domain[3] ^= 1; + assert_eq!(decode(&domain), None); + + // Hand-built: links out of order, repeated, to the observer itself, + // and an empty observer. + let raw = |observer: &str, peers: &[&str]| { + let mut out = b"id-sync/b23-route-observation/v1".to_vec(); + for s in [observer, SCOPE] { + out.extend_from_slice(&u32::try_from(s.len()).unwrap().to_be_bytes()); + out.extend_from_slice(s.as_bytes()); + } + out.extend_from_slice(&10u64.to_be_bytes()); + out.extend_from_slice(&60u64.to_be_bytes()); + out.extend_from_slice(&u32::try_from(peers.len()).unwrap().to_be_bytes()); + for p in peers { + out.extend_from_slice(&u32::try_from(p.len()).unwrap().to_be_bytes()); + out.extend_from_slice(p.as_bytes()); + out.push(1); + } + out + }; + assert!(decode(&raw("alice", &["bob", "carol"])).is_some()); + assert_eq!(decode(&raw("alice", &["carol", "bob"])), None); + assert_eq!(decode(&raw("alice", &["bob", "bob"])), None); + assert_eq!(decode(&raw("alice", &["alice"])), None); + assert_eq!(decode(&raw("", &["bob"])), None); + // A count larger than the links present. + let mut short = raw("alice", &["bob"]); + let at = short.len() - (4 + 3 + 1) - 4; + short[at + 3] = 2; + assert_eq!(decode(&short), None); +} + +// ----- golden fixture ---------------------------------------------------- + +#[test] +fn the_fixture_replays_to_the_expected_topologies() { + let mut s = state(); + let path = IngressPath::Remote; + + // Nothing observed: everything configured is unobserved and due. + assert_eq!( + s.topology(0), + PartialTopology { + unobserved: set(&["alice", "bob", "carol", "erin"]), + ..PartialTopology::default() + } + ); + assert_eq!(s.validation_due(0), set(&["alice", "bob", "carol", "erin"])); + + let a1 = obs("alice", 10, 50, &[("bob", Up), ("carol", Down)]); + assert_eq!(s.ingest(path, &envelope("alice", &a1, 1), 10), Ok(())); + let b1 = obs("bob", 12, 30, &[("alice", Up), ("dave", Up)]); + assert_eq!(s.ingest(path, &envelope("bob", &b1, 2), 12), Ok(())); + let t20 = s.topology(20); + assert_eq!( + t20, + PartialTopology { + links: links(&[("alice", "bob"), ("bob", "alice"), ("bob", "dave")]), + down: links(&[("alice", "carol")]), + current_observers: set(&["alice", "bob"]), + stale_observers: set(&[]), + unobserved: set(&["erin"]), + } + ); + assert_eq!(t20.reachable(), set(&["alice", "bob", "dave"])); + assert_eq!(s.validation_due(20), set(&["carol", "erin"])); + + // Bob's statement expires at 42: it no longer vouches for anything. + let t45 = s.topology(45); + assert_eq!( + t45, + PartialTopology { + links: links(&[("alice", "bob")]), + down: links(&[("alice", "carol")]), + current_observers: set(&["alice"]), + stale_observers: set(&["bob"]), + unobserved: set(&["erin"]), + } + ); + assert_eq!( + changes(&t20, &t45), + TopologyChange { + lost_sight: set(&["dave"]), + went_stale: set(&["bob"]), + links_lost: links(&[("bob", "alice"), ("bob", "dave")]), + ..TopologyChange::default() + } + ); + // Alice is 35 old at 45: not yet due; at 50 she is. + assert_eq!(s.validation_due(45), set(&["bob", "carol", "erin"])); + assert_eq!( + s.validation_due(50), + set(&["alice", "bob", "carol", "erin"]) + ); + + // Alice re-probes: bob is now down, carol is back. + let a2 = obs("alice", 50, 50, &[("bob", Down), ("carol", Up)]); + assert_eq!(s.ingest(path, &envelope("alice", &a2, 3), 50), Ok(())); + let t55 = s.topology(55); + assert_eq!( + changes(&t45, &t55), + TopologyChange { + appeared: set(&["carol"]), + vanished: set(&["bob"]), + links_added: links(&[("alice", "carol")]), + links_lost: links(&[("alice", "bob")]), + ..TopologyChange::default() + } + ); + assert!(changes(&t55, &t55).is_empty()); + for only in [ + TopologyChange { + appeared: set(&["x"]), + ..TopologyChange::default() + }, + TopologyChange { + vanished: set(&["x"]), + ..TopologyChange::default() + }, + TopologyChange { + lost_sight: set(&["x"]), + ..TopologyChange::default() + }, + TopologyChange { + went_stale: set(&["x"]), + ..TopologyChange::default() + }, + TopologyChange { + links_added: links(&[("x", "y")]), + ..TopologyChange::default() + }, + TopologyChange { + links_lost: links(&[("x", "y")]), + ..TopologyChange::default() + }, + ] { + assert!(!only.is_empty(), "{only:?}"); + } + + // The older statement arriving late changes nothing. + assert_eq!( + s.ingest(path, &envelope("alice", &a1, 4), 55), + Err(Refusal::Superseded) + ); + let mut same_time = a2; + same_time.links.insert("dave".to_owned(), Up); + assert_eq!( + s.ingest(path, &envelope("alice", &same_time, 5), 55), + Err(Refusal::Conflict) + ); + assert_eq!(s.topology(55), t55); + + // Everything expires: no current link survives, and pruning drops it. + let t200 = s.topology(200); + assert!(t200.links.is_empty() && t200.down.is_empty()); + assert_eq!(t200.stale_observers, set(&["alice", "bob"])); + assert_eq!(t200.unobserved, set(&["alice", "bob", "carol", "erin"])); + assert_eq!(s.prune(200), 2); + assert_eq!(s.topology(200).stale_observers, set(&[])); +} + +#[test] +fn poisoned_observations_never_enter_the_topology() { + let mut s = state(); + let path = IngressPath::Remote; + let honest = obs("alice", 10, 50, &[("bob", Up)]); + let try_it = |s: &mut RoutingState, e: &Envelope| s.ingest(path, e, 12); + + let mut unsigned = envelope("alice", &honest, 1); + unsigned.signature = None; + assert_eq!( + try_it(&mut s, &unsigned), + Err(Refusal::Gate(RejectReason::Unsigned)) + ); + + // Bob's key claiming to be alice. + let impostor = sign_envelope(&key("bob"), "alice", SCOPE, &honest.encode(), [2; 32], 10); + assert!(matches!( + try_it(&mut s, &impostor), + Err(Refusal::Gate(RejectReason::SignerMismatch { .. })) + )); + + // Bob signing a statement about alice's links. + assert_eq!( + try_it(&mut s, &envelope("bob", &honest, 3)), + Err(Refusal::ObserverMismatch) + ); + + // Bytes changed in transit. + let mut tampered = envelope("alice", &honest, 4); + tampered.payload[40] ^= 1; + assert_eq!( + try_it(&mut s, &tampered), + Err(Refusal::Gate(RejectReason::SemanticInvalid)) + ); + + // Signed garbage. + let garbage = sign_envelope(&key("alice"), "alice", SCOPE, b"not a route", [5; 32], 10); + assert_eq!(try_it(&mut s, &garbage), Err(Refusal::Malformed)); + + // Payload scope differs from the envelope's. + let mut other_scope = honest.clone(); + other_scope.scope = "routing/other".to_owned(); + let e = sign_envelope( + &key("alice"), + "alice", + SCOPE, + &other_scope.encode(), + [6; 32], + 10, + ); + assert_eq!(try_it(&mut s, &e), Err(Refusal::ScopeMismatch)); + + // Dave may publish only for another scope. + let mut daves = obs("dave", 10, 50, &[("bob", Up)]); + assert!(matches!( + try_it(&mut s, &envelope("dave", &daves, 7)), + Err(Refusal::Gate(RejectReason::NotAuthorized { .. })) + )); + daves.scope = "routing/other".to_owned(); + assert_eq!( + try_it(&mut s, &envelope("dave", &daves, 8)), + Err(Refusal::ScopeMismatch) + ); + + // Time and expiry. + let e = sign_envelope(&key("alice"), "alice", SCOPE, &honest.encode(), [9; 32], 11); + assert_eq!(try_it(&mut s, &e), Err(Refusal::TimeMismatch)); + assert_eq!( + try_it(&mut s, &envelope("alice", &obs("alice", 10, 0, &[]), 10)), + Err(Refusal::BadExpiry) + ); + assert_eq!( + try_it(&mut s, &envelope("alice", &obs("alice", 10, 101, &[]), 11)), + Err(Refusal::TtlTooLong) + ); + + // Too old for the gate, and dated in the future. + assert_eq!( + s.ingest(path, &envelope("alice", &honest, 12), 1011), + Err(Refusal::Gate(RejectReason::Stale)) + ); + assert_eq!( + s.ingest(path, &envelope("alice", &obs("alice", 20, 50, &[]), 13), 14), + Err(Refusal::Gate(RejectReason::FutureSkew)) + ); + + assert_eq!(s.topology(12), state().topology(12)); + + // The honest one is accepted once; its replay is refused by the gate. + let e = envelope("alice", &honest, 14); + assert_eq!(try_it(&mut s, &e), Ok(())); + assert_eq!(try_it(&mut s, &e), Err(Refusal::Gate(RejectReason::Replay))); + assert_eq!(s.topology(12).links, links(&[("alice", "bob")])); +} + +#[test] +fn static_mode_ignores_observations_and_validates_nothing() { + let mut s = state(); + let a = obs("alice", 10, 50, &[("bob", Up)]); + s.ingest(IngressPath::Local, &envelope("alice", &a, 1), 10) + .unwrap(); + s.set_mode(RoutingMode::Static); + assert_eq!( + s.topology(20), + PartialTopology { + links: links(&[("alice", "erin")]), + unobserved: set(&["bob", "carol"]), + ..PartialTopology::default() + } + ); + assert!(s.validation_due(20).is_empty()); + // Dynamic state still expires underneath. + assert_eq!(s.prune(60), 1); + s.set_mode(RoutingMode::Dynamic); + assert!(s.topology(20).links.is_empty()); + assert_eq!(s.observation("alice"), None); +} + +#[test] +fn every_ingress_path_faces_the_same_checks() { + for (i, path) in IngressPath::ALL.into_iter().enumerate() { + let mut s = state(); + let event = u8::try_from(i).unwrap(); + let honest = obs("alice", 10, 50, &[("bob", Up)]); + assert_eq!( + s.ingest(path, &envelope("bob", &honest, event), 12), + Err(Refusal::ObserverMismatch) + ); + assert_eq!( + s.ingest(path, &envelope("alice", &honest, event + 10), 12), + Ok(()) + ); + } +} + +// ----- reference model ----------------------------------------------------- + +#[derive(Debug, Clone, Copy)] +enum Poison { + None, + Unsigned, + ObserverMismatch, + Tampered, + TimeMismatch, + TtlTooLong, + Replay, +} + +#[derive(Debug, Clone)] +struct Step { + advance: u64, + observer: usize, + age: u64, + ttl: u64, + links: Vec<(usize, bool)>, + poison: Poison, +} + +fn step() -> impl Strategy { + ( + 0u64..20, + 0usize..3, + 0u64..15, + 1u64..60, + prop::collection::vec((0usize..5, any::()), 0..4), + prop_oneof![ + 8 => Just(Poison::None), + 1 => Just(Poison::Unsigned), + 1 => Just(Poison::ObserverMismatch), + 1 => Just(Poison::Tampered), + 1 => Just(Poison::TimeMismatch), + 1 => Just(Poison::TtlTooLong), + 1 => Just(Poison::Replay), + ], + ) + .prop_map(|(advance, observer, age, ttl, links, poison)| Step { + advance, + observer, + age, + ttl, + links, + poison, + }) +} + +const OBSERVERS: [&str; 3] = ["alice", "bob", "carol"]; +const TARGETS: [&str; 5] = ["alice", "bob", "carol", "dave", "erin"]; + +fn expected_topology(held: &BTreeMap, now: u64) -> PartialTopology { + let mut t = PartialTopology::default(); + for o in held.values() { + if now >= o.expires_at { + t.stale_observers.insert(o.observer.clone()); + continue; + } + t.current_observers.insert(o.observer.clone()); + for (peer, status) in &o.links { + let link = (o.observer.clone(), peer.clone()); + if *status == Up { + t.links.insert(link); + } else { + t.down.insert(link); + } + } + } + for peer in &policy().configured_peers { + let seen = t.current_observers.contains(peer) + || t.links + .iter() + .chain(&t.down) + .any(|(a, b)| a == peer || b == peer); + if !seen { + t.unobserved.insert(peer.clone()); + } + } + t +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 96, ..ProptestConfig::default() })] + + #[test] + fn admissions_and_topologies_match_the_reference(steps in prop::collection::vec(step(), 1..40)) { + let mut s = state(); + let mut held: BTreeMap = BTreeMap::new(); + let mut now = 20u64; + let mut last: Option = None; + let mut previous = s.topology(now); + for (i, st) in steps.iter().enumerate() { + now += st.advance; + let observer = OBSERVERS[st.observer]; + let mut o = RouteObservation { + observer: observer.to_owned(), + scope: SCOPE.to_owned(), + observed_at: now - st.age, + expires_at: now - st.age + st.ttl, + links: BTreeMap::new(), + }; + for (target, up) in &st.links { + if TARGETS[*target] != observer { + o.links.insert(TARGETS[*target].to_owned(), if *up { Up } else { Down }); + } + } + let event = u8::try_from(i).unwrap(); + let (env, want): (Envelope, Result<(), Refusal>) = match st.poison { + Poison::Replay if last.is_some() => { + (last.clone().unwrap(), Err(Refusal::Gate(RejectReason::Replay))) + } + Poison::None | Poison::Replay => { + let want = match held.get(observer) { + Some(h) if h.observed_at > o.observed_at || *h == o => Err(Refusal::Superseded), + Some(h) if h.observed_at == o.observed_at => Err(Refusal::Conflict), + _ => Ok(()), + }; + (envelope(observer, &o, event), want) + } + Poison::Unsigned => { + let mut e = envelope(observer, &o, event); + e.signature = None; + (e, Err(Refusal::Gate(RejectReason::Unsigned))) + } + Poison::ObserverMismatch => { + let other = OBSERVERS[(st.observer + 1) % 3]; + (envelope(other, &o, event), Err(Refusal::ObserverMismatch)) + } + Poison::Tampered => { + let mut e = envelope(observer, &o, event); + let n = e.payload.len(); + e.payload[n - 1] ^= 1; + (e, Err(Refusal::Gate(RejectReason::SemanticInvalid))) + } + Poison::TimeMismatch => { + let e = sign_envelope(&key(observer), observer, SCOPE, &o.encode(), [event; 32], o.observed_at + 1); + (e, Err(Refusal::TimeMismatch)) + } + Poison::TtlTooLong => { + o.expires_at = o.observed_at + 101; + (envelope(observer, &o, event), Err(Refusal::TtlTooLong)) + } + }; + let got = s.ingest(IngressPath::Remote, &env, now); + prop_assert_eq!(&got, &want, "step {} {:?}", i, st); + if got.is_ok() { + held.insert(observer.to_owned(), o); + last = Some(env); + } + let topology = s.topology(now); + prop_assert_eq!(&topology, &expected_topology(&held, now)); + // Nothing expired or refused contributes a link. + for (a, _) in topology.links.iter().chain(&topology.down) { + prop_assert!(now < held[a].expires_at); + } + let change = changes(&previous, &topology); + let gone: BTreeSet = + previous.reachable().difference(&topology.reachable()).cloned().collect(); + let mut split = change.vanished.clone(); + split.extend(change.lost_sight.iter().cloned()); + prop_assert_eq!(split, gone); + prop_assert!(change.vanished.is_disjoint(&change.lost_sight)); + prop_assert!(change.appeared.is_disjoint(&previous.reachable())); + prop_assert!(changes(&topology, &topology).is_empty()); + let due = s.validation_due(now); + for peer in &policy().configured_peers { + let fresh = held.get(peer).is_some_and(|h| now < h.expires_at && now < h.observed_at + 40); + prop_assert_eq!(due.contains(peer), !fresh); + } + previous = topology; + } + } +}