Skip to content

fix(gossip): cap PeerTable to defeat fresh-keypair memory-DoS (#577 H3) - #656

Merged
thiras merged 3 commits into
mainfrom
fix/577-peer-table-cap
May 21, 2026
Merged

thiras merged 3 commits into
mainfrom
fix/577-peer-table-cap

Conversation

@thiras

@thiras thiras commented May 21, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Adds a hard cap on PeerTable entry count, configurable via gossip.max_peer_table_entries (default 100_000). Closes H3 of Protocol/gossip robustness & DoS hardening (peer-table cap, reconnect sender, frame padding, I/O classification) #577 — the unbounded-growth bug in crates/gossip/src/peer_table.rs::insert_or_refresh that let any peer mint signature-valid NodeAnnounces under fresh ed25519 keypairs and grow the in-memory HashMap without limit under the empty-allowlist PoC stand-in (crates/gossip/src/validation.rs:107-114).
  • Refreshes of existing entries always succeed so legitimate peers don't lose their slot under a fresh-keypair flood; the cap only bites on previously-unseen node IDs. A one-shot inline TTL sweep runs before rejection, so under organic load the cap effectively short-circuits to the existing 30s sweeper (crates/gossip/src/service.rs:428-444).
  • New InsertOutcome::RejectedFull variant + service.rs match arm that bumps inc_rejected("peer_table_full"). Label pinned by the existing validation::tests::reject_labels_are_stable test so dashboards/alerts can't silently break on a future rename.
  • Out of scope (separate PRs): H2 reconnect-sender, M3 trailing-byte padding cap, M1 probe handler I/O classification — all still open under Protocol/gossip robustness & DoS hardening (peer-table cap, reconnect sender, frame padding, I/O classification) #577.

Test plan

  • cargo nextest run -p decdn-gossip — 4 new peer-table unit tests (cap rejection, refresh allowed at cap, inline-sweep admits after expiry, 0 == unbounded) + 1 service-layer dispatch test asserting the metric label + that the size gauge is NOT bumped on a rejection.
  • cargo nextest run -p decdn-common — 3 new config tests (default applied, > 0 validation, file override).
  • cargo nextest run --workspace — 927/927 pass.
  • cargo clippy --workspace --all-targets -- -D warnings clean.
  • cargo fmt --check clean.
  • pre-commit run passes on the changed files (one pre-existing markdownlint failure on .github/workflows/issue-triage.md is unrelated).

Design notes

  • Reject-on-breach over LRU. Under the empty-allowlist threat model, LRU eviction would let an attacker churn fresh keypairs to push legitimate peers out. Reject-on-breach degrades gracefully — the table keeps serving the entries it already has.
  • Default 100_000. Order-of-magnitude sized like cache::engine::MAX_EVICTED_ENTRIES (1M, 32-byte payloads) adjusted for the heavier PeerEntry (~few hundred bytes incl. announce + endpoints) — tens of MB of resident memory ceiling, plenty of headroom for the tens-of-nodes PoC. Operator-tunable.
  • max_entries = 0 is the unbounded escape hatch. Used by every existing PeerTable::new(0) test/admin-fixture call site so the diff stays tiny. The config resolver rejects 0 so production paths can never reach it.

🤖 Generated with Claude Code

Closes the unbounded-growth bug at crates/gossip/src/peer_table.rs that
let any peer mint signature-valid NodeAnnounces under fresh ed25519
keypairs and grow the in-memory HashMap without limit under the empty-
allowlist PoC stand-in.

PeerTable::new now takes a max_entries cap. New IDs at the cap trigger
a one-shot inline TTL sweep; if no slot frees up, the insert returns
the new InsertOutcome::RejectedFull variant and the subscriber loop
bumps inc_rejected("peer_table_full") (label pinned by the existing
label-stability test). Refreshes of existing entries are always allowed
so legitimate peers don't lose their slot under a flood. max_entries=0
is preserved as an "unbounded" escape hatch for tests; the resolved-
config validator rejects 0 so production paths never hit it.

Configurable via gossip.max_peer_table_entries (default 100_000;
~tens of MB at the ~few-hundred-byte PeerEntry size).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 21, 2026 21:43

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a hard cap on the number of entries in the PeerTable to mitigate memory-based Denial-of-Service attacks. It adds a max_peer_table_entries configuration parameter (defaulting to 100,000), updates the PeerTable to enforce this limit through an inline TTL sweep when the cap is reached, and implements metrics for tracking rejections. Feedback highlights a potential CPU DoS vulnerability due to the O(N) complexity of the inline sweep at the default scale of 100,000 entries, suggesting the use of a slack threshold or single-flight guard to optimize performance and minimize lock contention under load.

Comment thread crates/gossip/src/peer_table.rs Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a configurable hard cap to the gossip PeerTable to prevent unbounded memory growth from fresh-keypair floods (issue #577 H3), threads the cap through config/resolution/runtime wiring, and ensures drops are surfaced via a stable rejection-metric label.

Changes:

  • Add gossip.max_peer_table_entries (default 100_000) to config types + resolution and plumb it into node runtime PeerTable construction.
  • Enforce the cap in PeerTable::insert_or_refresh with a new InsertOutcome::RejectedFull outcome and an inline TTL sweep attempt before rejecting.
  • Update gossip service dispatch + tests to emit inc_rejected("peer_table_full") on cap rejection and avoid touching the peer-table size gauge on rejection.

Reviewed changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
crates/node/tests/sighup_signal.rs Updates resolved-config test seed to include max_peer_table_entries.
crates/node/src/runtime/reload.rs Seeds reload test configs with max_peer_table_entries.
crates/node/src/runtime/mod.rs Constructs PeerTable with TTL + configured cap (cast to usize).
crates/node/src/admin.rs Updates admin tests/fixtures to new PeerTable::new(ttl, max_entries) signature.
crates/gossip/src/validation.rs Pins the new peer_table_full rejection label for stability.
crates/gossip/src/service.rs Handles InsertOutcome::RejectedFull by incrementing a stable rejection metric; adds service-layer test.
crates/gossip/src/peer_table.rs Implements cap + inline sweep and adds unit tests for cap behavior.
crates/common/src/config/types.rs Adds max_peer_table_entries to GossipConfig TOML type.
crates/common/src/config/resolved.rs Adds resolved max_peer_table_entries field to ResolvedGossip.
crates/common/src/config/mod.rs Adds default + validation + resolution wiring for gossip.max_peer_table_entries; adds tests.
crates/cli/tests/config_validate.rs Updates CLI resolved-config fixture with max_peer_table_entries.
crates/cli/tests/admin_peers.rs Updates admin CLI tests to new PeerTable::new(ttl, max_entries) signature.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/gossip/src/peer_table.rs Resolved
Comment thread crates/gossip/src/service.rs Resolved
@github-actions

github-actions Bot commented May 21, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 90.11% (was 89.97%, ▲ +0.14%) — 17026/18894 lines

File Coverage Lines Δ
crates/common/src/config/mod.rs 96.37% 4356/4520 ▲ +0.03%
crates/gossip/src/peer_table.rs 98.97% 288/291 ▲ +2.77%
crates/gossip/src/service.rs 41.90% 132/315 ▲ +10.42%
crates/gossip/src/validation.rs 100.00% 251/251 ● 0.00%
crates/node/src/admin.rs 95.80% 616/643 ● 0.00%
crates/node/src/runtime/mod.rs 51.01% 406/796 ● 0.00%
crates/node/src/runtime/reload.rs 95.98% 1385/1443 ▲ +0.01%
History
Commit Total Δ vs base
b6658be 90.01% ▲ +0.04%
864a1e9 90.03% ▲ +0.06%
75a26dc (HEAD) 90.11% ▲ +0.14%

thiras and others added 2 commits May 22, 2026 00:53
…eview)

Addresses the CPU/lock-contention finding on PR #656: without throttling,
a fresh-keypair flood at cap forced a full O(N) `HashMap::retain` per
signature-valid announce while holding the write lock — moved the
original memory-DoS into a CPU-DoS.

Adds `last_inline_sweep_us` + `MIN_INLINE_SWEEP_INTERVAL_US` (1 s) so the
inline sweep runs at most once per second; rejected inserts in between
are O(1). The 30 s background sweeper still runs in parallel — the
inline sweep is only the cap-pressure short-circuit. First call always
fires via the sentinel-0 path so the existing
`inline_sweep_on_full_admits_new_after_expiry` test remains valid; a
new `inline_sweep_is_throttled_under_sustained_flood` test pins the
throttle behaviour against regressions.

Also addresses the test-recorder review: replace `if let Ok` Mutex
pattern with `.lock().unwrap()` so a poisoned mutex surfaces as a clear
panic rather than a silently-incorrect event count (test module
already opts into `unwrap_used`).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…tch helper

Follow-up on PR #656 review (code-reviewer, pr-test-analyzer,
comment-analyzer findings):

