Skip to content

fix(dht): check discovery response public key before removing in-flight entry - #8377

Open
aswadi wants to merge 3 commits into
tari-project:developmentfrom
aswadi:fix/dht-discovery-inflight-hardening
Open

aswadi wants to merge 3 commits into
tari-project:developmentfrom
aswadi:fix/dht-discovery-inflight-hardening

Conversation

@aswadi

@aswadi aswadi commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Check that an inbound DiscoveryResponseMessage's public key matches the expected public key of the pending inflight_discoveries entry before removing the entry, banning the mismatched responder while keeping the pending request intact so the requester waits for the real peer's reply (or its own timeout) rather than receiving an immediate ReplyCanceled.
  • Skip sending a discovery message or inserting an in-flight entry if reply_tx.is_closed() when initiate_peer_discovery runs.

@aswadi aswadi closed this Nov 23, 2026
@aswadi
aswadi force-pushed the fix/dht-discovery-inflight-hardening branch from 0c2dfd5 to c644942 Compare November 23, 2026 08:00
@aswadi aswadi reopened this Nov 23, 2026

@SWvheerden SWvheerden left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this. The code is tidy, merges cleanly onto development, and fmt, clippy (-p tari_comms_dht), the 296 dht lib tests and the discover integration tests all pass. The problem is that most of the change guards against conditions that cannot happen on development, and two parts change behaviour for the worse. Please cut it down to the part that is a real improvement.

1. The "spoofing" premise cannot be reached; keep the reorder only as defence-in-depth (service.rs:255-310)

A response with the right nonce and the wrong key cannot come from a third party:

  • send_discover sends the DiscoveryMessage with OutboundEncryption::EncryptFor(dest_public_key), so only the target can read the nonce.
  • The reply goes back with direct_public_key and is never forwarded, so relays never see it either.
  • handle_discover_response (inbound/dht_handler/task.rs:480-540) only passes on a response whose signer, source and claimed key are the same.

So the only peer that can produce a mismatched response is one the target gave its own nonce to, and the target could just as well not reply. Peeking before removing is harmless and cheap, so I'm fine keeping it with its test. Please reword the PR description and commit message so they don't claim a spoofing fix.

2. Remove the expiry, cap/eviction, unique-nonce and cleanup-tick machinery (service.rs:57-59, 76-78, 123-147, 174-233, 404-424)

  • Expiry is redundant. Every caller goes through DhtDiscoveryRequester::discover_peer, which times out after the same discovery_request_timeout (dht.rs:264). Its timer starts before the request is even queued, while start_ts is set only after send_discover resolves. So reply_tx is always closed before is_expired can be true, and is_closed() already covers it.
  • The table is not unbounded on development. The only insert is in initiate_peer_discovery, which drops every closed entry first. The table holds the live callers plus whatever was cancelled since the last insert.
  • The 1024 cap adds a new failure mode: when it is hit, the oldest entry is evicted even if its caller is still waiting, and that caller gets ReplyCanceled early instead of its answer.
  • A collision among at most ~1024 random u64 nonces is about 2^-54, so next_unique_nonce never loops.
  • The periodic tick only frees a handful of cancelled entries between two discoveries. That doesn't justify a new timer in the service loop.

Please drop is_expired, MAX_INFLIGHT_DISCOVERIES/evict_oldest_inflight_discovery, next_unique_nonce, the cleanup interval, has_live_request_for, the live_peers sibling-pruning logic and their tests. Keep the original retain(!is_closed) in initiate_peer_discovery.

3. Don't drop valid late responses (service.rs:259, 400-420)

On development, a validly signed response that arrives after its caller gave up is still validated and written to the peer DB, provided no new discovery has pruned the entry yet. The next send to that peer then succeeds without another network-wide discovery.

The PR prunes before the lookup, so these responses are now thrown away, and the tests expired_discovery_response_is_ignored_without_updating_peer_manager and cancelled_sole_discovery_is_pruned_and_late_response_does_not_add_peer lock that in. One concrete case: tari_pulse_service (base_layer/core/src/base_node/tari_pulse_service/mod.rs:467) gives up after 90 s, while the DHT timeout is 120 s, so a target that answers between 90 s and 120 s is never recorded.

