Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Authenticated peer announcements and bounded discovery

Issue: [#2944](https://github.com/developing-today/code/issues/2944)

## Intent

Public gossip currently accepts an announcement's self-asserted `node_id`, retains an unbounded number of peers, and probes every stale peer sequentially with a ten-second timeout. A forged identity can replace a peer, while a flood can grow the table and prolong cleanup. This change authenticates announcements, bounds retained peers, and limits each stale-cleanup pass.

## Design

- Keep the existing `PeerAnnouncement` data type and its postcard layout unchanged. It is also nested in `MetaResponse::ListPeers` under `/iroh-meta/2`; changing that layout here would silently break an unrelated wire protocol.
- Gossip uses a distinct, versioned frame containing the announcement and an Ed25519 signature. Sign a domain-separated, deterministic encoding of the version and every claim field (`node_id`, `name`, `blob_count`, and `timestamp_secs`). The signer must match the claimed `node_id`; receivers derive the verification key from that ID and use strict signature verification. The versioned frame is the only accepted gossip path: unsigned legacy frames are ignored, with no fallback that would keep the spoofable path alive. Existing freshness and per-peer timestamp-order checks remain in force as replay controls.
- Verify at both gossip ingress paths: the server's table update and the `peers` command's direct gossip collection. Do not treat Iroh's `delivered_from` relay endpoint as the original author.
- Cap the in-memory peer table at 1,000. Existing IDs may refresh at capacity. For a new ID at capacity, evict the stale peer with the oldest local `last_seen`, breaking ties by endpoint-ID bytes; if every retained peer is fresh, reject the new ID. This bounds state without allowing a fresh Sybil announcement to displace a fresh peer.
- Limit advertised names to 256 UTF-8 bytes and signed gossip frames to 1 KiB. Apply the peer-count cap to the CLI's temporary gossip result map as well, so both long-running and one-shot gossip ingestion have bounded state.
- Each cleanup tick probes at most four stale peers, selected in deterministic endpoint-ID order with a round-robin cursor. With the existing ten-second per-peer timeout, a pass is bounded to at most forty seconds. Refresh a reachable peer; remove a failed peer individually only if it is still stale, so a concurrent valid announcement cannot be deleted. Never run the global stale sweep after a partial probe batch.

## Compatibility and limits

New receivers intentionally ignore old unsigned gossip announcements; accepting them as a fallback would preserve the identity-forgery vulnerability. `PeerAnnouncement` and `/iroh-meta/2` remain unchanged in this scoped fix. Signatures prove control of the claimed endpoint key, not uniqueness of identities: a peer can still generate multiple valid keys, so the table cap remains necessary. Rate limiting and broader topic changes are outside this fix.

## Verification plan

- Test signed-frame round trips, unsupported versions, unsigned legacy frames, mismatched signing keys, and tampering with every signed claim field.
- Test capacity, existing-ID refresh at capacity, deterministic stale eviction, refusal when all entries are fresh, and the invariant that the table never exceeds its cap.
- Test oversized names and frames are rejected before they enter retained peer state.
- Test bounded round-robin stale selection and conditional removal when a concurrent refresh makes a probed peer fresh.
- Run `cargo test -p id discovery` and the focused serve/peer-gossip tests; then run formatting and relevant package checks.

## References

- [Peer discovery feature record](../2026-03-22T00-00-00Z_feature_peer-discovery/2026-03-22T00-00-00Z_feature_peer-discovery.md)
- [Issue #2944](https://github.com/developing-today/code/issues/2944)
- [`pkgs/id/crates/id-core/src/discovery.rs`](../../pkgs/id/crates/id-core/src/discovery.rs)
- [`pkgs/id/src/commands/serve.rs`](../../pkgs/id/src/commands/serve.rs)
- [`pkgs/id/src/commands/peers.rs`](../../pkgs/id/src/commands/peers.rs)
1 change: 1 addition & 0 deletions doc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ Folders are named `<UTC datetime>_<kind>_<name>`. The kinds in use are `feature`
- [Project-management stack design](2026-10-24T11-05-38Z_design_project-management-stack/2026-10-24T11-05-38Z_design_project-management-stack.md)
- [T3 Code V2 integration](2026-10-26T21-18-21Z_feature_t3code-v2-integration/main.md)
- [PM stack forecasting: velocity, quota walls, and stall risk](2026-11-01T21-07-00Z_design_pm-stack_forecasting/2026-11-01T21-07-00Z_design_pm-stack_forecasting.md)
- [Authenticated peer announcements and bounded discovery](2026-11-02T08-13-35Z_design_peer-announcement-authentication/2026-11-02T08-13-35Z_design_peer-announcement-authentication.md)

Two names break the pattern. They stay as they are because other documents link to them: `2026-03-23T00:00:00Z_feature_file_list_ui/` has colons in its name, and `2026-10-14T10-18-19Z_design_p7_2_cloudflare_workers.md` is a file, not a folder.

Expand Down
217 changes: 203 additions & 14 deletions pkgs/id/crates/id-core/src/discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,11 +317,18 @@ pub const STALE_THRESHOLD: Duration = Duration::from_secs(120);
/// Set to 60 seconds. Peers older than [`STALE_THRESHOLD`] are removed.
pub const STALE_CHECK_INTERVAL: Duration = Duration::from_secs(60);

/// Maximum number of peer identities retained by one discovery table.
pub const MAX_PEERS: usize = 1_000;

/// Maximum UTF-8 byte length retained for a peer's advertised name.
pub const MAX_PEER_NAME_BYTES: usize = 256;

// ============================================================================
// Types
// ============================================================================

/// A peer's presence announcement, broadcast over the gossip channel.
/// A peer's presence claim. Gossip carries it inside the id crate's signed,
/// versioned envelope; this plain structure is also nested in `/iroh-meta/2`.
///
/// Serialized with [postcard](https://docs.rs/postcard) for compact binary
/// encoding. Typical size: ~50-100 bytes depending on name length.
Expand All @@ -347,10 +354,8 @@ pub const STALE_CHECK_INTERVAL: Duration = Duration::from_secs(60);
/// timestamp_secs: 1700000000,
/// };
///
/// // Serialize for gossip broadcast
/// let bytes = postcard::to_allocvec(&announcement).unwrap();
/// let decoded: PeerAnnouncement = postcard::from_bytes(&bytes).unwrap();
/// assert_eq!(decoded.blob_count, 42);
/// // Gossip senders wrap this claim in a signed, versioned envelope.
/// assert_eq!(announcement.blob_count, 42);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PeerAnnouncement {
Expand Down Expand Up @@ -379,9 +384,10 @@ pub struct PeerInfo {

/// Thread-safe in-memory peer table.
///
/// Collects [`PeerAnnouncement`] messages from the gossip channel and
/// tracks peer liveness. Provides methods to query known peers and
/// prune stale entries.
/// Collects authenticated [`PeerAnnouncement`] messages from the gossip
/// channel and tracks peer liveness. Callers must verify the signed gossip
/// envelope before calling [`update`](Self::update). Provides methods to
/// query known peers and prune stale entries.
///
/// This type is cheaply cloneable (backed by `Arc`) and safe to share
/// across async tasks.
Expand Down Expand Up @@ -452,8 +458,19 @@ impl PeerDiscovery {
/// deterministically — the most recent arrival wins.
///
/// An announcement that passes both checks replaces the stored one
/// (or inserts a new peer), stamped with the local arrival time.
/// (or inserts a new peer), stamped with the local arrival time. The table
/// retains at most [`MAX_PEERS`]: a new identity may replace the oldest
/// stale entry (ties break by endpoint-ID bytes); if every entry is fresh,
/// the new identity is refused. Names longer than [`MAX_PEER_NAME_BYTES`]
/// are refused. Existing identities can always refresh.
pub fn update(&self, announcement: PeerAnnouncement) {
if announcement
.name
.as_ref()
.is_some_and(|name| name.len() > MAX_PEER_NAME_BYTES)
{
return;
}
let now_secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
Expand All @@ -469,11 +486,29 @@ impl PeerDiscovery {
{
return;
}

let now = Instant::now();
if !peers.contains_key(&node_id) && peers.len() >= MAX_PEERS {
let victim = peers
.iter()
.filter(|(_, info)| now.duration_since(info.last_seen) >= STALE_THRESHOLD)
.min_by(|(left_id, left), (right_id, right)| {
left.last_seen
.cmp(&right.last_seen)
.then_with(|| left_id.as_bytes().cmp(right_id.as_bytes()))
})
.map(|(id, _)| *id);
let Some(victim) = victim else {
return;
};
peers.remove(&victim);
}

peers.insert(
node_id,
PeerInfo {
announcement,
last_seen: Instant::now(),
last_seen: now,
},
);
}
Expand Down Expand Up @@ -511,8 +546,8 @@ impl PeerDiscovery {

/// Removes peers that haven't been seen for longer than `max_age`.
///
/// Call this periodically (every [`STALE_CHECK_INTERVAL`]) to keep
/// the peer table from growing unboundedly.
/// Call this periodically (every [`STALE_CHECK_INTERVAL`]) to discard
/// peers that have not been heard from or successfully probed.
pub fn remove_stale(&self, max_age: Duration) {
if let Ok(mut peers) = self.peers.write() {
let now = Instant::now();
Expand All @@ -529,11 +564,36 @@ impl PeerDiscovery {
return Vec::new();
};
let now = Instant::now();
peers
let mut stale: Vec<_> = peers
.values()
.filter(|info| now.duration_since(info.last_seen) >= STALE_THRESHOLD)
.cloned()
.collect()
.collect();
stale.sort_by(|left, right| {
left.announcement
.node_id
.as_bytes()
.cmp(right.announcement.node_id.as_bytes())
});
stale
}

/// Removes `node_id` only if it is still older than `max_age`.
///
/// This is used after a bounded probe batch: a concurrent announcement or
/// successful probe can refresh the peer while its network probe is in flight.
pub fn remove_if_stale(&self, node_id: &EndpointId, max_age: Duration) -> bool {
let Ok(mut peers) = self.peers.write() else {
return false;
};
let now = Instant::now();
let should_remove = peers
.get(node_id)
.is_some_and(|info| now.duration_since(info.last_seen) >= max_age);
if should_remove {
peers.remove(node_id);
}
should_remove
}

/// Refreshes the `last_seen` timestamp for a peer, preventing it from
Expand Down Expand Up @@ -581,6 +641,12 @@ mod tests {
secret.public()
}

fn make_node_id_from_index(index: u64) -> EndpointId {
let mut key_bytes = [0u8; 32];
key_bytes[..8].copy_from_slice(&index.to_be_bytes());
iroh_base::SecretKey::from_bytes(&key_bytes).public()
}

fn now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
Expand Down Expand Up @@ -752,6 +818,18 @@ mod tests {
assert_eq!(peers[0].announcement.blob_count, 20);
}

#[test]
fn test_discovery_refuses_oversized_peer_names() {
let discovery = PeerDiscovery::new();
discovery.update(PeerAnnouncement {
node_id: make_node_id(88),
name: Some("x".repeat(MAX_PEER_NAME_BYTES + 1)),
blob_count: 1,
timestamp_secs: now_secs(),
});
assert_eq!(discovery.count(), 0);
}

#[test]
fn test_discovery_multiple_peers() {
let discovery = PeerDiscovery::new();
Expand Down Expand Up @@ -942,11 +1020,122 @@ mod tests {
assert_eq!(remaining[0].announcement.node_id, alive_id);
}

#[test]
fn test_peer_table_cap_evicts_oldest_stale_with_endpoint_id_tie_break() {
let discovery = PeerDiscovery::new();
let now = now_secs();
for index in 1..=u64::try_from(MAX_PEERS).unwrap() {
discovery.update(PeerAnnouncement {
node_id: make_node_id_from_index(index),
name: None,
blob_count: index,
timestamp_secs: now,
});
}

let first = make_node_id_from_index(1);
let second = make_node_id_from_index(2);
let tied_stale_time = Instant::now() - (STALE_THRESHOLD + Duration::from_secs(2));
{
let mut peers = discovery.peers.write().unwrap();
peers.get_mut(&first).unwrap().last_seen = tied_stale_time;
peers.get_mut(&second).unwrap().last_seen = tied_stale_time;
}
let expected_victim = [first, second]
.into_iter()
.min_by(|left, right| left.as_bytes().cmp(right.as_bytes()))
.unwrap();
let new_id = make_node_id_from_index(u64::try_from(MAX_PEERS).unwrap() + 1);

discovery.update(PeerAnnouncement {
node_id: new_id,
name: Some("new".to_owned()),
blob_count: 1,
timestamp_secs: now,
});

assert_eq!(discovery.count(), MAX_PEERS);
assert!(discovery.peers.read().unwrap().contains_key(&new_id));
assert!(
!discovery
.peers
.read()
.unwrap()
.contains_key(&expected_victim)
);
let other_stale = if expected_victim == first {
second
} else {
first
};
assert!(discovery.peers.read().unwrap().contains_key(&other_stale));
}

#[test]
fn test_peer_table_cap_keeps_fresh_entries_and_allows_existing_refresh() {
let discovery = PeerDiscovery::new();
let now = now_secs();
for index in 1..=u64::try_from(MAX_PEERS).unwrap() {
discovery.update(PeerAnnouncement {
node_id: make_node_id_from_index(index),
name: None,
blob_count: index,
timestamp_secs: now,
});
}
let new_id = make_node_id_from_index(u64::try_from(MAX_PEERS).unwrap() + 1);
discovery.update(PeerAnnouncement {
node_id: new_id,
name: Some("refused".to_owned()),
blob_count: 1,
timestamp_secs: now,
});
assert_eq!(discovery.count(), MAX_PEERS);
assert!(!discovery.peers.read().unwrap().contains_key(&new_id));

let existing_id = make_node_id_from_index(1);
discovery.update(PeerAnnouncement {
node_id: existing_id,
name: Some("refreshed".to_owned()),
blob_count: 2,
timestamp_secs: now + 1,
});
let peers = discovery.all_peers();
let existing = peers
.iter()
.find(|peer| peer.announcement.node_id == existing_id)
.unwrap();
assert_eq!(existing.announcement.name.as_deref(), Some("refreshed"));
assert_eq!(discovery.count(), MAX_PEERS);
}

#[test]
fn test_remove_if_stale_preserves_a_peer_refreshed_during_probe() {
let discovery = PeerDiscovery::new();
let node_id = make_node_id(77);
{
let mut peers = discovery.peers.write().unwrap();
peers.insert(
node_id,
PeerInfo {
announcement: make_announcement(77, Some("peer"), 5),
last_seen: Instant::now() - (STALE_THRESHOLD + Duration::from_secs(1)),
},
);
}

assert!(discovery.refresh(&node_id));
assert!(!discovery.remove_if_stale(&node_id, STALE_THRESHOLD));
assert_eq!(discovery.count(), 1);
}

#[test]
fn test_constants() {
assert_eq!(ANNOUNCE_INTERVAL, Duration::from_secs(30));
assert_eq!(STALE_THRESHOLD, Duration::from_secs(120));
assert_eq!(STALE_CHECK_INTERVAL, Duration::from_secs(60));
assert_eq!(MAX_PEERS, 1_000);
assert_eq!(MAX_PEER_NAME_BYTES, 256);
assert_eq!(DEFAULT_TOPIC, "id-peer-discovery-v1");
assert_eq!(DEFAULT_TOPIC_SECRET, b"id-public-discovery-v1");
}
Expand Down
9 changes: 6 additions & 3 deletions pkgs/id/src/commands/peers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ use anyhow::{Result, bail};
use iroh_base::EndpointId;
use iroh_mdns_address_lookup::MdnsAddressLookup;

use crate::discovery::{PeerAnnouncement, resolve_config};
use crate::discovery::{MAX_PEERS, PeerAnnouncement, resolve_config};
use crate::peer_announcement::SignedPeerAnnouncement;
use crate::protocol::{MetaRequest, MetaResponse};
use crate::store::load_or_create_keypair;
use crate::{CLIENT_KEY_FILE, META_ALPN, is_node_id};
Expand Down Expand Up @@ -444,9 +445,11 @@ async fn discover_via_gossip(options: &PeersOptions) -> Result<Vec<PeerAnnouncem
let _ = tokio::time::timeout(collect_timeout, async {
while let Ok(event) = receiver.next().await {
if let iroh_gossip::api::Event::Received(msg) = event
&& let Ok(announcement) = postcard::from_bytes::<PeerAnnouncement>(&msg.content)
&& let Some(announcement) = SignedPeerAnnouncement::decode_frame(&msg.content)
{
peers.insert(announcement.node_id, announcement);
if peers.contains_key(&announcement.node_id) || peers.len() < MAX_PEERS {
peers.insert(announcement.node_id, announcement);
}
}
}
})
Expand Down
Loading
Loading