From 94763a82c77509fda89b5072c41ee62be6a9620a Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 12:39:35 -0600 Subject: [PATCH] id-sync: B31 core directional peer-class behavior and unknown-peer default (#10186) --- .../src/federation/slices/b31_peer_classes.rs | 287 ++++++++++++++ .../id/crates/id-sync/tests/federation_b31.rs | 359 ++++++++++++++++++ 2 files changed, 646 insertions(+) create mode 100644 pkgs/id/crates/id-sync/src/federation/slices/b31_peer_classes.rs create mode 100644 pkgs/id/crates/id-sync/tests/federation_b31.rs diff --git a/pkgs/id/crates/id-sync/src/federation/slices/b31_peer_classes.rs b/pkgs/id/crates/id-sync/src/federation/slices/b31_peer_classes.rs new file mode 100644 index 0000000000..fa7e93c940 --- /dev/null +++ b/pkgs/id/crates/id-sync/src/federation/slices/b31_peer_classes.rs @@ -0,0 +1,287 @@ +//! Core directional peer-class behavior and the unknown-peer default +//! (slice B31, #10186; design: part-b versioned design, wire/data model, +//! statements S1.1–S1.11). +//! +//! Trust classes are directional policy labels, never cryptographic +//! facts. This module is the pure policy matrix: given a peer's +//! configured [`PeerPolicy`], a direction, an operation, and — for +//! inbound acceptance — the evidence produced by the universal +//! signed-and-validated gate, it decides whether the operation is +//! allowed. It performs no I/O and no cryptography itself; the gate +//! (slice B32) supplies the evidence, this matrix supplies the policy. +//! +//! The rules, exactly as settled in the design: +//! +//! - `fully_trusted` is configured bidirectional policy, never a +//! bypass: it permits only the operations explicitly configured for +//! the peer, and inbound acceptance still requires the full gate +//! (valid signature, authorized signer, semantic validation, scope +//! authorization) to pass. +//! - `send_only` permits local outbound sends and rejects +//! peer-originated accepted data, whatever the gate evidence says. +//! - `accept_signed_from` permits configured inbound objects only +//! after the full gate passes; it grants no outbound send by itself. +//! - An unknown peer — no policy at all, an explicit +//! [`PeerClass::Unknown`] policy, or a policy outside its validity +//! window — defaults to no acceptance and no send. +//! - No class grants query relay, completeness authority, or +//! cross-tenant access by itself: relay requires a separate, +//! explicit relay grant recorded on the policy, and the other two +//! are never granted by a peer class. +//! +//! Class changes are versioned per peer ([`PeerPolicy::policy_version`]); +//! this matrix evaluates one policy snapshot at one instant, so a +//! demotion or revocation takes effect as soon as the caller evaluates +//! against the new snapshot. + +use std::collections::BTreeSet; + +/// A peer's trust class: a directional policy label, never a +/// cryptographic fact. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum PeerClass { + /// Broad configured operations in both directions, subject to the + /// configured operation set and — inbound — the full gate. Never + /// a validation bypass. + FullyTrusted, + /// Local outbound sends only; peer-originated data is never + /// accepted. + SendOnly, + /// Inbound acceptance only, and only for objects that pass the + /// full signed-and-validated gate. + AcceptSignedFrom, + /// No configured trust. The restrictive default for any peer the + /// local node has no policy for. + Unknown, +} + +/// The direction an operation moves data, relative to the local node. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Direction { + /// Peer-originated data arriving at the local node (acceptance). + Inbound, + /// Locally originated data sent to the peer. + Outbound, +} + +/// An operation the peer-class matrix can decide. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Operation { + /// Accept a peer-originated signed object into local accepted + /// data. Inbound only. + AcceptData, + /// Send a locally originated object to the peer. Outbound only. + SendData, + /// Relay a third party's query through / to this peer. Never + /// granted by a class alone; needs a separate relay grant. + QueryRelay, + /// Treat the peer as authoritative for completeness claims. Never + /// granted by a peer class. + CompletenessAuthority, + /// Access across a tenant boundary via this peer. Never granted + /// by a peer class. + CrossTenantAccess, +} + +impl Operation { + /// The only direction in which this operation is meaningful. + #[must_use] + pub const fn direction(self) -> Direction { + match self { + Self::AcceptData => Direction::Inbound, + Self::SendData | Self::QueryRelay => Direction::Outbound, + Self::CompletenessAuthority | Self::CrossTenantAccess => Direction::Inbound, + } + } +} + +/// Evidence from the universal signed-and-validated gate for one +/// inbound object. Every field must hold before any class may accept +/// the object; `fully_trusted` does not waive any of them. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +pub struct GateEvidence { + /// The object's signature verified under the claimed signer's key. + pub signature_valid: bool, + /// The signer is the peer (or an identity the peer is bound to) + /// and is authorized for this kind of object. + pub signer_authorized: bool, + /// The object passed semantic validation for its type. + pub semantically_valid: bool, + /// The object is inside the scope the peer is configured for. + pub scope_authorized: bool, +} + +impl GateEvidence { + /// The all-pass evidence: every gate check held. + #[must_use] + pub const fn all_pass() -> Self { + Self { + signature_valid: true, + signer_authorized: true, + semantically_valid: true, + scope_authorized: true, + } + } + + /// Whether every gate check held. + #[must_use] + pub const fn passed(&self) -> bool { + self.signature_valid + && self.signer_authorized + && self.semantically_valid + && self.scope_authorized + } +} + +/// One peer's configured policy snapshot (design `PeerPolicy`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PeerPolicy { + /// The peer this policy governs (an opaque local identifier). + pub peer_id: String, + /// The peer's trust class. + pub class: PeerClass, + /// The operations explicitly configured for this peer. A class + /// permits at most these; an operation absent from this set is + /// denied even for `fully_trusted`. + pub operations: BTreeSet, + /// Separate, explicit relay grant. No class sets this by itself; + /// it is recorded only when relay was granted independently of + /// the peer's class. + pub relay_granted: bool, + /// The scope this policy applies to (an opaque local scope id). + pub scope: String, + /// Monotonic per-peer policy version; a class change or demotion + /// is a new version, never an in-place edit of a snapshot. + pub policy_version: u64, + /// First instant (unix seconds) the policy is in force, if bounded. + pub valid_from: Option, + /// Instant (unix seconds) at which the policy stops being in + /// force, if bounded. At or after it the peer is unknown. + pub expires_at: Option, +} + +impl PeerPolicy { + /// Whether the policy is in force at `now` (unix seconds). + #[must_use] + pub const fn in_force_at(&self, now: u64) -> bool { + if let Some(from) = self.valid_from + && now < from + { + return false; + } + if let Some(until) = self.expires_at + && now >= until + { + return false; + } + true + } +} + +/// The matrix's verdict for one (peer, operation, evidence) question. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Decision { + /// The operation may proceed. + Allow, + /// The operation must not proceed. + Deny(DenyReason), +} + +/// Why the matrix denied an operation. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum DenyReason { + /// No policy for the peer, an explicit unknown class, or a policy + /// outside its validity window: the restrictive default. + UnknownPeer, + /// The operation is not in the peer's configured operation set. + NotConfigured, + /// The peer's class never permits this operation in this + /// direction (e.g. `send_only` inbound, `accept_signed_from` + /// outbound). + ClassForbids, + /// Inbound acceptance was asked for without the full gate + /// passing. Applies to every class, `fully_trusted` included. + GateNotPassed, + /// The operation is one no peer class grants by itself (relay + /// without a separate grant, completeness authority, + /// cross-tenant access). + NotGrantedByClass, + /// The operation was evaluated in a direction it does not have. + WrongDirection, +} + +/// Decide one operation for one peer. +/// +/// `policy` is the peer's current policy snapshot, or `None` for a +/// peer the local node has no policy for (unknown). `gate` is the +/// gate evidence for the object in question; it is consulted only +/// for inbound acceptance and ignored for outbound sends, which are +/// locally originated and signed before admission by the local gate +/// on the producing side. `now` is unix seconds, used only for the +/// policy validity window. +#[must_use] +pub fn decide( + policy: Option<&PeerPolicy>, + operation: Operation, + direction: Direction, + gate: &GateEvidence, + now: u64, +) -> Decision { + if direction != operation.direction() { + return Decision::Deny(DenyReason::WrongDirection); + } + let Some(policy) = policy.filter(|p| p.in_force_at(now)) else { + return Decision::Deny(DenyReason::UnknownPeer); + }; + if policy.class == PeerClass::Unknown { + return Decision::Deny(DenyReason::UnknownPeer); + } + match operation { + Operation::AcceptData => decide_accept(policy, gate), + Operation::SendData => decide_send(policy), + Operation::QueryRelay => { + if policy.relay_granted { + Decision::Allow + } else { + Decision::Deny(DenyReason::NotGrantedByClass) + } + } + Operation::CompletenessAuthority | Operation::CrossTenantAccess => { + Decision::Deny(DenyReason::NotGrantedByClass) + } + } +} + +/// Inbound acceptance: class first, then configuration, then the +/// gate — the gate is never waived, for any class. +fn decide_accept(policy: &PeerPolicy, gate: &GateEvidence) -> Decision { + match policy.class { + PeerClass::SendOnly | PeerClass::Unknown => Decision::Deny(DenyReason::ClassForbids), + PeerClass::FullyTrusted | PeerClass::AcceptSignedFrom => { + if !policy.operations.contains(&Operation::AcceptData) { + Decision::Deny(DenyReason::NotConfigured) + } else if !gate.passed() { + Decision::Deny(DenyReason::GateNotPassed) + } else { + Decision::Allow + } + } + } +} + +/// Outbound send: `accept_signed_from` grants no send; the other +/// non-unknown classes send only when send is configured. +fn decide_send(policy: &PeerPolicy) -> Decision { + match policy.class { + PeerClass::AcceptSignedFrom | PeerClass::Unknown => { + Decision::Deny(DenyReason::ClassForbids) + } + PeerClass::FullyTrusted | PeerClass::SendOnly => { + if policy.operations.contains(&Operation::SendData) { + Decision::Allow + } else { + Decision::Deny(DenyReason::NotConfigured) + } + } + } +} diff --git a/pkgs/id/crates/id-sync/tests/federation_b31.rs b/pkgs/id/crates/id-sync/tests/federation_b31.rs new file mode 100644 index 0000000000..f668bd6367 --- /dev/null +++ b/pkgs/id/crates/id-sync/tests/federation_b31.rs @@ -0,0 +1,359 @@ +//! B31 golden test: core directional peer-class behavior and the +//! unknown-peer default (#10186, statements S1.1–S1.11). +//! +//! Oracle: golden — the policy matrix covers class × direction × +//! operation and the unknown defaults, and `fully_trusted` never +//! bypasses the gate. The verifier is the independent reference +//! state machine below (`reference_decide`): it is written directly +//! from the settled design statements, as a literal transition +//! table, and shares no code with the implementation under test. +//! The implementation is loaded by direct path because slice +//! 9110-09 — not this slice — wires the versioned public exports +//! after the leaf modules land (9110-02 registry rule). + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +#[path = "../src/federation/slices/b31_peer_classes.rs"] +mod b31; + +use std::collections::BTreeSet; + +use b31::{Decision, DenyReason, Direction, GateEvidence, Operation, PeerClass, PeerPolicy}; + +const NOW: u64 = 1_000; + +fn policy(class: PeerClass, operations: &[Operation]) -> PeerPolicy { + PeerPolicy { + peer_id: "peer-1".to_string(), + class, + operations: operations.iter().copied().collect::>(), + relay_granted: false, + scope: "scope-1".to_string(), + policy_version: 1, + valid_from: None, + expires_at: None, + } +} + +/// Independent reference state machine, from the design text: +/// +/// - unknown / no policy / out-of-window -> deny everything; +/// - accept: send_only forbids; fully_trusted and accept_signed_from +/// accept only when accept is configured AND every gate check +/// passed (fully_trusted never bypasses); +/// - send: accept_signed_from forbids; fully_trusted and send_only +/// send only when send is configured; +/// - relay: only a separate relay grant allows it, class never does; +/// - completeness authority / cross-tenant: class never grants; +/// - an operation in the wrong direction is always denied. +fn reference_decide( + policy: Option<&PeerPolicy>, + operation: Operation, + direction: Direction, + gate: &GateEvidence, + now: u64, +) -> Decision { + let direction_ok = matches!( + (operation, direction), + (Operation::AcceptData, Direction::Inbound) + | (Operation::SendData, Direction::Outbound) + | (Operation::QueryRelay, Direction::Outbound) + | (Operation::CompletenessAuthority, Direction::Inbound) + | (Operation::CrossTenantAccess, Direction::Inbound) + ); + if !direction_ok { + return Decision::Deny(DenyReason::WrongDirection); + } + let Some(p) = policy else { + return Decision::Deny(DenyReason::UnknownPeer); + }; + if p.valid_from.is_some_and(|from| now < from) + || p.expires_at.is_some_and(|until| now >= until) + || p.class == PeerClass::Unknown + { + return Decision::Deny(DenyReason::UnknownPeer); + } + let gate_ok = gate.signature_valid + && gate.signer_authorized + && gate.semantically_valid + && gate.scope_authorized; + match (p.class, operation) { + (_, Operation::CompletenessAuthority | Operation::CrossTenantAccess) => { + Decision::Deny(DenyReason::NotGrantedByClass) + } + (_, Operation::QueryRelay) => { + if p.relay_granted { + Decision::Allow + } else { + Decision::Deny(DenyReason::NotGrantedByClass) + } + } + (PeerClass::SendOnly, Operation::AcceptData) => Decision::Deny(DenyReason::ClassForbids), + (PeerClass::AcceptSignedFrom, Operation::SendData) => { + Decision::Deny(DenyReason::ClassForbids) + } + (PeerClass::FullyTrusted | PeerClass::AcceptSignedFrom, Operation::AcceptData) => { + if !p.operations.contains(&Operation::AcceptData) { + Decision::Deny(DenyReason::NotConfigured) + } else if !gate_ok { + Decision::Deny(DenyReason::GateNotPassed) + } else { + Decision::Allow + } + } + (PeerClass::FullyTrusted | PeerClass::SendOnly, Operation::SendData) => { + if p.operations.contains(&Operation::SendData) { + Decision::Allow + } else { + Decision::Deny(DenyReason::NotConfigured) + } + } + (PeerClass::Unknown, _) => Decision::Deny(DenyReason::UnknownPeer), + } +} + +const CLASSES: [PeerClass; 4] = [ + PeerClass::FullyTrusted, + PeerClass::SendOnly, + PeerClass::AcceptSignedFrom, + PeerClass::Unknown, +]; +const OPERATIONS: [Operation; 5] = [ + Operation::AcceptData, + Operation::SendData, + Operation::QueryRelay, + Operation::CompletenessAuthority, + Operation::CrossTenantAccess, +]; +const DIRECTIONS: [Direction; 2] = [Direction::Inbound, Direction::Outbound]; + +fn gate_variants() -> Vec { + let pass = GateEvidence::all_pass(); + vec![ + pass, + GateEvidence::default(), + GateEvidence { + signature_valid: false, + ..pass + }, + GateEvidence { + signer_authorized: false, + ..pass + }, + GateEvidence { + semantically_valid: false, + ..pass + }, + GateEvidence { + scope_authorized: false, + ..pass + }, + ] +} + +#[test] +fn matrix_matches_reference_for_every_combination() { + let configured_sets: [&[Operation]; 3] = [ + &[], + &[Operation::AcceptData], + &[Operation::AcceptData, Operation::SendData], + ]; + for class in CLASSES { + for configured in configured_sets { + for relay_granted in [false, true] { + let mut p = policy(class, configured); + p.relay_granted = relay_granted; + for operation in OPERATIONS { + for direction in DIRECTIONS { + for gate in gate_variants() { + let expected = + reference_decide(Some(&p), operation, direction, &gate, NOW); + let actual = b31::decide(Some(&p), operation, direction, &gate, NOW); + assert_eq!( + actual, expected, + "class={class:?} configured={configured:?} relay={relay_granted} \ + op={operation:?} dir={direction:?} gate={gate:?}" + ); + } + } + } + } + } + } +} + +#[test] +fn no_policy_is_unknown_and_denies_everything() { + for operation in OPERATIONS { + for direction in DIRECTIONS { + assert_eq!( + b31::decide(None, operation, direction, &GateEvidence::all_pass(), NOW), + if direction == operation.direction() { + Decision::Deny(DenyReason::UnknownPeer) + } else { + Decision::Deny(DenyReason::WrongDirection) + }, + "op={operation:?} dir={direction:?}" + ); + } + } +} + +#[test] +fn fully_trusted_never_bypasses_the_gate() { + let p = policy( + PeerClass::FullyTrusted, + &[Operation::AcceptData, Operation::SendData], + ); + // Every single gate failure, and total gate failure, deny + // acceptance even for a fully trusted, fully configured peer. + for gate in gate_variants().into_iter().skip(1) { + assert_eq!( + b31::decide( + Some(&p), + Operation::AcceptData, + Direction::Inbound, + &gate, + NOW + ), + Decision::Deny(DenyReason::GateNotPassed), + "gate={gate:?}" + ); + } + assert_eq!( + b31::decide( + Some(&p), + Operation::AcceptData, + Direction::Inbound, + &GateEvidence::all_pass(), + NOW + ), + Decision::Allow + ); +} + +#[test] +fn send_only_rejects_inbound_and_accept_signed_from_grants_no_send() { + let sender = policy( + PeerClass::SendOnly, + &[Operation::AcceptData, Operation::SendData], + ); + assert_eq!( + b31::decide( + Some(&sender), + Operation::AcceptData, + Direction::Inbound, + &GateEvidence::all_pass(), + NOW + ), + Decision::Deny(DenyReason::ClassForbids) + ); + let accepter = policy( + PeerClass::AcceptSignedFrom, + &[Operation::AcceptData, Operation::SendData], + ); + assert_eq!( + b31::decide( + Some(&accepter), + Operation::SendData, + Direction::Outbound, + &GateEvidence::all_pass(), + NOW + ), + Decision::Deny(DenyReason::ClassForbids) + ); +} + +#[test] +fn no_class_grants_relay_completeness_or_cross_tenant_by_itself() { + for class in CLASSES { + let p = policy( + class, + &[ + Operation::AcceptData, + Operation::SendData, + Operation::QueryRelay, + ], + ); + // An unknown peer is denied as unknown, before the + // not-granted-by-class reasons are even reached. + let expected = if class == PeerClass::Unknown { + DenyReason::UnknownPeer + } else { + DenyReason::NotGrantedByClass + }; + assert_eq!( + b31::decide( + Some(&p), + Operation::QueryRelay, + Direction::Outbound, + &GateEvidence::all_pass(), + NOW + ), + Decision::Deny(expected), + "class={class:?}" + ); + for operation in [ + Operation::CompletenessAuthority, + Operation::CrossTenantAccess, + ] { + assert_eq!( + b31::decide( + Some(&p), + operation, + Direction::Inbound, + &GateEvidence::all_pass(), + NOW + ), + Decision::Deny(expected), + "class={class:?} op={operation:?}" + ); + } + } + // A separate relay grant is the only route to relay, and it does + // not leak into the other never-by-class operations. + let mut p = policy(PeerClass::FullyTrusted, &[Operation::QueryRelay]); + p.relay_granted = true; + assert_eq!( + b31::decide( + Some(&p), + Operation::QueryRelay, + Direction::Outbound, + &GateEvidence::all_pass(), + NOW + ), + Decision::Allow + ); +} + +#[test] +fn policy_outside_its_validity_window_is_treated_as_unknown() { + let mut expired = policy( + PeerClass::FullyTrusted, + &[Operation::AcceptData, Operation::SendData], + ); + expired.expires_at = Some(NOW); + assert_eq!( + b31::decide( + Some(&expired), + Operation::SendData, + Direction::Outbound, + &GateEvidence::all_pass(), + NOW + ), + Decision::Deny(DenyReason::UnknownPeer) + ); + let mut future = expired.clone(); + future.expires_at = None; + future.valid_from = Some(NOW + 1); + assert_eq!( + b31::decide( + Some(&future), + Operation::AcceptData, + Direction::Inbound, + &GateEvidence::all_pass(), + NOW + ), + Decision::Deny(DenyReason::UnknownPeer) + ); +}