From f90e704cce6b3bb1af7e07569a8a65872db2e546 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 23:26:21 -0600 Subject: [PATCH] feat(id-sync): wire the chained-message relay gate into live ingest (#3796) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The validate-before-forward relay gate (part B, PR #10804) had no live call site: nothing fed arrivals through RelayGate::decide. Add relay_ingest, the receiving end of the ID-controlled forwarding path the gate's design finding prescribes (stock iroh-gossip forwards eagerly and cannot carry chained messages): - ChainedRelayProtocol: an Iroh protocol handler on the new /id-chained-relay/1 ALPN. Every frame is decoded strictly (duplicate JSON keys refused, like the envelope path) and run through RelayGate::decide before anything else happens to it. Only a Forward decision reaches the host's ChainedSink, in the forwarded form (origin envelope byte-identical, this relay's hop appended). Duplicate answers Reply::Duplicate; every other refusal answers Reply::Refused with the gate's reason. - forward_message: the sender half, mirroring envelope_net::deliver. - ChainedSink: the host seam — deliver locally, fan the forwarded message out to next peers with forward_message. Tests exercise issue #3796's acceptance at the live call site over real Iroh connections: origin -> bridge -> leaf exchange with an identical message ID and both hops in order; forged message refused at ingest and never delivered; non-member origin refused at ingest; duplicate arrival suppressed (delivered exactly once). Also updates the relay_gate module doc, which named this wiring as the remaining follow-on. What remains on #3796 is the frontier backing: a MembershipFrontier over the signed-graph membership state (open design), which replaces AllowlistFrontier without changing the gate or this wiring. Full id-sync lib suite: 225 passed, 0 failed. cargo fmt clean; clippy clean for the new module. --- pkgs/id/crates/id-sync/src/lib.rs | 1 + pkgs/id/crates/id-sync/src/relay_gate.rs | 7 +- pkgs/id/crates/id-sync/src/relay_ingest.rs | 414 +++++++++++++++++++++ 3 files changed, 419 insertions(+), 3 deletions(-) create mode 100644 pkgs/id/crates/id-sync/src/relay_ingest.rs diff --git a/pkgs/id/crates/id-sync/src/lib.rs b/pkgs/id/crates/id-sync/src/lib.rs index f3b240bf2e..54fe5abf68 100644 --- a/pkgs/id/crates/id-sync/src/lib.rs +++ b/pkgs/id/crates/id-sync/src/lib.rs @@ -39,4 +39,5 @@ pub mod meta_client; pub mod protocol; pub mod registry; pub mod relay_gate; +pub mod relay_ingest; pub mod transfer; diff --git a/pkgs/id/crates/id-sync/src/relay_gate.rs b/pkgs/id/crates/id-sync/src/relay_gate.rs index 1827b6bbf0..b08aead16d 100644 --- a/pkgs/id/crates/id-sync/src/relay_gate.rs +++ b/pkgs/id/crates/id-sync/src/relay_gate.rs @@ -37,9 +37,10 @@ //! post-hoc ingest checks would propagate unsigned or unauthorized //! traffic before validation (#2035). The multi-node bridge test is //! in this module's tests (two gates chained origin -> bridge -> -//! leaf, plus the unauthorized-at-bridge stop). The remaining -//! follow-on slice is the live call-site wiring: feeding gossip/ -//! ingest arrivals through this gate and backing +//! leaf, plus the unauthorized-at-bridge stop). The live call-site +//! wiring has since landed in [`crate::relay_ingest`]: arrivals on +//! the chained-relay ALPN run through this gate before delivery or +//! forwarding. The remaining follow-on is backing //! [`MembershipFrontier`] with the signed-graph membership state. //! //! # Membership frontier diff --git a/pkgs/id/crates/id-sync/src/relay_ingest.rs b/pkgs/id/crates/id-sync/src/relay_ingest.rs new file mode 100644 index 0000000000..343be7fb37 --- /dev/null +++ b/pkgs/id/crates/id-sync/src/relay_ingest.rs @@ -0,0 +1,414 @@ +//! Live call-site wiring for the relay gate: phase 3 of the #2036 +//! messaging/relay protocol v1 (#3796), the ingest slice. +//! +//! The gate in [`crate::relay_gate`] is the only forwarding path for +//! chained messages, and its gate-verification finding stands: the +//! pinned `iroh-gossip` forwards eagerly before the application can +//! accept or reject, so stock gossip broadcast must not carry chained +//! messages. They arrive instead over direct Iroh connections on +//! [`CHAINED_RELAY_ALPN`], and this module is the receiving end. +//! +//! Every frame on that ALPN is decoded strictly (duplicate JSON keys +//! are refused, like the envelope path), then run through +//! [`RelayGate::decide`] BEFORE anything else happens to it. Only a +//! [`GateDecision::Forward`] reaches the host's [`ChainedSink`]; the +//! sink receives the forwarded form — origin envelope byte-identical, +//! this relay's hop appended — delivers it locally, and fans it out +//! to next peers with [`forward_message`]. Refusals map onto the +//! envelope transport's [`Reply`] vocabulary: a duplicate arrival +//! answers [`Reply::Duplicate`], every other refusal answers +//! [`Reply::Refused`] with the gate's reason, so a sender learns a +//! forged or unauthorized message will never succeed on retry. +//! +//! What remains after this slice is the frontier backing, not the +//! wiring: [`MembershipFrontier`](crate::relay_gate::MembershipFrontier) +//! is still satisfied by local stand-ins until the signed-graph +//! membership state lands (open design, recorded in +//! [`crate::relay_gate`]). + +use std::sync::{Arc, Mutex}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use iroh::{ + Endpoint, EndpointAddr, + endpoint::Connection, + protocol::{AcceptError, ProtocolHandler}, +}; + +use crate::chained_message::RelayedMessage; +use crate::envelope_net::{Reply, answer_frames, send}; +use crate::envelope_outbox::Outcome; +use crate::relay_gate::{GateDecision, GateRefusal, MembershipFrontier, RelayGate}; + +/// ALPN for chained-message relay. Within version 1 fields may be +/// added; removing or changing one needs `/id-chained-relay/2`. +pub const CHAINED_RELAY_ALPN: &[u8] = b"/id-chained-relay/1"; + +/// What a host does with a chained message its relay gate forwarded. +/// +/// The sink receives the forwarded form of the message: the origin +/// envelope is byte-identical to what arrived (so the message ID is +/// the same on every path) and this relay's hop has been appended. +/// Deliver it locally, then fan the same value out to next peers with +/// [`forward_message`]. Implementations must not block: hand the +/// message to a channel or queue and return. +pub trait ChainedSink: Send + Sync { + /// The gate forwarded `forwarded`; deliver and fan it out. + fn deliver(&self, forwarded: &RelayedMessage); +} + +/// Sends `msg` to the node at `target` over the chained-relay ALPN, +/// and says whether it is done. Mirrors +/// [`deliver`](crate::envelope_net::deliver) for friend envelopes. +pub async fn forward_message( + endpoint: &Endpoint, + target: impl Into, + msg: &RelayedMessage, +) -> Outcome { + let json = match serde_json::to_vec(msg) { + Ok(json) => json, + Err(error) => { + return Outcome::Refused(format!("chained message does not encode: {error}")); + } + }; + send(endpoint, CHAINED_RELAY_ALPN, target.into(), &json).await +} + +/// Accepts chained messages over Iroh and runs each one through a +/// [`RelayGate`] before it can be delivered or forwarded. +/// +/// Register with `Router::builder(..).accept(CHAINED_RELAY_ALPN, +/// ChainedRelayProtocol::new(gate, sink))`. +#[derive(Clone)] +pub struct ChainedRelayProtocol { + gate: Arc>>, + sink: S, +} + +impl ChainedRelayProtocol { + /// Serve chained messages through `gate`, delivering forwards to + /// `sink`. + #[must_use] + pub fn new(gate: RelayGate, sink: S) -> Self { + Self { + gate: Arc::new(Mutex::new(gate)), + sink, + } + } + + fn lock_gate(&self) -> std::sync::MutexGuard<'_, RelayGate> { + self.gate + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } +} + +/// The gate holds the relay's secret key bytes, so `Debug` names the +/// type and shows nothing else. +impl std::fmt::Debug for ChainedRelayProtocol { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ChainedRelayProtocol") + .finish_non_exhaustive() + } +} + +impl ProtocolHandler for ChainedRelayProtocol +where + F: MembershipFrontier + Send + 'static, + S: ChainedSink + Clone + Send + Sync + 'static, +{ + async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { + let gate = Arc::clone(&self.gate); + let sink = self.sink.clone(); + answer_frames(&conn, move |body| { + let gate = Arc::clone(&gate); + let sink = sink.clone(); + async move { receive(&gate, &sink, &body) } + }) + .await + } +} + +/// One inbound frame: decode strictly, decide through the gate, +/// deliver only on a forward. Never panics on malformed input — +/// every failure is a [`Reply::Refused`] (or [`Reply::Duplicate`]) +/// the sender can act on. +fn receive( + gate: &Mutex>, + sink: &S, + body: &[u8], +) -> Reply { + let msg: RelayedMessage = match crate::checked_json::from_slice_unique(body) { + Ok(msg) => msg, + Err(error) => { + return Reply::Refused { + message: format!("not a chained message: {error:#}"), + }; + } + }; + let received_at = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_secs()); + let decision = { + let mut gate = gate + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + gate.decide(&msg, received_at) + }; + match decision { + GateDecision::Forward(forwarded) => { + sink.deliver(&forwarded); + Reply::Applied + } + GateDecision::Refuse(GateRefusal::Duplicate) => Reply::Duplicate, + GateDecision::Refuse(refusal) => Reply::Refused { + message: refusal.to_string(), + }, + } +} + +impl ChainedRelayProtocol { + /// How many distinct message IDs this relay has forwarded. + pub fn forwarded(&self) -> usize { + self.lock_gate().forwarded() + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use std::sync::{Arc, Mutex}; + + use ed25519_dalek::SigningKey; + use iroh::{ + EndpointAddr, + endpoint::{RelayMode, presets}, + protocol::Router, + }; + + use super::*; + use crate::chained_message::{ChainedContent, ChainedEnvelope}; + use crate::hex::hex_encode; + use crate::relay_gate::AllowlistFrontier; + + // Oracle: issue #3796's acceptance (two members with no direct + // connection exchange chained messages via a bridging member; + // forged/altered relayed messages are rejected; duplicates are + // suppressed) exercised at the live ingest call site this module + // adds, over real Iroh connections — the gate-level half of the + // same acceptance is covered in `relay_gate`'s tests. + + fn key(seed: u8) -> SigningKey { + SigningKey::from_bytes(&[seed; 32]) + } + + fn key_id(seed: u8) -> String { + hex_encode(&key(seed).verifying_key().to_bytes()) + } + + fn envelope(origin_seed: u8, sequence: u64) -> ChainedEnvelope { + ChainedEnvelope::signed( + &key(origin_seed), + "group-1", + sequence, + Vec::new(), + "durable", + ChainedContent::Inline { + bytes: b"hello".to_vec(), + }, + 1_000, + ) + .unwrap() + } + + #[derive(Clone, Default)] + struct CollectSink(Arc>>); + + impl CollectSink { + fn received(&self) -> Vec { + self.0.lock().unwrap().clone() + } + } + + impl ChainedSink for CollectSink { + fn deliver(&self, forwarded: &RelayedMessage) { + self.0.lock().unwrap().push(forwarded.clone()); + } + } + + async fn endpoint() -> Endpoint { + Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .bind() + .await + .unwrap() + } + + fn loopback_addr(ep: &Endpoint) -> EndpointAddr { + EndpointAddr::from_parts( + ep.id(), + ep.bound_sockets().iter().map(|addr| { + let ip = if addr.ip().is_unspecified() { + std::net::Ipv4Addr::LOCALHOST.into() + } else { + addr.ip() + }; + iroh::TransportAddr::Ip(std::net::SocketAddr::new(ip, addr.port())) + }), + ) + } + + fn member_protocol( + relay_seed: u8, + origin_seed: u8, + sink: CollectSink, + ) -> ChainedRelayProtocol { + let mut frontier = AllowlistFrontier::new(); + frontier.allow("group-1", &key_id(origin_seed)); + ChainedRelayProtocol::new(RelayGate::new(&key(relay_seed), frontier), sink) + } + + #[tokio::test] + async fn bridge_then_leaf_exchange_over_live_connections() { + // Acceptance: origin -> bridge -> leaf over real connections. + // The leaf receives the origin's envelope byte-identical (same + // message ID) with both relays' hops appended in order. + let origin = endpoint().await; + let bridge = endpoint().await; + let leaf = endpoint().await; + + let bridge_sink = CollectSink::default(); + let bridge_protocol = member_protocol(7, 1, bridge_sink.clone()); + let leaf_sink = CollectSink::default(); + let leaf_protocol = member_protocol(8, 1, leaf_sink.clone()); + let _bridge_router = Router::builder(bridge.clone()) + .accept(CHAINED_RELAY_ALPN, bridge_protocol.clone()) + .spawn(); + let _leaf_router = Router::builder(leaf.clone()) + .accept(CHAINED_RELAY_ALPN, leaf_protocol.clone()) + .spawn(); + + let msg = RelayedMessage::new(envelope(1, 0)); + let id = msg.message_id().unwrap(); + + let outcome = forward_message(&origin, loopback_addr(&bridge), &msg).await; + assert!( + matches!(outcome, Outcome::Delivered), + "bridge must accept a valid member message, got {outcome:?}" + ); + let bridged = bridge_sink.received(); + assert_eq!(bridged.len(), 1); + assert_eq!(bridged[0].message_id().unwrap(), id); + assert_eq!(bridged[0].envelope, msg.envelope); + assert_eq!(bridged[0].hops.len(), 1); + assert_eq!(bridged[0].hops[0].relay, key_id(7)); + assert_eq!(bridge_protocol.forwarded(), 1); + + let outcome = forward_message(&bridge, loopback_addr(&leaf), &bridged[0]).await; + assert!( + matches!(outcome, Outcome::Delivered), + "leaf must accept the bridged message, got {outcome:?}" + ); + let delivered = leaf_sink.received(); + assert_eq!(delivered.len(), 1); + assert_eq!(delivered[0].message_id().unwrap(), id); + assert_eq!(delivered[0].envelope, msg.envelope); + assert_eq!(delivered[0].hops.len(), 2); + assert_eq!(delivered[0].hops[0].relay, key_id(7)); + assert_eq!(delivered[0].hops[1].relay, key_id(8)); + assert_eq!( + delivered[0].hops[1].previous_hop.as_deref(), + Some(key_id(7).as_str()) + ); + delivered[0].verify_envelope().unwrap(); + delivered[0].check_hops().unwrap(); + } + + #[tokio::test] + async fn forged_message_is_refused_at_ingest_and_never_delivered() { + // Acceptance: a forged/altered relayed message is rejected at + // the ingest call site — refused reply, nothing delivered, + // nothing forwarded. + let origin = endpoint().await; + let bridge = endpoint().await; + let bridge_sink = CollectSink::default(); + let bridge_protocol = member_protocol(7, 1, bridge_sink.clone()); + let _bridge_router = Router::builder(bridge.clone()) + .accept(CHAINED_RELAY_ALPN, bridge_protocol.clone()) + .spawn(); + + let mut forged = envelope(1, 0); + forged.content = ChainedContent::Inline { + bytes: b"forged".to_vec(), + }; + let outcome = forward_message( + &origin, + loopback_addr(&bridge), + &RelayedMessage::new(forged), + ) + .await; + assert!( + matches!(outcome, Outcome::Refused(_)), + "forged message must be refused at ingest, got {outcome:?}" + ); + assert!(bridge_sink.received().is_empty()); + assert_eq!(bridge_protocol.forwarded(), 0); + } + + #[tokio::test] + async fn non_member_origin_is_refused_at_ingest() { + // Acceptance: the safe default — a relay only carries traffic + // for groups whose membership it can authorize. An origin the + // frontier does not list is refused before any forward. + let origin = endpoint().await; + let bridge = endpoint().await; + let bridge_sink = CollectSink::default(); + let protocol = ChainedRelayProtocol::new( + RelayGate::new(&key(7), AllowlistFrontier::new()), + bridge_sink.clone(), + ); + let _bridge_router = Router::builder(bridge.clone()) + .accept(CHAINED_RELAY_ALPN, protocol.clone()) + .spawn(); + + let msg = RelayedMessage::new(envelope(1, 0)); + let outcome = forward_message(&origin, loopback_addr(&bridge), &msg).await; + match outcome { + Outcome::Refused(message) => { + assert!( + message.contains("may not write"), + "refusal must name the authorization failure, got: {message}" + ); + } + other => panic!("non-member origin must be refused at ingest, got {other:?}"), + } + assert!(bridge_sink.received().is_empty()); + assert_eq!(protocol.forwarded(), 0); + } + + #[tokio::test] + async fn duplicate_arrival_is_suppressed_at_ingest() { + // Acceptance: duplicates are suppressed — the second arrival + // of the same message ID delivers nothing new (the transport + // maps the gate's Duplicate onto a delivered outcome, since + // the message HAS been delivered exactly once). + let origin = endpoint().await; + let bridge = endpoint().await; + let bridge_sink = CollectSink::default(); + let bridge_protocol = member_protocol(7, 1, bridge_sink.clone()); + let _bridge_router = Router::builder(bridge.clone()) + .accept(CHAINED_RELAY_ALPN, bridge_protocol.clone()) + .spawn(); + + let msg = RelayedMessage::new(envelope(1, 0)); + for attempt in 0..2 { + let outcome = forward_message(&origin, loopback_addr(&bridge), &msg).await; + assert!( + matches!(outcome, Outcome::Delivered), + "attempt {attempt} must report delivered, got {outcome:?}" + ); + } + assert_eq!(bridge_sink.received().len(), 1); + assert_eq!(bridge_protocol.forwarded(), 1); + } +}