diff --git a/pkgs/id/src/abuse.rs b/pkgs/id/src/abuse.rs index 0ccbaeb430..d38e95e8f4 100644 --- a/pkgs/id/src/abuse.rs +++ b/pkgs/id/src/abuse.rs @@ -43,6 +43,9 @@ use std::collections::{HashMap, HashSet}; use std::net::IpAddr; +use std::sync::Arc; + +use crate::event_store::BlockList; /// A remote endpoint identity: the 32 bytes of its verifying key, /// the same bytes the event store uses as an author key. @@ -673,6 +676,11 @@ pub struct AbuseEvaluator { /// exactly: token buckets only, no budget scopes charged. budgets: Option, budget_state: HashMap>, + /// The operator block list (#2245), when the evaluator's owner + /// attached one: [`AbuseEvaluator::open_connection`] refuses a + /// blocked endpoint before any bucket or cap is consulted. `None` + /// keeps the pre-#2245 behaviour exactly. + blocks: Option>, } impl AbuseEvaluator { @@ -686,9 +694,23 @@ impl AbuseEvaluator { registry: CounterRegistry::new(), budgets: None, budget_state: HashMap::new(), + blocks: None, } } + /// Like [`AbuseEvaluator::new`], with the operator block list + /// (#2245) attached: a new connection from an endpoint blocked by + /// key is refused with [`Refusal::blocked_by_operator`]. The list + /// is consulted live on every open, so a block or an unblock lands + /// on the next connection. Frame and byte checks are unchanged — + /// a block refuses new sessions; it does not retroactively charge + /// or drop a session that is already open. + #[must_use] + pub fn with_block_list(mut self, blocks: Arc) -> Self { + self.blocks = Some(blocks); + self + } + /// Like [`AbuseEvaluator::new`], with the #2247 rolling-window /// budgets configured: charges through /// [`AbuseEvaluator::check_budget`] and @@ -951,13 +973,23 @@ impl AbuseEvaluator { /// /// # Errors /// - /// Returns a [`RefusalReason::RateLimited`] refusal when the - /// endpoint already holds the policy's maximum connections. + /// Returns a [`RefusalReason::BlockedByOperator`] refusal when the + /// operator block list attached with + /// [`AbuseEvaluator::with_block_list`] blocks `endpoint`, and a + /// [`RefusalReason::RateLimited`] refusal when the endpoint already + /// holds the policy's maximum connections. pub fn open_connection( &mut self, endpoint: EndpointId, now_ms: u64, ) -> Result { + if self + .blocks + .as_ref() + .is_some_and(|blocks| blocks.peer_blocked(&endpoint)) + { + return Err(Refusal::blocked_by_operator()); + } let cap = self.policy.max_connections_per_peer; // Ids are unique and never reused; a refused open may skip // an id, which is harmless. @@ -1200,6 +1232,24 @@ mod tests { assert!(eval.check_frame(ep, true, 0).is_err()); } + #[test] + fn a_blocked_endpoint_is_refused_a_new_connection() { + // #2245 session admission: with a block list attached, a blocked + // endpoint's new connection is refused as an operator block — + // permanent, no retry offered, and no connection registered. + let blocks = crate::pull_policy::testing::stub_blocks(&[endpoint(7)], &[]); + let mut eval = evaluator().with_block_list(blocks); + let refused = eval + .open_connection(endpoint(7), 0) + .expect_err("a blocked endpoint was admitted"); + assert_eq!(refused, Refusal::blocked_by_operator()); + assert_eq!(refused.reason, RefusalReason::BlockedByOperator); + assert_eq!(refused.retry_after_ms, None); + assert_eq!(eval.active_connection_count(&endpoint(7)), 0); + eval.open_connection(endpoint(8), 0) + .expect("an unblocked endpoint still connects"); + } + #[test] fn connection_cap_is_per_peer() { let mut eval = evaluator(); diff --git a/pkgs/id/src/blob_gate.rs b/pkgs/id/src/blob_gate.rs index e64b3bdd34..0bdc4c160a 100644 --- a/pkgs/id/src/blob_gate.rs +++ b/pkgs/id/src/blob_gate.rs @@ -34,6 +34,7 @@ use iroh_blobs::{ }; use crate::access::AccessPolicy; +use crate::event_store::BlockList; use crate::groups::{Role, worlds::Worlds}; /// The two questions the gate asks of the world graph. @@ -98,6 +99,29 @@ pub fn decide( hash: &Hash, request: Request, ) -> bool { + decide_with_blocks(access, policy, None, requester, hash, request) +} + +/// [`decide`], with the operator block list composed in (#2245): a +/// requester blocked by endpoint key is refused fetch and observe alike, +/// member or not. The seam's shape stays the crate's bool verdict (the +/// provider's `AbortReason::Permission` is what a refusal becomes in +/// [`blob_events_with_blocks`]). Pushes are not decided here: a block +/// changes serving only, never what the store ingests. +/// +/// `blocks` is `None` for a gate with no list attached — exactly +/// [`decide`]'s behaviour. +pub fn decide_with_blocks( + access: &impl WorldAccess, + policy: &BlobPolicy, + blocks: Option<&dyn BlockList>, + requester: &EndpointId, + hash: &Hash, + request: Request, +) -> bool { + if blocks.is_some_and(|blocks| blocks.peer_blocked(requester.as_bytes())) { + return false; + } access.worlds_referencing(hash).iter().any(|world| { access.is_current_member(world, requester) && match request { @@ -167,6 +191,21 @@ pub fn blob_events( access: Arc, policy: BlobPolicy, writes: AccessPolicy, +) -> EventSender { + blob_events_with_blocks(access, policy, writes, None) +} + +/// [`blob_events`], with the operator block list composed into every +/// serving verdict (#2245): a blocked endpoint is refused `get`, +/// `get_many`, and `observe` through the same `AbortReason::Permission` +/// as a non-member, so a refusal still does not reveal which rule made +/// it. Push verdicts are unchanged — writes are ingest, and a block +/// never rejects what a peer sends, only what it is served. +pub fn blob_events_with_blocks( + access: Arc, + policy: BlobPolicy, + writes: AccessPolicy, + blocks: Option>, ) -> EventSender { let (tx, mut rx) = tokio::sync::mpsc::channel::(64); let mask = EventMask { @@ -191,22 +230,42 @@ pub fn blob_events( } ProviderMessage::GetRequestReceived(m) => { let verdict = admit(peers.get(&m.connection_id), |id| { - decide(&*access, &policy, id, &m.request.hash, Request::Fetch) + decide_with_blocks( + &*access, + &policy, + blocks.as_deref(), + id, + &m.request.hash, + Request::Fetch, + ) }); let _ = m.tx.send(verdict).await; } ProviderMessage::GetManyRequestReceived(m) => { let verdict = admit(peers.get(&m.connection_id), |id| { - m.request - .hashes - .iter() - .all(|hash| decide(&*access, &policy, id, hash, Request::Fetch)) + m.request.hashes.iter().all(|hash| { + decide_with_blocks( + &*access, + &policy, + blocks.as_deref(), + id, + hash, + Request::Fetch, + ) + }) }); let _ = m.tx.send(verdict).await; } ProviderMessage::ObserveRequestReceived(m) => { let verdict = admit(peers.get(&m.connection_id), |id| { - decide(&*access, &policy, id, &m.request.hash, Request::Observe) + decide_with_blocks( + &*access, + &policy, + blocks.as_deref(), + id, + &m.request.hash, + Request::Observe, + ) }); let _ = m.tx.send(verdict).await; } @@ -303,6 +362,36 @@ mod tests { )); } + #[test] + fn a_blocked_member_is_refused_fetch_and_observe() { + // #2245: the block composes over membership — a current member + // blocked by endpoint key is served nothing. + let t = one_world(id(1), blob(9)); + let p = BlobPolicy::default().with_observe(); + let blocks = crate::pull_policy::testing::stub_blocks(&[*id(1).as_bytes()], &[]); + for request in [Request::Fetch, Request::Observe] { + assert!(!decide_with_blocks( + &t, + &p, + Some(&*blocks), + &id(1), + &blob(9), + request + )); + } + // A list that blocks someone else leaves the member's verdict + // exactly what membership decides. + let blocks = crate::pull_policy::testing::stub_blocks(&[*id(2).as_bytes()], &[]); + assert!(decide_with_blocks( + &t, + &p, + Some(&*blocks), + &id(1), + &blob(9), + Request::Fetch + )); + } + #[test] fn a_member_of_an_unrelated_world_is_refused() { let t = Table { diff --git a/pkgs/id/src/event_store/mod.rs b/pkgs/id/src/event_store/mod.rs index b5676ee560..e185762e00 100644 --- a/pkgs/id/src/event_store/mod.rs +++ b/pkgs/id/src/event_store/mod.rs @@ -21,6 +21,9 @@ //! dependency to the rows that wait for it. The `waiting_rows` module describes them, and //! the waiting pool in memory mirrors them. //! - `meta`: the store's format. +//! - `blocks`: the operator block list (see `Block`): one row per blocked peer +//! key, IP, or topic tag. A block changes serving and subscribing only; it +//! never rejects already-signed objects at ingest. //! //! A position key is the author's 32 bytes followed by the sequence number in //! big-endian, so one author's events sort in sequence order. @@ -103,6 +106,8 @@ const WAITING: TableDefinition<'static, &'static [u8], &'static [u8]> = const WAITING_BY_DEP: MultimapTableDefinition<'static, &'static [u8], &'static [u8]> = MultimapTableDefinition::new("waiting_by_dep"); const META: TableDefinition<'static, &'static [u8], &'static [u8]> = TableDefinition::new("meta"); +const BLOCKS: TableDefinition<'static, &'static [u8], &'static [u8]> = + TableDefinition::new("blocks"); /// Each group operation's encoded action, by event ID. Written when the event arrives, held or /// stored, so a release reads it back without the caller. The resolution reads it again. const ACTIONS: TableDefinition<'static, &'static [u8], &'static [u8]> = @@ -346,6 +351,268 @@ pub struct EventStore { unusable: bool, } +/// What an operator block names. The tag byte leads the row key in `blocks`, +/// so rows sort by kind, then by value. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BlockKind { + /// An Iroh endpoint key (the EndpointId of abuse.rs): refuse the peer's + /// new sessions, blob serving, and gossip subscriptions. + PeerKey, + /// An IP address, enforced at the listener only (best-effort). + Ip, + /// A topic tag, composing with the pull policy. + TopicTag, +} + +impl BlockKind { + fn tag(self) -> u8 { + match self { + BlockKind::PeerKey => 0, + BlockKind::Ip => 1, + BlockKind::TopicTag => 2, + } + } + + fn from_tag(tag: u8) -> Option { + match tag { + 0 => Some(BlockKind::PeerKey), + 1 => Some(BlockKind::Ip), + 2 => Some(BlockKind::TopicTag), + _ => None, + } + } +} + +/// One operator block-list row: the blocked value, when it was added, why, +/// and when it stops being enforced. An `expires_at_ms` of `None` is a +/// permanent block. An expired block stays on the list (the operator's +/// record) but is never enforced. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Block { + /// What the block names. + pub kind: BlockKind, + /// The blocked value: a 32-byte endpoint key, an IP address, or a topic + /// tag. + pub value: Vec, + /// When the block was added, in milliseconds since the Unix epoch. + pub added_at_ms: u64, + /// The operator's reason for the block. + pub reason: String, + /// When the block stops being enforced, in milliseconds since the Unix + /// epoch, or `None` for a permanent block. + pub expires_at_ms: Option, +} + +impl Block { + /// Whether the block is enforced at `now_ms`. Expiry is exclusive: a + /// block that expires at `t` is no longer enforced at `t`. + pub fn is_active(&self, now_ms: u64) -> bool { + self.expires_at_ms.map_or(true, |expiry| expiry > now_ms) + } + + fn key(&self) -> Vec { + let mut key = Vec::with_capacity(1 + self.value.len()); + key.push(self.kind.tag()); + key.extend_from_slice(&self.value); + key + } + + fn encode(&self) -> Vec { + let mut out = Vec::with_capacity(8 + 1 + 8 + 4 + self.reason.len()); + out.extend_from_slice(&self.added_at_ms.to_be_bytes()); + match self.expires_at_ms { + Some(expiry) => { + out.push(1); + out.extend_from_slice(&expiry.to_be_bytes()); + } + None => { + out.push(0); + out.extend_from_slice(&0u64.to_be_bytes()); + } + } + out.extend_from_slice(&(self.reason.len() as u32).to_be_bytes()); + out.extend_from_slice(self.reason.as_bytes()); + out + } + + fn decode(key: &[u8], value: &[u8]) -> Result { + let Some((&tag, blocked)) = key.split_first() else { + return Err(corrupt("a block row has an empty key")); + }; + let kind = BlockKind::from_tag(tag) + .ok_or_else(|| corrupt("a block row has an unknown kind tag"))?; + if value.len() < 8 + 1 + 8 + 4 { + return Err(corrupt("a block row is too short")); + } + let added_at_ms = u64::from_be_bytes(value[0..8].try_into().unwrap()); + let expires_at_ms = match value[8] { + 0 => None, + 1 => Some(u64::from_be_bytes(value[9..17].try_into().unwrap())), + _ => return Err(corrupt("a block row has a bad expiry flag")), + }; + let reason_len = u32::from_be_bytes(value[17..21].try_into().unwrap()) as usize; + if value.len() != 21 + reason_len { + return Err(corrupt("a block row has the wrong reason length")); + } + let reason = String::from_utf8(value[21..].to_vec()) + .map_err(|_err| corrupt("a block row's reason is not UTF-8"))?; + Ok(Block { + kind, + value: blocked.to_vec(), + added_at_ms, + reason, + expires_at_ms, + }) + } +} + +impl EventStore { + /// Adds `block` to the operator block list, replacing any row that names + /// the same kind and value. + /// + /// # Errors + /// + /// Returns a redb error if the write fails. + pub fn add_block(&self, block: &Block) -> Result<(), StoreError> { + let txn = self.db.begin_write()?; + { + let mut blocks = txn.open_table(BLOCKS)?; + blocks.insert(block.key().as_slice(), block.encode().as_slice())?; + } + txn.commit()?; + Ok(()) + } + + /// Removes the block naming (`kind`, `value`), returning whether a row + /// was removed. Removing a block that does not exist is not an error. + /// + /// # Errors + /// + /// Returns a redb error if the write fails. + pub fn remove_block(&self, kind: BlockKind, value: &[u8]) -> Result { + let mut key = Vec::with_capacity(1 + value.len()); + key.push(kind.tag()); + key.extend_from_slice(value); + let txn = self.db.begin_write()?; + let removed = { + let mut blocks = txn.open_table(BLOCKS)?; + blocks.remove(key.as_slice())?.is_some() + }; + txn.commit()?; + Ok(removed) + } + + /// Every block on the list, expired ones included, in (kind, value) + /// order. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or `StoreError::Corrupt`. + pub fn blocks(&self) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let blocks = txn.open_table(BLOCKS)?; + let mut found = Vec::new(); + for row in blocks.iter()? { + let (key, value) = row?; + found.push(Block::decode(key.value(), value.value())?); + } + Ok(found) + } + + /// The block naming (`kind`, `value`) if one is on the list and still + /// enforced at `now_ms`. An expired block is not returned. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or `StoreError::Corrupt`. + pub fn active_block( + &self, + kind: BlockKind, + value: &[u8], + now_ms: u64, + ) -> Result, StoreError> { + let mut key = Vec::with_capacity(1 + value.len()); + key.push(kind.tag()); + key.extend_from_slice(value); + let txn = self.db.begin_read()?; + let blocks = txn.open_table(BLOCKS)?; + let Some(row) = blocks.get(key.as_slice())? else { + return Ok(None); + }; + let block = Block::decode(&key, row.value())?; + Ok(block.is_active(now_ms).then_some(block)) + } + + /// Whether (`kind`, `value`) is blocked at `now_ms`. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or `StoreError::Corrupt`. + pub fn is_blocked( + &self, + kind: BlockKind, + value: &[u8], + now_ms: u64, + ) -> Result { + Ok(self.active_block(kind, value, now_ms)?.is_some()) + } +} + +/// The operator block list as the enforcement seams consult it (#2245). +/// +/// A seam holds an `Arc` and asks it about a peer, a topic +/// tag, or an IP; it never reads the `blocks` table itself. Implementations +/// read the list live on every call, so a block (or an unblock) lands on the +/// next check, and they judge expiry against the wall clock +/// ([`crate::time::unix_ms`]) — the same epoch `Block::added_at_ms` and +/// `Block::expires_at_ms` are stamped in. That is why this trait takes no +/// `now_ms`: the session clocks the sync seams carry are not all wall +/// clocks (the abuse evaluator's is monotonic), and a block's expiry is a +/// wall-clock fact. +/// +/// The invariant from the module docs rides on this trait's callers: blocks +/// change serving and subscribing only. No ingest path consults a +/// `BlockList`, so an already-signed object from a blocked peer is decided +/// by the store's ordinary rules, exactly as if the block did not exist. +pub trait BlockList: std::fmt::Debug + Send + Sync + 'static { + /// Whether (`kind`, `value`) is blocked now. An expired block is not + /// enforced, so this is false for one, however long it stays listed. + fn is_blocked(&self, kind: BlockKind, value: &[u8]) -> bool; + + /// Whether the endpoint with this 32-byte key is blocked. + fn peer_blocked(&self, peer: &[u8; 32]) -> bool { + self.is_blocked(BlockKind::PeerKey, peer) + } + + /// Whether this topic tag is blocked. The tag is raw bytes: a pull + /// gate passes its world's name, the sync handshake passes the topic's + /// hash bytes; an operator blocks whichever form a surface names. + fn topic_tag_blocked(&self, tag: &[u8]) -> bool { + self.is_blocked(BlockKind::TopicTag, tag) + } + + /// Whether this IP is blocked. IP rows name the address in its text + /// form (as the storage tests write them), so the check formats `ip` + /// the same way. + fn ip_blocked(&self, ip: &std::net::IpAddr) -> bool { + self.is_blocked(BlockKind::Ip, ip.to_string().as_bytes()) + } +} + +impl BlockList for EventStore { + fn is_blocked(&self, kind: BlockKind, value: &[u8]) -> bool { + // A read error invents no block: the seam fails open, and the + // store's error still surfaces on the store's own read paths. + EventStore::is_blocked(self, kind, value, crate::time::unix_ms()).unwrap_or(false) + } +} + +impl BlockList for std::sync::Arc { + fn is_blocked(&self, kind: BlockKind, value: &[u8]) -> bool { + (**self).is_blocked(kind, value) + } +} + impl EventStore { /// Opens the store in `dir`, creating it if the directory has none. `limits` are the caps /// on waiting events, and `now_ms` is the clock: the waiting events due at it are dropped. @@ -376,6 +643,14 @@ impl EventStore { create_fresh(storage)? }; verify_schema(&db)?; + // The blocks table is additive: stores created before it gain it here, + // on the write every open already performs, instead of a format change + // that would refuse them. + { + let txn = db.begin_write()?; + txn.open_table(BLOCKS)?; + txn.commit()?; + } let mut store = Self { db, limits, @@ -1100,6 +1375,7 @@ fn initialize(db: &Database) -> Result<(), StoreError> { txn.open_multimap_table(WAITING_BY_DEP)?; txn.open_table(ACTIONS)?; txn.open_table(APPLIED)?; + txn.open_table(BLOCKS)?; let mut meta = txn.open_table(META)?; meta.insert(FORMAT_KEY, FORMAT)?; drop(meta); @@ -1662,4 +1938,148 @@ mod tests { let found = meta.get(FORMAT_KEY).unwrap().unwrap(); assert_eq!(found.value(), b"id.events.store.v2".as_slice()); } + + fn block(kind: BlockKind, value: &[u8], expires_at_ms: Option) -> Block { + Block { + kind, + value: value.to_vec(), + added_at_ms: 1_000, + reason: "test block".to_owned(), + expires_at_ms, + } + } + + #[test] + fn test_blocks_persist_across_restart() { + let dir = tempfile::tempdir().unwrap(); + let peer = block(BlockKind::PeerKey, &[7u8; 32], None); + { + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); + store.add_block(&peer).unwrap(); + store + .add_block(&block(BlockKind::Ip, b"192.0.2.1", None)) + .unwrap(); + } + let reopened = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); + let listed = reopened.blocks().unwrap(); + assert_eq!(listed.len(), 2); + assert_eq!(listed[0], peer, "peer-key rows sort before IP rows"); + assert!( + reopened + .is_blocked(BlockKind::PeerKey, &[7u8; 32], 2_000) + .unwrap() + ); + assert!( + !reopened + .is_blocked(BlockKind::PeerKey, &[8u8; 32], 2_000) + .unwrap() + ); + } + + #[test] + fn test_an_expired_block_is_listed_but_not_enforced() { + let (_dir, store) = open_temp(); + let expiring = block(BlockKind::TopicTag, b"spam", Some(1_500)); + store.add_block(&expiring).unwrap(); + assert_eq!( + store + .active_block(BlockKind::TopicTag, b"spam", 1_499) + .unwrap(), + Some(expiring.clone()) + ); + assert_eq!( + store + .active_block(BlockKind::TopicTag, b"spam", 1_500) + .unwrap(), + None, + "expiry is exclusive: at the expiry instant the block no longer applies" + ); + assert!( + !store + .is_blocked(BlockKind::TopicTag, b"spam", 9_999) + .unwrap() + ); + assert_eq!( + store.blocks().unwrap(), + vec![expiring], + "the expired row stays on the list as the operator's record" + ); + } + + #[test] + fn test_block_list_answers_peer_topic_and_ip_from_the_store() { + let (_dir, store) = open_temp(); + store + .add_block(&block(BlockKind::PeerKey, &[7u8; 32], None)) + .unwrap(); + store + .add_block(&block(BlockKind::TopicTag, b"spam", None)) + .unwrap(); + store + .add_block(&block(BlockKind::Ip, b"192.0.2.1", None)) + .unwrap(); + // The trait is what the enforcement seams hold: it answers from the + // store's live rows, with no clock handed in. + let list: &dyn BlockList = &store; + assert!(list.peer_blocked(&[7u8; 32])); + assert!(!list.peer_blocked(&[8u8; 32])); + assert!(list.topic_tag_blocked(b"spam")); + assert!(!list.topic_tag_blocked(b"ham")); + let blocked_ip: std::net::IpAddr = "192.0.2.1".parse().unwrap(); + let other_ip: std::net::IpAddr = "192.0.2.2".parse().unwrap(); + assert!(list.ip_blocked(&blocked_ip)); + assert!(!list.ip_blocked(&other_ip)); + // An expired block is listed but never enforced, through the trait + // exactly as through the store (its expiry, 1_500, is long past). + store + .add_block(&block(BlockKind::PeerKey, &[9u8; 32], Some(1_500))) + .unwrap(); + assert!(!list.peer_blocked(&[9u8; 32])); + assert_eq!(store.blocks().unwrap().len(), 4); + } + + /// The #2245 invariant: a block changes serving and subscribing only. + /// Signed events from a blocked author are ingested and applied by the + /// ordinary rules — if ingest ever consulted the block list, the graph + /// would diverge between nodes that block and nodes that do not. + #[test] + fn test_a_blocked_authors_signed_events_are_still_ingested() { + let (_dir, mut store) = open_temp(); + let signer = key(41); + let who = author(&signer); + store + .add_block(&block(BlockKind::PeerKey, &who, None)) + .unwrap(); + assert!(store.is_blocked(BlockKind::PeerKey, &who, 2_000).unwrap()); + let events = chain_of(&signer, 2); + for event in &events { + assert!( + matches!( + store.ingest(&event.bytes, 0).unwrap(), + Ingest::Accepted { .. } + ), + "a blocked author's signed event was not accepted" + ); + } + assert_eq!( + store.chain(&who).unwrap().map(|chain| chain.next_seq), + Some(2), + "both events applied, block notwithstanding" + ); + store.check_invariants().unwrap(); + } + + #[test] + fn test_remove_block() { + let (_dir, store) = open_temp(); + store + .add_block(&block(BlockKind::Ip, b"198.51.100.7", None)) + .unwrap(); + assert!(store.remove_block(BlockKind::Ip, b"198.51.100.7").unwrap()); + assert!( + !store.remove_block(BlockKind::Ip, b"198.51.100.7").unwrap(), + "removing an absent block is false, not an error" + ); + assert!(store.blocks().unwrap().is_empty()); + } } diff --git a/pkgs/id/src/event_store/sync.rs b/pkgs/id/src/event_store/sync.rs index ac829e86d3..16f7b1871f 100644 --- a/pkgs/id/src/event_store/sync.rs +++ b/pkgs/id/src/event_store/sync.rs @@ -1751,6 +1751,38 @@ mod tests { assert_eq!(ids(&a), before_a, "the server's store is unchanged"); } + /// #2245: a peer blocked by key is refused by the acceptor's gate + /// before any event is sent, under the open policy included. Both + /// sides end with an error, and neither store changes. + #[tokio::test(flavor = "multi_thread")] + async fn test_blocked_peer_range_session_is_refused_and_sends_no_event() { + let (_da, mut a) = open(); + let (_db, mut b) = open(); + populate(&mut a, &[(1, 4)]); + let (before_a, before_b) = (ids(&a), ids(&b)); + let gate = testing::open_gate() + .with_blocks(testing::stub_blocks(&[*testing::key(0xd1).public().as_bytes()], &[])); + let (dialer, acceptor) = loopback_gated( + &mut a, + &mut b, + Params::default(), + Params::default(), + Cut::Never, + &gate, + testing::key(0xd1), + ) + .await + .unwrap(); + let refused = acceptor.expect_err("a blocked peer was served events"); + assert!( + refused.downcast_ref::().is_some(), + "{refused:#}" + ); + assert!(dialer.is_err(), "the dialer's session ends with the refusal"); + assert_eq!(ids(&b), before_b, "no event crossed to the blocked peer"); + assert_eq!(ids(&a), before_a, "the server's store is unchanged"); + } + /// P6.5: a member gets every event under the members option. #[tokio::test(flavor = "multi_thread")] async fn test_pull_policy_members_range_serves_a_member_everything() { diff --git a/pkgs/id/src/log_sync.rs b/pkgs/id/src/log_sync.rs index d2bbd2de98..615f71d689 100644 --- a/pkgs/id/src/log_sync.rs +++ b/pkgs/id/src/log_sync.rs @@ -306,6 +306,15 @@ pub async fn answer( finish_stream(&mut send, &mut recv).await; return Err(SyncError::PullRefused); } + // A blocked topic tag is not pulled (#2245): the gate's block list + // is also checked against the requested topic's hash bytes, the + // form this seam names a topic in. Refused exactly as a pull + // refusal, before the method is agreed. + if gate.topic_tag_blocked(request.topic.as_bytes()) { + send_message(&mut send, &Answer::Refuse).await?; + finish_stream(&mut send, &mut recv).await; + return Err(SyncError::PullRefused); + } if !support.supports(request.method) { send_message(&mut send, &Answer::Refuse).await?; finish_stream(&mut send, &mut recv).await; @@ -1678,6 +1687,94 @@ mod tests { ); } + /// #2245: a peer blocked by key is refused by the responder's gate + /// before any event is sent, under the open policy included. The + /// dialer gets `Refuse`, the responder reports the refusal, and the + /// blocked peer's store does not change. + #[tokio::test] + async fn test_blocked_peer_log_session_is_refused_and_sends_no_event() { + let topic = group(14); + let alice = key(26); + let (_da, store_a) = open(); + let (_db, store_b) = open(); + ingest_all(&store_a, &chain_of(&alice, 4, topic)); + let before = applied(&store_b, &[&alice], 3); + let gate = testing::open_gate() + .with_blocks(testing::stub_blocks(&[*testing::key(0xd5).public().as_bytes()], &[])); + let (server, _router, mut results) = responder_gated(&store_a, gate).await; + let client = endpoint_as(testing::key(0xd5)).await; + let error = sync_with( + &client, + loopback(&server), + &store_b, + topic, + &bootstrap(), + DEADLINE, + ) + .await + .unwrap_err(); + let answered = results.recv().await.unwrap(); + + assert!( + matches!(error, SyncError::Refused(SyncMethod::Log)), + "got {error}" + ); + assert!( + matches!(answered, Err(SyncError::PullRefused)), + "got {answered:?}" + ); + assert_eq!( + applied(&store_b, &[&alice], 3), + before, + "no event crossed to the blocked peer" + ); + } + + /// #2245: a blocked topic tag is not pulled. The peer is not blocked + /// and the gate is open, but the requested topic's hash bytes are a + /// blocked tag, so the session is refused before the method is agreed. + #[tokio::test] + async fn test_blocked_topic_tag_log_session_is_refused_and_sends_no_event() { + let topic = group(15); + let alice = key(27); + let (_da, store_a) = open(); + let (_db, store_b) = open(); + ingest_all(&store_a, &chain_of(&alice, 4, topic)); + let before = applied(&store_b, &[&alice], 3); + let blocks = std::sync::Arc::new(testing::StubBlocks { + peers: Default::default(), + topics: [topic.as_bytes().to_vec()].into_iter().collect(), + }); + let gate = testing::open_gate().with_blocks(blocks); + let (server, _router, mut results) = responder_gated(&store_a, gate).await; + let client = endpoint_as(testing::key(0xd5)).await; + let error = sync_with( + &client, + loopback(&server), + &store_b, + topic, + &bootstrap(), + DEADLINE, + ) + .await + .unwrap_err(); + let answered = results.recv().await.unwrap(); + + assert!( + matches!(error, SyncError::Refused(SyncMethod::Log)), + "got {error}" + ); + assert!( + matches!(answered, Err(SyncError::PullRefused)), + "got {answered:?}" + ); + assert_eq!( + applied(&store_b, &[&alice], 3), + before, + "no event crossed for the blocked topic" + ); + } + /// P6.5: membership is read when each session starts. A member removed from the fold is refused /// on its next session, and the events it pulled before stay. Nothing new crosses. #[tokio::test] diff --git a/pkgs/id/src/pull_policy.rs b/pkgs/id/src/pull_policy.rs index 09cee5ee37..791aabf987 100644 --- a/pkgs/id/src/pull_policy.rs +++ b/pkgs/id/src/pull_policy.rs @@ -11,6 +11,13 @@ //! sync sessions check the gate before any event is sent. A refused peer gets no event, and the //! refusal is clean. An open gate never reads membership. //! +//! A gate may also carry the operator block list ([`crate::event_store::BlockList`], #2245): +//! a peer blocked by key is refused under every policy, and a gate whose world's name is a +//! blocked topic tag serves nothing. The blocks compose with the policy — they only ever +//! narrow it. Without a list attached, a gate behaves exactly as it did before the list +//! existed. The list is read on each check, so a block or an unblock lands on the next +//! session, as a membership removal does. +//! //! This is a config setting, not a protocol rule. The policy belongs with the world's policy. The //! server config's `[policy]` table parses it ([`crate::server_config::ServerConfig::pull_policy`]), //! but `id serve` does not read it yet, and no session builds a gate from config. Blobs are not @@ -23,6 +30,7 @@ use std::sync::Arc; use iroh_base::EndpointId; use crate::blob_gate::WorldAccess; +use crate::event_store::BlockList; /// Who may pull a world's events from this server. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -51,10 +59,14 @@ pub struct PullGate { policy: PullPolicy, world: String, access: Arc, + /// The operator block list, when the gate's owner attached one + /// ([`PullGate::with_blocks`]). Read on each check. + blocks: Option>, } impl PullGate { /// A gate for `world` under `policy`. `access` answers membership at the time of each check. + /// No operator block list is attached; [`PullGate::with_blocks`] adds one. #[must_use] pub fn new( policy: PullPolicy, @@ -65,19 +77,54 @@ impl PullGate { policy, world: world.into(), access, + blocks: None, } } + /// Attaches the operator block list (#2245): a peer blocked by key is + /// refused under every policy, and a gate whose world's name is a + /// blocked topic tag serves nothing. The list is consulted live, so a + /// block added after the gate was built is seen by the next check. + #[must_use] + pub fn with_blocks(mut self, blocks: Arc) -> Self { + self.blocks = Some(blocks); + self + } + /// The world this gate serves. #[must_use] pub fn world(&self) -> &str { &self.world } - /// Whether `peer` may pull this world's events now. + /// Whether the operator block list blocks `peer` by key. False when + /// no list is attached. + #[must_use] + pub fn peer_blocked(&self, peer: &EndpointId) -> bool { + self.blocks + .as_ref() + .is_some_and(|blocks| blocks.peer_blocked(peer.as_bytes())) + } + + /// Whether the operator block list blocks this topic tag (raw bytes: + /// a world name, or a sync topic's hash bytes). False when no list is + /// attached. Session seams that carry a topic the gate's world does + /// not name — the `log_sync` handshake — check the tag through here. + #[must_use] + pub fn topic_tag_blocked(&self, tag: &[u8]) -> bool { + self.blocks + .as_ref() + .is_some_and(|blocks| blocks.topic_tag_blocked(tag)) + } + + /// Whether `peer` may pull this world's events now: not blocked by + /// key, the world not blocked as a topic tag, and the policy admits + /// the peer. #[must_use] pub fn admits(&self, peer: &EndpointId) -> bool { - self.policy.admits(self.access.as_ref(), &self.world, peer) + !self.peer_blocked(peer) + && !self.topic_tag_blocked(self.world.as_bytes()) + && self.policy.admits(self.access.as_ref(), &self.world, peer) } } @@ -207,6 +254,37 @@ pub(crate) mod testing { Arc::new(Live::new(folded)) } + /// An operator block list with fixed rows, for the gate tests and the + /// session tests: the peers and topic tags it names are blocked, and + /// nothing else is. + #[derive(Debug, Default)] + pub(crate) struct StubBlocks { + /// Blocked endpoint keys. + pub peers: std::collections::HashSet<[u8; 32]>, + /// Blocked topic tags, as raw bytes. + pub topics: std::collections::HashSet>, + } + + impl crate::event_store::BlockList for StubBlocks { + fn is_blocked(&self, kind: crate::event_store::BlockKind, value: &[u8]) -> bool { + match kind { + crate::event_store::BlockKind::PeerKey => { + <[u8; 32]>::try_from(value).is_ok_and(|key| self.peers.contains(&key)) + } + crate::event_store::BlockKind::TopicTag => self.topics.iter().any(|t| t == value), + crate::event_store::BlockKind::Ip => false, + } + } + } + + /// A stub block list naming `peers` by key and `topics` by tag. + pub(crate) fn stub_blocks(peers: &[[u8; 32]], topics: &[&str]) -> Arc { + Arc::new(StubBlocks { + peers: peers.iter().copied().collect(), + topics: topics.iter().map(|t| t.as_bytes().to_vec()).collect(), + }) + } + /// An open gate over an empty world. It never reads membership. pub(crate) fn open_gate() -> PullGate { let none: BTreeMap> = BTreeMap::new(); @@ -265,6 +343,71 @@ mod tests { assert!(!gate.admits(&key(2).public()), "after the removal"); } + /// #2245: a peer blocked by key is refused even under the open + /// policy, which admits every other peer. The block only narrows. + #[test] + fn test_pull_gate_refuses_a_blocked_peer_under_open_policy() { + let gate = PullGate::new( + PullPolicy::Open, + WORLD, + live(docs_world(key(1).public(), key(2).public(), false)), + ) + .with_blocks(super::testing::stub_blocks(&[*key(9).public().as_bytes()], &[])); + assert!(!gate.admits(&key(9).public()), "the blocked peer is refused"); + assert!(gate.admits(&key(2).public()), "an unblocked peer still pulls"); + } + + /// #2245: a blocked topic tag is not pulled — a gate whose world is a + /// blocked tag serves nothing, to members included. + #[test] + fn test_pull_gate_refuses_every_peer_when_its_world_is_a_blocked_topic_tag() { + let gate = PullGate::new( + PullPolicy::Members, + WORLD, + live(docs_world(key(1).public(), key(2).public(), false)), + ) + .with_blocks(super::testing::stub_blocks(&[], &[WORLD])); + assert!(!gate.admits(&key(2).public()), "a member of a blocked topic"); + assert!(!gate.admits(&key(1).public()), "the founder of a blocked topic"); + } + + /// #2245, against the real store-backed list: a permanent block + /// refuses the peer, and an expired block does not — expiry is judged + /// by the list itself, so the gate needs no clock of its own. + #[test] + fn test_pull_gate_over_a_store_block_list_enforces_only_live_blocks() { + use crate::event_store::{Block, BlockKind, EventStore}; + use crate::waiting::WaitingLimits; + + let dir = tempfile::tempdir().unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); + let row = |value: &[u8], expires_at_ms: Option| Block { + kind: BlockKind::PeerKey, + value: value.to_vec(), + added_at_ms: 1_000, + reason: "gate test".to_owned(), + expires_at_ms, + }; + store + .add_block(&row(key(9).public().as_bytes(), None)) + .unwrap(); + store + .add_block(&row(key(8).public().as_bytes(), Some(1_500))) + .unwrap(); + let gate = PullGate::new( + PullPolicy::Open, + WORLD, + live(docs_world(key(1).public(), key(2).public(), false)), + ) + .with_blocks(Arc::new(store)); + assert!(!gate.admits(&key(9).public()), "a permanent block refuses"); + assert!( + gate.admits(&key(8).public()), + "an expired block (expiry 1_500, long past) is not enforced" + ); + assert!(gate.admits(&key(2).public()), "an unlisted peer pulls"); + } + /// A gate names one world. A member of `docs` is not a member of another world. #[test] fn test_pull_policy_members_checks_only_the_gates_world() { diff --git a/pkgs/id/src/server_config/mod.rs b/pkgs/id/src/server_config/mod.rs index fce3ed44f3..8fca99e147 100644 --- a/pkgs/id/src/server_config/mod.rs +++ b/pkgs/id/src/server_config/mod.rs @@ -28,6 +28,9 @@ //! [policy] # absent: the code defaults apply //! freshness_window_seconds = 300 # the server-level freshness window (N23) //! pull_policy = "open" # who may pull a world's events: "open" or "members" (P6.5) +//! # (the operator block list is not config: it lives in the +//! # event store's `blocks` table, #2245, and gates read it +//! # from there via `crate::event_store::BlockList`) //! //! [budgets] # absent: the #2247 code defaults apply //! app_inbound_bytes_per_hour = 21474836480 # 20 GiB/h app-wide inbound diff --git a/pkgs/id/src/store_traits.rs b/pkgs/id/src/store_traits.rs index 2cef646464..b400db2498 100644 --- a/pkgs/id/src/store_traits.rs +++ b/pkgs/id/src/store_traits.rs @@ -37,7 +37,7 @@ use p2panda_store::topics::TopicStore; use serde::{Deserialize, Serialize}; use crate::chain::Event; -use crate::event_store::{EventStore, Ingest, StoreError}; +use crate::event_store::{BlockKind, BlockList, EventStore, Ingest, StoreError}; use crate::waiting::AuthorKey; /// Entries read per page. A page takes the read lock once, so a stream never holds the lock @@ -304,6 +304,20 @@ impl SharedEventStore { } } +impl BlockList for SharedEventStore { + /// Whether (`kind`, `value`) is on the store's operator block list + /// and still enforced, under the read lock, taken for this one call. + /// The wall clock judges expiry, and a read error or a poisoned lock + /// invents no block. + fn is_blocked(&self, kind: BlockKind, value: &[u8]) -> bool { + self.read(|store| { + Ok(EventStore::is_blocked(store, kind, value, crate::time::unix_ms()) + .unwrap_or(false)) + }) + .unwrap_or(false) + } +} + /// The sequence number of the author's last applied event, or `None` when none applies. fn applied_height(store: &EventStore, author: &AuthorKey) -> Result, StoreError> { let Some(chain) = store.chain(author)? else { diff --git a/pkgs/id/src/world_net.rs b/pkgs/id/src/world_net.rs index c8e68a1e76..6ee44d1d69 100644 --- a/pkgs/id/src/world_net.rs +++ b/pkgs/id/src/world_net.rs @@ -29,8 +29,9 @@ use tokio::{ use crate::abuse::{ AbuseEvaluator, AbusePolicy, BudgetPolicy, BudgetUsage, ConnectionId, Counters, Direction, - EndpointId as AbuseEndpointId, NodeId, + EndpointId as AbuseEndpointId, NodeId, RefusalReason, }; +use crate::event_store::BlockList; use crate::frames::{read_frame_body, read_frame_len}; use crate::world_hub::WorldHub; use crate::world_session::{ @@ -119,13 +120,37 @@ impl WorldProtocol { local_node: NodeId, budgets: BudgetPolicy, ) -> Self { + Self::build(hub, local_node, budgets, None) + } + + /// Like [`WorldProtocol::with_local_node`], with the operator block + /// list (#2245) attached to the shared evaluator: a connection from + /// an endpoint blocked by key is refused at admission, before any + /// session starts, with the evaluator's + /// [`RefusalReason::BlockedByOperator`] refusal. The list is + /// consulted live, so a block lands on the next connection. + #[must_use] + pub fn with_blocks( + hub: impl Into, + local_node: NodeId, + blocks: Arc, + ) -> Self { + Self::build(hub, local_node, BudgetPolicy::default(), Some(blocks)) + } + + fn build( + hub: impl Into, + local_node: NodeId, + budgets: BudgetPolicy, + blocks: Option>, + ) -> Self { + let mut evaluator = AbuseEvaluator::with_budgets(AbusePolicy::default(), local_node, budgets); + if let Some(blocks) = blocks { + evaluator = evaluator.with_block_list(blocks); + } Self { hub: hub.into(), - abuse: Arc::new(Mutex::new(AbuseEvaluator::with_budgets( - AbusePolicy::default(), - local_node, - budgets, - ))), + abuse: Arc::new(Mutex::new(evaluator)), connection_cap_refusals: Arc::new(AtomicU64::new(0)), } } @@ -201,6 +226,16 @@ impl ProtocolHandler for WorldProtocol { let connection_id = match self.abuse.lock() { Ok(mut abuse) => match abuse.open_connection(remote_endpoint, abuse_now_ms()) { Ok(connection_id) => connection_id, + Err(refusal) if refusal.reason == RefusalReason::BlockedByOperator => { + // #2245: an operator block is not a cap refusal — it + // is not counted as one, and it offers no retry. + tracing::warn!( + remote = %remote, + "world: operator block; refusing connection" + ); + conn.close(0_u32.into(), b"blocked by operator"); + return Ok(()); + } Err(refusal) => { let refusal_count = self .connection_cap_refusals