The response is signed by the peer and goes through PeerValidator, so there is no security reason to reject it. Please keep the development behaviour.

Non-blocking

  • The "skip registration when reply_tx is already closed" check (service.rs:412) runs after the Discovery has already been broadcast, so it saves no network work. If you want an early return, check reply_tx.is_closed() before send_discover.
  • The commit body is just an empty Closes #.
  • idle_run_loop_prunes_expired_inflight_discoveries and resolving_one_peer_preserves_other_peer_cancelled_sibling would hang on reply_rx.await rather than fail if they regressed. Wrap the awaits in a timeout if any of these tests survive.

No other open PR touches discovery/service.rs. #8368 (per-origin Discovery cooldown) changes only the inbound dht_handler and merges cleanly alongside this.

@aswadi aswadi closed this Nov 24, 2026
@aswadi
aswadi force-pushed the fix/dht-discovery-inflight-hardening branch from 1526110 to ae2296b Compare November 24, 2026 16:03
@aswadi aswadi changed the title fix(dht): harden discovery in-flight state against spoofing, expiry, and unbounded retention fix(dht): check discovery response public key before removing in-flight entry Nov 24, 2026
@aswadi

aswadi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the clear review @SWvheerden! I've narrowed the PR on top of development to address all three items:

  1. Kept the public-key peek before removing as defence-in-depth & reworded commit/PR description: Removed any spoofing claims from the commit message, PR title, and PR description, and extended a_mismatched_response_bans_the_responder to verify the in-flight entry remains intact and resolves when the requested peer replies.
  2. Removed expiry, cap/eviction, unique-nonce, and cleanup-tick machinery: Dropped is_expired, MAX_INFLIGHT_DISCOVERIES, evict_oldest_inflight_discovery, next_unique_nonce, the cleanup interval, has_live_request_for, and the sibling-pruning logic, keeping development's filter(|(_, state)| !state.reply_tx.is_closed()) in initiate_peer_discovery.
  3. Preserved valid late responses & early-checked reply_tx.is_closed() before send_discover: Restored development's lookup behavior so late valid responses still update the peer DB, and checked if reply_tx.is_closed() { return Ok(()); } before send_discover.

@aswadi aswadi reopened this Nov 24, 2026
@aswadi aswadi closed this Nov 25, 2026
@aswadi
aswadi force-pushed the fix/dht-discovery-inflight-hardening branch from 3e841b6 to d48066d Compare November 25, 2026 11:17
@aswadi aswadi reopened this Nov 25, 2026
@aswadi aswadi closed this Nov 25, 2026
@aswadi
aswadi force-pushed the fix/dht-discovery-inflight-hardening branch from eb6d35f to d48066d Compare November 25, 2026 11:24
@aswadi aswadi reopened this Nov 25, 2026
@aswadi aswadi closed this Nov 25, 2026
@aswadi
aswadi force-pushed the fix/dht-discovery-inflight-hardening branch from 3152096 to d48066d Compare November 25, 2026 11:26
@aswadi aswadi reopened this Nov 25, 2026
Comment thread comms/dht/src/discovery/service.rs Resolved
Comment thread comms/dht/src/discovery/service.rs Resolved

@SWvheerden SWvheerden left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for cutting this down. All three items from the last round are addressed. The key check now runs before the entry is removed, the expiry/cap/cleanup machinery is gone, and late valid responses still reach the peer DB as on development. On this head, nightly fmt, cargo lints clippy -p tari_comms_dht (no new warnings), the 290 dht lib tests and the discover integration tests all pass, and it merges cleanly onto current development.