- Extract `dispatch_insert` from `subscriber_task` into a `pub(crate)`
  helper so the subscriber loop and the contract test call the same
  code. Eliminates the inline-mirror drift surface where a future
  change to one match arm could slip past the other.
- Add `#[cfg(test)]` accessor for `PeerTable::last_inline_sweep_us` and
  use it in `inline_sweep_is_throttled_under_sustained_flood` to assert
  the throttle's *CPU-bound contract* directly: the sweep timestamp
  must NOT advance on a throttled call. A regression that re-ran the
  sweep but discarded the result would still produce `RejectedFull`,
  and would silently pass without this assertion.
- Add `throttle_still_binds_one_microsecond_below_interval` — boundary
  partner to the existing exact-interval release, mirroring the
  `evict_at_exact_cutoff` / `one_microsecond_past_cutoff` discipline.
- Add `throttle_holds_under_clock_reversal` — exercises the
  `saturating_sub` defensive path. A regression to bare subtraction
  would underflow on a backward NTP step or VM-resume with stale wall
  clock; this test pins the safe-direction behaviour.
- Fix narrative drift in the existing throttle test comment (claimed
  "C is the only entry" at t=500 when the test inserts a filler first;
  same omission in the t=400+1s explanation).
- Fix stale `service.rs:308` line citation in the dispatch test
  doc-comment — the test now calls the helper directly, so the cited
  line is replaced by a description of the contract.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras merged commit c80667f into main May 21, 2026
19 checks passed
@thiras
thiras deleted the fix/577-peer-table-cap branch May 21, 2026 22:16
thiras added a commit that referenced this pull request May 21, 2026
…M1) (#659)

Closes #577 M3 + M1, the two remaining items from the original review (H2/H3 already shipped in #656/#657).

Four commits squashed:
- M3: validation.rs trailing-bytes cap (`MAX_TRAILING_BYTES = 4 KiB`, `OversizeTrailingBytes` variant + `oversize_trailing_bytes` label, boundary pair, sig-ordering test)
- M1: probe.rs `FrameError::Io → APP_ERR_NO_ERROR` (split out of MALFORMED), named const, truncation integration test
- ADR 013: §Application Error Codes table rewritten to match new Io→0x00 mapping (Copilot review)
- Forensic `tracing::warn!` at service-layer caller for `OversizeTrailingBytes` only, doc tightenings (5 review-followup items)

Detection-only on the M3 side: iroh-gossip 0.98 doesn't expose a per-subscription max-message knob, so the upstream 16 MiB allocation happens before validation. Tracking the deeper fix (per-ALPN frame ceiling) at #660.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants