Skip to content

Retry the integration test webhook server when it loses its port - #9211

Merged
cert-manager-prow[bot] merged 3 commits into
cert-manager:masterfrom
wallrj-cyberark:webhook-test-port-race
Sep 1, 2026
Merged

cert-manager-prow[bot] merged 3 commits into
cert-manager:masterfrom
wallrj-cyberark:webhook-test-port-race

Conversation

@wallrj-cyberark

Copy link
Copy Markdown
Member

Pull Request Motivation

The integration tests are flaky, and when they fail they blame the wrong thing.

The test webhook server picks its port by binding to port 0, reading back the port it was allocated, closing that listener and then binding again to the same number — freePort in pkg/webhook/server/server.go. Anything on the machine can claim the port in the gap. go test ./... runs the integration test packages concurrently and each one starts its own webhook server, so they race each other for it.

Losing that race was fatal rather than merely unlucky. Server.Port reports the port number as soon as it has been chosen, which is before the listener has been created. StartWebhookServer polled Port, saw a number, and handed the caller a URL for a server that had already exited. Every request to it was then refused, so the failure surfaced in some unrelated test as a confusing assertion mismatch:

certificaterequest_test.go:194: unexpected error suffix,
  exp=encoded CSR error: the ExtKeyUsages [ 'client auth' ] do not match the expected ExtKeyUsages []
  got=Internal error occurred: failed calling webhook "webhook.cert-manager.io":
      failed to call webhook: Post "https://127.0.0.1:46009/mutate?timeout=10s":
      dial tcp 127.0.0.1:46009: connect: connection refused
testwebhook.go:139: error running webhook server: listen tcp :46009: bind: address already in use

The real cause is on the last line, and it is easy to miss underneath a failing assertion about key usages.

What this changes

Three things in test/webhook, plus two comment corrections:

  1. Wait for the port to actually accept a connection before returning it, instead of trusting Port(). The probe verifies the peer against the CA generated for the server, so another process holding the port cannot be mistaken for ours. This is what DefaultServer.StartedChecker does; it is not reachable here because Server.Run does not keep the manager it builds.
  2. Watch the error channel while polling, so a server that stops is reported straight away rather than after a timeout.
  3. Retry startup on EADDRINUSE (5 attempts). A fresh attempt is allocated a different port.

The error from Run is now wrapped with %w so errors.Is(err, syscall.EADDRINUSE) works. The poll interval drops from 100ms to 10ms, which is where most of the speed-up below comes from. The redundant os.RemoveAll(tempDir) goes, since t.TempDir() already cleans up.

The doc comment on Port said it "returns the port number that the webhook listener is listening on", which is not true and is the trap that made this easy to write. It and freePort now say what they actually do. No behaviour changes outside tests — freePort is only reachable with --secure-port=0.

Why not fix the race itself?

Binding port 0 and asking the server which port it got would remove the race rather than tolerate it, but controller-runtime permits neither half of it. webhook.Options.Port = 0 does not mean "any port" — setDefaults rewrites it to DefaultPort. And DefaultServer.Start creates its listener as a local variable and never exposes it: no Addr(), no Port(), and no Listener field on Options to pass a pre-bound listener in. Implementing the webhook.Server interface ourselves would mean duplicating Start, which imports pkg/internal/httpserver and pkg/webhook/internal/metrics; dropping the latter would silently remove the controller_runtime_webhook_* metrics from the shipped webhook.

SO_REUSEADDR does not help either. Go already sets it on every listener, and for TCP it only waives TIME_WAIT conflicts — it has never permitted two live listeners on one port. SO_REUSEPORT does, and would be worse: both servers would bind and the kernel would split connections between them.

For contrast, the healthz listener a few lines further down in the same file does it correctly — lc.Listen(ctx, "tcp", ":0"), keeping the listener it was given. Only the webhook port has this problem.

Testing

TestStartWebhookServerRetriesWhenItsPortIsTaken reproduces the failure deterministically: it holds a port open, forces the first attempt onto it, and asserts that the helper retries and returns a server that is genuinely reachable over TLS with the expected CA. It needs no apiserver, so it runs in the normal unit test job.

To confirm the test actually catches the bug rather than passing vacuously, I set startAttempts = 1 and re-ran it:

testwebhook_test.go:39: failed to start webhook server: error running webhook server: listen tcp :40039: bind: address already in use
FAIL	github.com/cert-manager/cert-manager/test/webhook	0.273s

With the retry restored it passes, and the log shows both attempts:

testwebhook_test.go:39: webhook server lost the race for its port, retrying (attempt 1 of 5): error running webhook server: listen tcp :41933: bind: address already in use
"Serving webhook server" host="" port=39719
--- PASS: TestStartWebhookServerRetriesWhenItsPortIsTaken (0.23s)

The full integration suite passes:

ok  	integration-tests/acme	                14.605s
ok  	integration-tests/certificaterequests	17.665s
ok  	integration-tests/certificates	        117.555s
ok  	integration-tests/fuzz/acme	            0.175s
ok  	integration-tests/fuzz/cert-manager	    0.264s
ok  	integration-tests/issuers	            18.617s
ok  	integration-tests/rfc2136_dns01	        31.983s
ok  	integration-tests/validation	        69.915s
ok  	integration-tests/webhook	            36.183s

golangci-lint run over the whole repo reports 0 issues.

I could not find an existing issue for this, so there is nothing to link.

Kind

/kind flake

Release Note

NONE

The test webhook server picks its port by binding to port 0, reading back
the port it was allocated, closing that listener and then binding again to
the same number. Anything on the machine can claim the port in the gap.
`go test ./...` runs the integration test packages concurrently and each
one starts its own webhook server, so they race each other for it.

Losing that race was fatal rather than merely unlucky, because Server.Port
reports the port number as soon as it has been chosen, which is before the
listener has been created. StartWebhookServer polled Port, saw a number and
handed the caller a URL for a server that had already exited. Every request
to it was then refused, and the failure surfaced as a confusing assertion
mismatch in an unrelated test rather than as the bind error.

Wait for the port to accept a TLS connection before returning it, verifying
the peer against the CA generated for the server so that another process
holding the port cannot be mistaken for ours; watch the error channel while
polling so a server that stops is reported immediately; and retry the whole
startup on EADDRINUSE, which allocates a different port.

The race cannot be closed in freePort itself: that needs controller-runtime
to accept a pre-bound listener, and webhook.Options has no such field.

Signed-off-by: Richard Wall <[email protected]>
@cert-manager-prow cert-manager-prow Bot added release-note-none Denotes a PR that doesn't merit a release note. kind/flake Categorizes issue or PR as related to a flaky test. dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. area/testing Issues relating to testing size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Aug 28, 2026

@wallrj-cyberark wallrj-cyberark left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Flagging the choices a reviewer is most likely to want justified.

} else {
// The caller supplied its own TLS files, so there is no CA to check
// against and reaching the port has to be good enough.
tlsConfig.InsecureSkipVerify = true

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

InsecureSkipVerify here is deliberate but narrow, so worth calling out.

It is only reached when the caller passed --tls-cert-file/--tls-private-key-file themselves, in which case CAPEM is empty and there is no CA available to check against. The connection is thrown away immediately; it exists only to answer "is this port accepting connections yet".

In the normal path — the one every current caller takes — caPEM is set and the probe pins to it. That pinning is load-bearing rather than cosmetic: without it, a different webhook server that won the race for this port would satisfy the readiness check, and we would hand the caller its URL.

Happy to make the no-CA case fall back to a plain TCP dial instead if reviewers would rather not see the flag at all.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

load-bearing

Claude loves this expression.

[human]

// then refused. The deadline covers the TLS handshake as well as the
// connection, so that a listener which never replies cannot wedge the
// poll; a loopback handshake takes single-digit milliseconds.
dialCtx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The deadline covers the handshake, not just the connect, and that matters.

An earlier version of this used tls.Dial with no deadline. A listener that accepts the TCP connection but never speaks TLS — which is exactly what a squatting process looks like — leaves the handshake blocked forever, and the poll loop wedges until the whole test binary times out. Using DialContext with a deadline bounds both phases.

250ms is generous for loopback, where a handshake is single-digit milliseconds.

conn, err := dialer.DialContext(dialCtx, "tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)))
cancel()
if err != nil {
return false, nil //nolint:nilerr // not listening yet, keep polling

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Swallowing the dial error is intentional: at this point the server has chosen a port but may not have finished binding, so a refused connection is the expected state and we keep polling. A genuine startup failure is not lost — it arrives on errCh and is picked up by the select at the top of this poll function.

}

// Port returns the port number that the webhook listener is listening on
// Port returns the port number the webhook listener has been assigned. It

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is a comment-only change, but it is the part I would most like a second opinion on.

The previous wording — "returns the port number that the webhook listener is listening on" — is not true, and believing it is what produced the bug this PR fixes. Callers reasonably read it as a readiness signal when it is only "a number has been picked".

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR reduces flakiness in cert-manager’s integration tests by making the test webhook server startup robust against the known port selection race (port chosen via bind-to-:0 then re-bind), and by ensuring the helper only returns once the server is actually accepting TLS connections.

Changes:

  • Add retry-on-EADDRINUSE behavior to StartWebhookServer and surface server startup failures promptly by monitoring the Run error channel while polling.
  • Replace “port chosen” readiness with a real “TLS connection succeeds” readiness probe (verifying against the generated CA when available).
  • Add a deterministic unit test that reproduces the port-race condition and asserts the helper retries and returns a reachable server; update misleading comments on freePort/Port.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
test/webhook/testwebhook.go Adds retry logic and a TLS-based readiness check that waits for the listener to truly accept connections (and fails fast if the server exits).
test/webhook/testwebhook_test.go New unit test that deterministically squats on a port to validate retry behavior and confirm the returned server is reachable over TLS with the expected CA.
pkg/webhook/server/server.go Clarifies freePort/Port doc comments to reflect the real behavior (port chosen vs actually listening).

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@wallrj-cyberark
wallrj-cyberark requested a review from wallrj August 30, 2026 05:32
Tolerate probe connection close errors, document the unverified
caller-supplied-TLS path, and fix a spelling nit.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
Comment thread test/webhook/testwebhook.go Resolved
Comment thread test/webhook/testwebhook.go Resolved
Comment thread pkg/webhook/server/server.go Resolved
Bound waitForListener at 30 seconds so a server that can never pass the
probe fails fast instead of hanging until the go test deadline. Publish
the chosen webhook port through an atomic instead of writing ListenAddr
from the Run goroutine, closing a data race with Port that go test -race
flags. Correct the freePort comment: --secure-port=0 passes validation
for any deployment, not just tests.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
@wallrj

wallrj commented Sep 1, 2026

Copy link
Copy Markdown
Member

/test pull-cert-manager-master-make-test

@maelvls

maelvls commented Sep 1, 2026

Copy link
Copy Markdown
Member

I've given a look with my human eyes, and it looks OK to me.

/lgtm
/approve

@cert-manager-prow cert-manager-prow Bot added the lgtm Indicates that a PR is ready to be merged. label Sep 1, 2026
@cert-manager-prow

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: maelvls

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@cert-manager-prow cert-manager-prow Bot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Sep 1, 2026
@cert-manager-prow
cert-manager-prow Bot merged commit e5fa012 into cert-manager:master Sep 1, 2026
6 checks passed
@wallrj-cyberark
wallrj-cyberark deleted the webhook-test-port-race branch September 1, 2026 15:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by an approver from all required OWNERS files. area/testing Issues relating to testing dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. kind/flake Categorizes issue or PR as related to a flaky test. lgtm Indicates that a PR is ready to be merged. release-note-none Denotes a PR that doesn't merit a release note. size/L Denotes a PR that changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants