Repository navigation
cl/sentinel: honour the peer ban on inbound connections - #23606
Conversation
domiwei
left a comment
There was a problem hiding this comment.
Requesting changes for two related lifecycle issues.
-
cl/sentinel/discovery.go:562-568checksBanStatusbefore gate admission, leaving a TOCTOU window. Event B can observe not-banned and pause; event A can complete the third failing handshake, install the ban, and release; then B can acquire and callValidatePeerfor the now-banned peer. Acquire first and check or recheck the ban inside the serialized section before handshaking. -
The new tests exercise only
handshakeGate; removing the newonConnectionwiring leaves all of them green. The burst test also never releases its winner, so serial execution still admits exactly one. Because the issue and PR both say the observed production ordering is unverified, please add a deterministic production-sequence test coveringonConnection -> BanStatus -> ValidatePeer -> RecordHandshakeFailure, three failures reaching the ban, release on all exits, and the next inbound event closing without another handshake.
The focused cl/sentinel suite passes normally and under -race, but it does not cover these sequences.
|
Both findings addressed in 69196c7. TOCTOU — you are right, and the window is not where I would have guessed it. The gate is now taken first and the ban is read while it is held, so a ban installed by a handshake that completed while this event waited is visible before Tests — your critique is correct and it is the second time I have made it: the four gate tests exercised
I verified they bite by mutation rather than assuming:
One limit worth stating plainly: these tests pin that the ban is consulted and that a ban installed during an earlier handshake is honoured by the next event. They do not deterministically pin the ordering of acquire-versus-check, because that interleaving needs a hook inside the function to reproduce. If you want that guaranteed against future edits, I can add a test seam for it — say the word and I will. |
domiwei
left a comment
There was a problem hiding this comment.
The production TOCTOU is fixed correctly at 69196c7: gate admission now precedes BanStatus, so a same-peer event cannot carry a stale ban observation past the third failing handshake. One blocking regression-test gap remains.
The new sequence tests still pass if BanStatus is moved back above tryAcquire, which restores the exact bug, and they also pass if the onConnection -> exchangeStatus wiring is deleted. TestExchangeStatusRefusesAPeerBannedWhileTheEventWaited pre-bans the peer before the call; no event actually waits or crosses the check/admission boundary because busy admission is dropped.
Please add a deterministic production-sequence seam that distinguishes the ordering: prove gate ownership exists when ban status is observed, and enter through onConnection or a directly invoked production handler. The sequence should pause one validation, submit a same-peer event and an unrelated peer, complete the third failure, then assert the next inbound event closes without validation. This should fail if ban observation is moved before admission or if the onConnection wiring is removed.
The full cl/sentinel package passes normally and under -race; this request is specifically about pinning the production regression.
|
Fixed in f116f2d. You were right that the previous tests pinned nothing — they only observed outcomes, and the outcome is identical either way because admission is non-blocking, so The seam. The entry point. The sequence is the one you described: a first handshake for peer A pauses mid-flight holding the slot; a second same-peer event is refused without validating; an unrelated peer B proceeds anyway; A resumes; two more failures reach the three-strike ban; the next A event closes it without a handshake; every exit leaves Mutation results, both fast:
One detail worth flagging, since I hit it: my first version asserted inside the handshake goroutine with
|
|
I took another pass at the current head ( One blocking test gap remains:
Because both #23605 and this PR say that the production event ordering was not reproduced, please add a deterministic test entering through Two lower-priority cleanup items:
Validation on this head: One adjacent, non-blocking risk: a pure initial |
|
Thanks — two of the four are fixed in 46e880f. Comment policy. Trimmed Paused-handshake deadlock.
On the blocking item — you are right on both counts: nothing enters through I would rather fix it than downgrade the issue link. My plan: two real in-memory hosts, actually connected, enter through If you would prefer to avoid that field, say so and I will take your alternative instead — Your last point — a pure |
domiwei
left a comment
There was a problem hiding this comment.
The ban check is now correctly inside the per-peer gate. Requesting changes for one introduced reconnection regression, detailed inline: a replacement connection can lose its only status-validation event while the previous connection is being rejected.
The focused handshake/gate/handler tests pass normally and with -race. A deterministic scratch regression test reproduces the replacement-connection failure in all three runs; a control using the same test with only gate admission/drop/release removed passes all three runs. That control isolates the cause; removing serialization is not the proposed fix.
Non-blocking test cleanup:
handshake_sequence_test.go:63: replacewaitForInFlightwith a direct assertion. Receivingenteredalready establishes acquisition, andresumekeeps the handshake paused. The helper andtimeimport can go.handshake_sequence_test.go:84: thevalidatedAmutex/wrapper is unnecessary;enteredandwg.Wait()already order its accesses. These two simplifications remove about 13 lines.testSentinel()creates two positive-TTL cache cleaner goroutines per call throughpeers.NewPool(nil). The pinned expirable LRU has no working close API, so the four new fixture uses retain eight goroutines per suite repetition. A bounded fixture arrangement would help; a broader Pool/LRU lifecycle redesign should be a separate follow-up.
Only the reconnection regression is blocking this review.
| // exchangeStatus runs one status handshake for peerId and reports whether the peer was kept. | ||
| // The ban must be read while the slot is held: a handshake completing meanwhile may install it. | ||
| func (s *Sentinel) exchangeStatus(peerId peer.ID, banned func(peer.ID) bool, validate func() (bool, error), closePeer, dropPeer func(peer.ID)) bool { | ||
| if !s.handshakeGate.tryAcquire(peerId) { |
There was a problem hiding this comment.
[P2] Preserve status validation for replacement connections during rejection
Dropping every same-peer event while the slot is held assumes the in-flight verdict also handles any replacement connection. That is not true across closePeer/dropPeer:
- Connection A's status is rejected (
valid == false,err == nil). Its handler still owns the gate while closing the peer. - libp2p
ClosePeertakes a snapshot of current connections and closes those connections. - The same peer establishes connection B after that snapshot, before A's handler returns and releases the gate.
- B's connection callback reaches this branch and is dropped. A's close did not include B, and releasing the gate does not schedule another validation, so B remains connected without a status check.
The previous implementation ran a separate validation for B. This is therefore an introduced regression in the existing fork-mismatch rejection behavior.
I reproduced this with two libp2p mocknet hosts, real connection notifications, and the production handleNewConnection handler. The test substitutes a rejecting validator and pauses a wrapped Network.ClosePeer after the underlying close but before returning; it reconnects the peer and waits for B's handler to finish before releasing A. All three runs report validation calls=1, live replacement connections=1. This deliberately stretches a valid scheduling window; it is not a live-network reproduction.
Please distinguish replacement connections from duplicate events, or preserve sufficient pending work to validate/close a replacement after rejection, while retaining the one-active-handshake invariant. Add a deterministic regression test that observes the replacement connection's actual validation/closure.
…ound onConnection handles every connection event on its own goroutine, so a burst of events for one peer started a handshake for each. The three-strike ban could not intervene: all of them completed before any raised the failure count to its threshold. It also only consulted the ban in ConnectWithPeer, which covers dials we initiate and not the events that arrive anyway. A gnosis archive node reached 101 attempts against a single peer in two minutes, and 13,827 handshake failures across 1,638 peers in ninety minutes, until libp2p's own dialer began refusing with "rate limit exceeded". Banned peers are now closed before the handshake, and a per-peer gate admits one attempt at a time so the ban threshold is reachable. Concurrent events for the same peer are dropped rather than queued: the peer is about to be judged by the attempt already running. Closes #23605
Checking BanStatus before admission left a window: an event could observe the peer as not banned, a concurrent handshake could complete the third failure and install the ban, and the first event could then acquire the gate and handshake a peer that is already banned. Extracts the status exchange into exchangeStatus so the gate is taken first and the ban is read while it is held, and so the sequence is reachable from a test. The connection handler keeps its subnet and peer-limit checks. The previous tests only exercised handshakeGate in isolation, leaving the wiring unpinned: deleting it kept them green. The new tests drive the whole sequence against a real peers pool - three transport failures reaching the ban, the next event closing the peer without another handshake, a concurrent event for the same peer refused, and a fork mismatch dropped without counting toward the ban - and each exit path leaving the gate released.
The previous tests passed with BanStatus moved back above tryAcquire, so they did not pin the fix at all. They only observed outcomes, and the outcome is the same either way when admission is non-blocking. Injects the ban reader into exchangeStatus, so a test can assert the peer's handshake slot is already held at the moment the ban is read - which is false if the read moves back above admission. Splits onConnection's body into handleNewConnection so the handler itself is reachable without a live handshaker. The sequence test pauses one handshake mid-flight, submits a second event for the same peer and one for an unrelated peer, releases, drives two more failures to reach the pool ban, and asserts the next event closes the peer without handshaking it. Violations are counted rather than asserted inside the handshake goroutine: a failed require there would Goexit and turn a regression into a ten-minute timeout instead of a named failure. Verified both regressions fail fast: reading the ban before admission, and deleting the handleNewConnection wiring.
…n failure Cuts the production comments to the invariant and drops the incident measurements from the test docstring, per the repository comment policy. The sequence test closed its resume channel only after several assertions, so a regression reaching FailNow first left the paused handshake goroutine parked and the failure surfaced as a timeout. Registers the release as cleanup, which runs after Goexit: a forced early failure now reports in under a second.
The connection callback never read the ban list. Handshake failures were recorded and the three-strike ban was installed, but nothing consulted it on the inbound path, so a banned peer was handshaked again on every reconnect - 101 handshakes against one peer in two minutes on a gnosis node. Reads the ban before handshaking, and closes the peer instead. Splits the callback body into handleNewConnection so the sequence is reachable from a test. Drops the per-peer handshake gate from earlier revisions of this change. It was an optimisation against duplicate concurrent handshakes, not the fix, and it introduced a regression: a replacement connection arriving while the previous one was being closed had its only status validation dropped and stayed connected unvalidated. Reducing duplicate handshakes is worth doing separately, with event coalescing so no connection loses its validation.
46e880f to
6242da5
Compare
|
You found a real regression, and chasing it led me to conclude the gate should not be in this PR at all. Rebased on current main and reduced to the actual fix in 6242da5. Why I dropped the gate. I went back to the original So the fix is now just the ban read, plus splitting the callback body into Your regression is structurally gone. With no serialization, a replacement connection gets its own validation exactly as it did before this PR. Nothing is dropped, so there is no lost-validation window to reason about. Tests use two real hosts with a live connection, so the close is observable rather than a no-op on an absent connection:
Mutation-verified rather than assumed:
Follow-ups I will file separately rather than widen this: duplicate-handshake coalescing done properly; the |
domiwei
left a comment
There was a problem hiding this comment.
The blocking reconnection regression is resolved in 6242da5. Removing the per-peer gate preserves validation of replacement connections, while the early ban check applies the existing ban policy to connection events.
I re-reviewed the cumulative diff and found no new blocking correctness issue. The original deterministic reconnect test, adapted only to the new fixture signature, passes all three runs: two validations and zero remaining connections. The full cl/sentinel package passes normally and with -race; the race run also includes that reconnect test. Removing only the new ban guard in a temporary test overlay makes the ban tests fail as expected.
Approving with two non-blocking comments:
- Please update the PR title and description. They still describe the removed per-peer gate, dropped concurrent events, and 64-acquire burst test. The current change is inbound ban enforcement; the latest commit message already describes that narrower scope accurately.
- The test fixture still creates two permanent TTL-cache cleanup goroutines per
peers.NewPoolcall, leaving eight workers per suite repetition. A bounded fixture arrangement would help. A broader shared Pool/LRU lifecycle redesign can remain a separate follow-up.
The reconnect test uses mocknet connections and an injected status verdict; it verifies the reported ordering regression, not the original live-network attempt-rate measurements.
|
Thanks — both non-blocking comments are handled. Title and description. Updated to describe the merged change: inbound ban enforcement plus Test fixture. #23847. One shared pool for the whole package instead of one per test. Safe Your count was exactly right. A probe counting surviving cleanup goroutines gives eight per The broader lifecycle point is #23848 as you suggested. One detail that makes it tractable: |
Closes #23605.
The three-strike ban in
peers.Poolwas written and never read on the inbound path.RecordHandshakeFailureinstalled the ban, but onlyConnectWithPeerconsulted it, and thatcovers dials we initiate — not the connection events that arrive regardless. A banned peer
therefore got a fresh status handshake on every reconnect.
Measured on a gnosis archive node: 101 attempts against a single peer in two minutes, 13,827
handshake failures across 1,638 distinct peers in ninety minutes, and 460 dials refused by
libp2p's own dialer with
rate limit exceeded.Change
BanStatusin the connection handler and close banned peers before handshakinghandleNewConnection, reporting whether the peer was kept, sothe inbound path is reachable from a test
Retained-peer behaviour is untouched. Keeping a peer whose status exchange failed on a
transport error ("may still work for gossip") is deliberate and unchanged — only the rate at
which a banned peer is re-attempted changes.
Tests
cl/sentinel/ban_on_connection_test.gouses two real connected hosts, so closing the peer isobservable rather than a no-op against an absent connection. It covers entry through
onConnectionwith a realnetwork.Conn, and drives #23605 end to end: three transportfailures reach the ban, then the next event closes the peer without validating again.
Mutation-verified rather than assumed: removing the ban read fails
TestBannedPeerIsClosedInsteadOfHandshaked; makingonConnectionbypasshandleNewConnectionfailsTestOnConnectionClosesABannedPeer.History, for anyone reading the commit message
Earlier revisions also added a per-peer gate admitting one handshake at a time. @domiwei showed
it dropped replacement connections created during
closePeerand lost their validation, whichwas a regression against the existing fork-mismatch path, so the gate was removed — the ban
read is the whole fix. The squash commit message predates that removal and still describes the
gate, the dropped concurrent events and a burst test, none of which are in the merged code.
Follow-ups tracked separately: duplicate-handshake coalescing done correctly, the
ConnectWithPeer -> Host.Connectfailure path that never records a handshake failure, andenforcing the ban in
Gater.InterceptSecuredso a banned peer is dropped before the connectionis upgraded.