Before approving we need every new expression to be minimal. Three small changes:

  1. comms/dht/src/discovery/service.rs:177-181: don't clone the key on every response. .map(|request| (*request.public_key).clone()) copies the expected key for every response whose nonce matches, including the normal, matching case. The copy only exists so the warning can print the key on a mismatch. Compare inside the borrow instead. self.inflight_discoveries and self.dht are separate fields, so the borrow can live across the ban_peer await. This compiles and passes the tests:

    if let Some(request) = self.inflight_discoveries.get(&discovery_msg.nonce) &&
        discovery_msg.public_key.as_bytes() != request.public_key.as_bytes()
    {
        let expected_public_key = &request.public_key;
        // ... warn!/ban_peer as now

    While you're there, move the comment above the if let so it describes the check rather than sitting inside the branch.

  2. service.rs:306-309: generate the nonce after the early returns. rand::rng().next_u64() now runs before the reply_tx.is_closed() and self-discovery returns, which never use it. Move let nonce = ... down to just before send_discover.

  3. Add a test for the new closed-reply_tx skip. It is new behaviour and nothing covers it. Something like: drop the receiver, call initiate_peer_discovery directly, then assert the outbound mock recorded no call and inflight_discoveries is empty.

Non-blocking:

  • The existing send_discovery test (1 ms requester timeout) now depends on the service task being polled before the test task wakes from its timeout. That holds on the single-thread #[tokio::test] runtime, but a short comment there would stop someone switching it to multi_thread and making it flaky.
  • The PR description could mention that a requester whose request gets a mismatched response now waits for its own timeout (or the real peer's reply) instead of getting ReplyCanceled straight away. That is intended.

@aswadi

aswadi commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @SWvheerden! Pushed GPG-signed commit 954b4204ec addressing all 3 items (and both non-blocking items):

  1. Avoided key clone on response: Borrowed request directly from self.inflight_discoveries.get(&discovery_msg.nonce), compared discovery_msg.public_key.as_bytes() != request.public_key.as_bytes(), and moved the comment above the if let.
  2. Deferred nonce generation: Moved let nonce = rand::rng().next_u64(); after the reply_tx.is_closed() and self-discovery early returns.
  3. Added initiate_peer_discovery_skips_closed_reply_channel: Verified that dropping reply_rx before initiate_peer_discovery records 0 outbound calls and leaves inflight_discoveries empty.

@SWvheerden SWvheerden left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the quick turnaround. All three items from the last round are in: the key is compared by borrow (no clone), the nonce is generated after the early returns, and there is a new test for the closed reply_tx skip. fmt (nightly-2026-06-01) is clean, clippy adds no new warnings, and the tari_comms_dht lib tests (302) pass on a local merge with development.

One thing left, in the new test.

initiate_peer_discovery_skips_closed_reply_channel cannot fail. It hangs, and its call_count assertion always passes (service.rs, new test)

The test never starts the outbound mock. call_count() only goes up inside OutboundServiceMock::run, so assert_eq!(oms_mock_state.call_count().await, 0) holds whatever the code does. If the reply_tx.is_closed() guard is removed, send_discover queues the request on the mock's channel and then waits forever for a reply that only the running mock would send. I checked this locally: with the guard removed, the test hangs past 60 s and never reaches its assertions. In CI that only shows up as a nextest timeout after 6 minutes.

Fix (one line, same as send_discovery does):

let (outbound_requester, outbound_mock) = create_outbound_service_mock();
let oms_mock_state = outbound_mock.get_state();
task::spawn(outbound_mock.run());

I checked this locally too. With the line added, the test passes with the guard in place. With the guard removed it fails at once with left: 1, right: 0, and the inflight_discoveries.is_empty() check would fail as well.

Non-blocking: the third bullet in the PR body ("Resolve all matching non-closed in-flight requests ... even if the primary request's receiver was dropped") describes behaviour that is already on development. This PR does not change it, so please drop that bullet.

With the mock started, this is ready to approve from my side.

@aswadi

aswadi commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Good catch @SWvheerden, thank you! Pushed GPG-signed commit cb66afea5b spawning outbound_mock.run() in initiate_peer_discovery_skips_closed_reply_channel, and dropped the third bullet from the PR description.

This branch has not been deployed

No deployments
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