Repository navigation
feat(node): bound DHT rate-limiter keyspace via lazy prune + periodic GC (#645) - #676
Conversation
… GC (#645) The `cdn/dht/v1` per-IP and per-peer keyed token-bucket maps could grow without bound under churning source IPs / NodeIds — same DoS shape that #440 fixed for the connection-level dispatch limiter. Ports the #440 pattern to `DhtRateLimiter`: - New `[dht.rate_limit] max_tracked_per_ip` / `max_tracked_per_peer` knobs (default 4096; `0` = unbounded with `tracing::warn!` on resolve, mirroring `security.max_tracked_sources`). - Opportunistic prune from `check` when `len() > cap + cap/10`, single-flighted via two independent `AtomicBool` flags (per-IP and per-peer prune in parallel) with `PruneGuard` RAII so a panic in `retain_recent` cannot stall the prune codepath. - Periodic `run_dht_rate_limit_gc` task at `DHT_RATE_LIMIT_GC_INTERVAL` (60s) driving both keyed layers per tick with `biased; stop_rx | ticker.tick()` shutdown contract. - New metrics: `decdn_dht_rate_limit_prune_sweeps_{per_ip,per_peer}_total` counters and `decdn_dht_rate_limit_tracked_{per_ip,per_peer}` gauges, written post-prune. 13 new tests cover both layers: noop-when-disabled, drops-refilled-buckets, lazy-prune bounded under flood (with sweep-counter assertion), unbounded-when-cap-zero, `PruneGuard` panic-safety, end-to-end metric scrape, runtime shutdown-promptness, and 6 resolver tests mirroring the `resolve_security_max_tracked_sources_*` precedent. Closes #645. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Coverage reportTotal: 89.01% (was 88.83%, ▲ +0.17%) — 20993/23586 lines
History
|
There was a problem hiding this comment.
Code Review
This pull request addresses a potential denial-of-service vulnerability by bounding the keyspace of the DHT rate-limiter. It introduces hard caps for per-IP and per-peer bookkeeping maps, along with opportunistic pruning and a periodic garbage collection task to manage stale entries. New metrics have also been added to monitor these maps and pruning activities. A review comment correctly points out that operational warnings during configuration resolution should use eprintln! instead of tracing::warn!, as the tracing subscriber may not yet be initialized during startup.
There was a problem hiding this comment.
Pull request overview
Ports the keyspace-bounding approach used by dispatch::ConnectionLimiter to the DHT request rate limiter so the per-IP and per-peer keyed limiter maps cannot grow without bound under churn, adding both opportunistic (hot-path) pruning and a periodic GC sweep integrated into the node runtime.
Changes:
- Added
[dht.rate_limit] max_tracked_per_ip/max_tracked_per_peerconfig knobs (default 4096;0= unbounded with resolver warning) and plumbed them through config resolution into the runtime. - Implemented lazy pruning (single-flight via
AtomicBool+ RAII guard) and periodic GC for per-IP/per-peer keyed DHT limiters, plus new metrics (sweep counters + tracked-size gauges). - Added unit/integration tests covering GC behavior, bounded growth under flood, the unbounded cap=0 contract, panic-safety of the guard, and metric emission.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/node/src/dht/rate_limit.rs | Adds keyspace caps, lazy-prune + periodic GC APIs, single-flight guards, and extensive tests for pruning/GC/metrics. |
| crates/node/src/runtime/mod.rs | Spawns/stops a new periodic DHT rate-limit GC task and adds a runtime test for prompt shutdown behavior. |
| crates/node/src/metrics.rs | Introduces new DHT prune sweep counters and tracked-size gauges with helper methods. |
| crates/common/src/config/types.rs | Adds new optional config fields under [dht.rate_limit] for max tracked entries per IP/peer. |
| crates/common/src/config/resolved.rs | Extends resolved DHT config with max_tracked_per_ip/max_tracked_per_peer defaults. |
| crates/common/src/config/mod.rs | Resolves the new config knobs, defaults them, and warns when set to unbounded (0), plus resolver tests. |
| crates/node/tests/dht_bootstrap.rs | Updates permissive DHT limiter test config to include the new required fields. |
| crates/node/tests/dht_loopback.rs | Updates permissive DHT limiter test config to include the new required fields. |
| CHANGELOG.md | Documents the new bounded-keyspace behavior, config knobs, GC cadence, and metrics. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
… wording
- `config::resolve_security_into` / `resolve_dht_into`: switch the
`max_tracked_sources == 0` and `max_tracked_per_{ip,peer} == 0`
warnings from `tracing::warn!` to `eprintln!` so they actually
surface — `tracing` is not initialized at `resolve_config` time
(per the rationale on `validate_port_layout_into`). The
`security.max_tracked_sources` warning had the same latent bug.
- `metrics::dht_rate_limit_tracked_per_ip` docstring: reword "until
the first GC tick after startup" to "until the first successful
prune (lazy or periodic) after startup" — the lazy-prune path in
`DhtRateLimiter::check` also writes this gauge.
- `runtime::run_dht_rate_limit_gc` panic-contract comment: spell out
that the lazy-prune path also writes the gauges, but on a quiet
node `check` is not called so the periodic sweep is the only
writer — which is why "fails to drop on a quiet node" is the
right alerting signal.
Refs PR #676 review comments.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Follow-up review pass on b399445. - `config::resolve_security_into`: also switch the two `tracing::info!` confirmations (`max_concurrent_handlers == 0`, `per_source_rate_per_sec == 0`) to `eprintln!("info: ...")`. They had the same latent bug as the warnings — tracing not initialized at `resolve_config` time — so operators who intentionally disabled either layer got zero confirmation. Consolidated the explanatory comment to cover both `info` and `warn` levels. - `runtime::run_dht_rate_limit_gc` panic-contract comment: add the empty-map caveat. "Fails to drop on a quiet node" only fires when the map was non-empty when the sweep died; a map that was already empty sits at `0` legitimately, indistinguishable from a healthy GC task on an empty map. Refs PR #676 multi-agent review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The dht_lookup.rs permissive limiter helper constructed DhtRateLimitConfig without max_tracked_per_ip / max_tracked_per_peer, added in #676 (#645). Since dht_lookup.rs landed in #673 in parallel, the field additions never reached it, breaking the test, MSRV, and clippy jobs on main. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ck map Address alpergundogdu's PR #713 review (the two actionable observations; #1 and the design note verified correct, no change). #2 per_hash_fallback aggregate timeout: a receiver that accepts the connection but never answers could pin one publish task for up to MAX_BATCH_STORE_HASHES x DHT_CLIENT_TIMEOUT (~34 min). Bail after MAX_CONSECUTIVE_FALLBACK_TIMEOUTS (3) back-to-back read timeouts; any answering outcome resets the run so a slow-but-responsive peer is not cut off. Thread the per-hash timeout as a parameter (prod passes DHT_CLIENT_TIMEOUT) and expose per_hash_fallback as a reusable building block for the #630 republish scheduler. New loopback test asserts exactly K streams open against a non-answering stub. #3 BatchStoreFallback size cap: DEFAULT_BATCH_FALLBACK_MAX_ENTRIES = 4096 (mirrors rate_limit max_tracked_per_peer); a new mark at capacity evicts the soonest-to-expire entry. No periodic GC -- unlike rate_limit's keyspace maps (keyed by attacker-supplied inbound IP/peer, hence #676's sweep) this map is keyed only by receivers the local node chose to publish to that returned a 0x01 close, so it is not externally inflatable and a static cap suffices. Unit tests cover cap eviction, no-evict-on-re-mark, and zero-cap clamp. fmt + clippy clean; node suite 318 pass (dht_loopback 21/21). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
) (#713) * feat(node): DHT BatchStore handler-side admission (closes #648) Implements ACs 17-20 of ADR 022 §Batch token accounting: publishers can now send a single BatchStoreRequest covering many hashes destined for one receiver instead of N separate Store RPCs (~80% wire-bytes reduction at C ≥ 10k cached blobs), with a per-hash Store fallback for receivers that don't implement batching. Handler admission (handlers/dht.rs, ACs 17/19): - Route BatchStore through handle_batch_store: batch-level holder == authenticated NodeId check once (mismatch -> MALFORMED_MESSAGE stream-close per ADR 022 step 2), then per-hash admission identical to N separate Stores (active-staker filter + RecordStore::insert_at) sharing one receiver-anchored receive_us. One bool per hash in request order. Oversize (>256) rejected at wire decode -> MALFORMED_MESSAGE. - Thread peer_ip into handle_one/dispatch; dispatch returns Result<_, app_code> for the stream-close case. Two-stage rate-limit accounting (rate_limit.rs, AC 18): - Refactor check() to share a metric-free try_admit_one; add admit_batch_extra() consuming up to n-1 more units cheapest-first with short-circuit, byte-for-byte equivalent to N separate Store admissions. Stage 1 (the frame token) is already charged in serve(). No rejection counter bump on the partial-admit boundary. Publisher fallback (batch_fallback.rs new, client.rs, AC 20): - BatchStoreFallback: bounded per-receiver unsupported_until cache (default 15 min), lazy expiry, clock-injected for tests. - client::batch_store primitive + batch_store_with_fallback: skips batch when cached unsupported; on an UNSUPPORTED (0x01) close caches the negative result + retries per-hash; malformed/too-large/rate-limited/ transport errors hard-fail (no per-hash storm). - Fix exchange_on: a peer stream-reset was collapsed by iroh's AsyncRead into an io::Error with no typed source, so extract_app_error_code lost the code and fallback never fired. Now probe recv.received_reset() and re-surface ReadError::Reset(code) typed. Metrics: dht_batch_store_received, dht_batch_store_hashes_deferred_rate_limit; per-hash outcomes reuse the existing dht_store_* counters. Tests: 13 unit (rate-limit, fallback cache, classifier) + 8 loopback (roundtrip, holder-mismatch MALFORMED, >256 MALFORMED, partial rate-limit admit, single-hash boundary, primitive roundtrip, batch-vs-fallback path selection, and end-to-end UNSUPPORTED-close -> cache -> per-hash fallback). Scope: the republish scheduler is not rewired to group hashes by receiver (that consumes these building blocks and belongs to #630); AC 20's publisher-MUST is satisfied by the tested batch_store_with_fallback helper. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * refactor(node): address PR #713 review feedback on BatchStore Apply automated-reviewer (gemini, copilot) findings; all behaviour- preserving except the metric-counting fix, which is covered by a new regression test. - client::per_hash_fallback: reuse a single QUIC connection across the fallback set via exchange_on instead of opening one connection per hash (up to 256 sequential handshakes). Each per-hash exchange keeps its own DHT_CLIENT_TIMEOUT. - handle_batch_store: lock the record store once before the loop (no .await inside) instead of per-hash; only lock on the active path. Fixes the inaccurate "rejecting remaining hashes" log spamming once per hash on a poisoned mutex (now logged once, "rejecting all hashes"). - handle_one: a dispatch Err(app_code) is a deliberate protocol rejection (holder-mismatch -> MALFORMED stream-close) already counted by dht_store_rejected_holder_mismatch; reset the stream and return Ok(()) so it no longer inflates dht_requests_failed (reserved for post- admission internal failures). New test asserts the counter split. - rate_limit::try_admit_one: add a `prune` flag; admit_batch_extra passes false. Stage-2 units key on the same (peer, ip) stage-1 already inserted, so they can't grow the keyed maps -> the per-unit prune check is redundant (bound upheld by stage-1 + periodic GC). - batch_store_with_fallback: guard an over-cap (>256) batch up front with a clear error log + per-hash fallback, instead of burning a doomed batch round-trip that looked like a normal all-false rejection. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * refactor(node): bound per-hash fallback wall-clock + cap batch-fallback map Address alpergundogdu's PR #713 review (the two actionable observations; #1 and the design note verified correct, no change). #2 per_hash_fallback aggregate timeout: a receiver that accepts the connection but never answers could pin one publish task for up to MAX_BATCH_STORE_HASHES x DHT_CLIENT_TIMEOUT (~34 min). Bail after MAX_CONSECUTIVE_FALLBACK_TIMEOUTS (3) back-to-back read timeouts; any answering outcome resets the run so a slow-but-responsive peer is not cut off. Thread the per-hash timeout as a parameter (prod passes DHT_CLIENT_TIMEOUT) and expose per_hash_fallback as a reusable building block for the #630 republish scheduler. New loopback test asserts exactly K streams open against a non-answering stub. #3 BatchStoreFallback size cap: DEFAULT_BATCH_FALLBACK_MAX_ENTRIES = 4096 (mirrors rate_limit max_tracked_per_peer); a new mark at capacity evicts the soonest-to-expire entry. No periodic GC -- unlike rate_limit's keyspace maps (keyed by attacker-supplied inbound IP/peer, hence #676's sweep) this map is keyed only by receivers the local node chose to publish to that returned a 0x01 close, so it is not externally inflatable and a static cap suffices. Unit tests cover cap eviction, no-evict-on-re-mark, and zero-cap clamp. fmt + clippy clean; node suite 318 pass (dht_loopback 21/21). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Summary
Closes #645. Ports the
dispatch::ConnectionLimiterkeyspace-bound fix(#440) to
dht::rate_limit::DhtRateLimiter. The per-IP and per-peergovernor::DefaultKeyedRateLimitermaps now have hard caps, anopportunistic prune from the hot path at
cap + cap/10, and a periodicGC task that runs
retain_recentevery 60s.[dht.rate_limit] max_tracked_per_ip/max_tracked_per_peer(default 4096;0= unbounded withoperator-warn on resolve, mirroring
security.max_tracked_sources).checkevaluatescheck_keythen runsmaybe_prune_per_*before dispatching on the result — preserves thecheapest-first short-circuit (global → per-IP → per-peer).
AtomicBoolflags (per-IP andper-peer prune in parallel) +
PruneGuardRAII so a panic inretain_recentcannot stick the flag.run_dht_rate_limit_gcmirrorsrun_dispatch_gc—biased; stop_rx | ticker.tick()for prompt shutdown; integrated intothe existing
JoinSet+ oneshot shutdown sequence.Counters(
decdn_dht_rate_limit_prune_sweeps_{per_ip,per_peer}_total) and twoGauges (decdn_dht_rate_limit_tracked_{per_ip,per_peer}), writtenpost-prune.
Test plan
cargo nextest run --workspace— 1116/1116 pass (13 new tests).cargo clippy --workspace --all-targets --all-features -- -D warningsclean.cargo fmt --all -- --checkclean.RUSTDOCFLAGS=-D warnings cargo doc --workspace --no-deps --document-private-itemsclean.pre-commit run --files <touched>— all hooks pass.New test coverage:
gc_per_{ip,peer}_is_noop_when_layer_disabledgc_per_{ip,peer}_drops_refilled_buckets(async, fast refill)lazy_prune_bounds_per_{ip,peer}_under_flood(200 distinct keys, cap=16, asserts sweep counter ≥ 1)unbounded_when_cap_is_zero_per_{ip,peer}(pins the operator opt-in contract)prune_guard_resets_flag_on_panic(panic-unwind viacatch_unwind)gauge_and_sweep_counter_emit_in_scrape(end-to-end metric scrape)run_dht_rate_limit_gc_exits_promptly_on_shutdown(shutdown-promptness contract)resolve_dht_max_tracked_per_{ip,peer}_{file_override,default_when_field_absent,accepts_zero_as_unbounded}(6 resolver tests)Out of scope
Three larger refactors raised in review and deferred as follow-ups:
KeyedLayer<K>generic wrapper to dedupemaybe_prune_per_{ip,peer}andgc_per_{ip,peer}into one impl per kind.single_flight::PruneGuardutility module spanning dispatch + DHT.enum GcOutcome { Disabled, CasLost, Swept{..} }to disambiguate the twoNonecauses for operator monitoring.Refs ADR 022 §DHT Rate Limiting.
🤖 Generated with Claude Code