Skip to content

Fix port-selection TOCTOU race in e2e tests - #6142

Merged
jhrozek merged 1 commit into
mainfrom
worktree-toctou-port
Jul 29, 2026
Merged

Fix port-selection TOCTOU race in e2e tests#6142
jhrozek merged 1 commit into
mainfrom
worktree-toctou-port

Conversation

@jhrozek

@jhrozek jhrozek commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Summary

networking.FindOrUsePort/FindAvailable pick a port by binding a probe listener, reading the port, and immediately closing it — the real bind happens later, so anything else on the machine can steal the number in between. Under sharded CI this is lost often enough to flake, observed on PR #6088 as OIDC mock server error: listen tcp :49278: bind: address already in use.

  • OIDCMockServer and LLMGatewayMock (test/e2e/oidc_mock.go, test/e2e/llm_gateway_mock.go) now open their own listener at construction time instead of accepting a pre-selected port, closing the race window entirely for the 6 e2e call sites that use them.
  • test/e2e/api_helpers.go gets a shared RetryOnPortConflict helper, applied to NewServer (thv serve) and to thv llm proxy start call sites in cli_llm_all_clients_test.go — both hard-fail on a real bind conflict, so a retry-once-with-a-fresh-port is correct and sufficient there. This generalizes the pattern already used for Docker workload port races in test/e2e/vmcp_dual_era_helpers_test.go.
  • thv proxy (test/e2e/proxy_oauth_test.go) needed a different fix: for a nonzero requested port it silently substitutes a different one on conflict with no error to retry on, and its real bind can trail port selection by a full OAuth exchange. Those tests now pass --port 0 and read the actual bound port back from the subprocess's own stdout instead of pre-selecting.

Production callers sharing the same root cause (Docker port bindings in pkg/container/docker, in-process OAuth/proxy binders in pkg/auth and cmd/thv/app/proxy.go) are deliberately out of scope here and tracked in #6141.

Type of change

  • Bug fix

Test plan

  • Linting (task lint-fix)
  • Manual testing (describe below)

Ran task build and task lint-fix clean throughout. Ran targeted, label-filtered ginkgo passes covering the touched specs (llm, oauth, infra labels) plus the ~14 other e2e files sharing the modified NewServer/RetryOnPortConflict helper (api label). Every failure surfaced traced to a cause unrelated to this diff: TOOLHIVE_SKIP_DESKTOP_CHECK not being set for a local ToolHive Desktop conflict, Docker workload-readiness timeouts under local resource contention, and a pre-existing macOS-only gap in a SSL_CERT_FILE trust mechanism one test class relies on — confirmed by reverting the two files involved to clean main and reproducing the identical failure there. No failure was attributable to the code in this diff.

Changes

File Change
test/e2e/oidc_mock.go NewOIDCMockServer opens its own listener at construction; adds Port()
test/e2e/llm_gateway_mock.go NewLLMGatewayMock opens its own listener at construction; adds Port()
test/e2e/api_helpers.go Adds RetryOnPortConflict; NewServer uses it
test/e2e/cli_llm_all_clients_test.go Drops pre-selection at the mock-server call sites; wraps thv llm proxy start sites in RetryOnPortConflict via a new startLLMProxy helper
test/e2e/cli_llm_setup_test.go Drops pre-selection at the mock-server call site
test/e2e/proxy_oauth_test.go Passes --port 0 and discovers the real bound port from subprocess output (discoverProxyPort, startProxyAndDiscoverPort); thread-safe output capture via a new syncBuffer
test/e2e/vmcp_infra_features_test.go Drops pre-selection at the mock-server call site

Does this introduce a user-facing change?

No.

Special notes for reviewers

  • Follow-up production-side hardening tracked in Production port-selection TOCTOU: FindOrUsePort bind-close-rebind race across 7 call sites #6141 — same root cause, different fix shapes (some sites can hold a listener the way the mocks now do; the Docker-handoff sites can only be narrowed via retry-at-container-create-time).
  • startLLMProxy's TCP-dial readiness check double-checks the subprocess's own exit signal before trusting a successful dial, to avoid a false positive if the dial happens to reach a different process that won the same port-bind race.

Generated with Claude Code

networking.FindOrUsePort probes a port by binding then immediately
releasing it, so anything else on the machine can steal the number
before the real bind happens later. Under sharded CI this is lost
often enough to flake (observed on PR #6088 as
"OIDC mock server error: listen tcp :49278: bind: address already in use").

Two fixes depending on where the real bind happens:

- In-process mock servers (OIDCMockServer, LLMGatewayMock) now open
  their own listener at construction time instead of accepting a
  pre-selected port, closing the window entirely.
- Subprocess-launched proxies (thv serve, thv llm proxy start) get a
  shared RetryOnPortConflict helper that retries once on a detected
  bind conflict, generalizing the pattern already used for Docker
  workload port races in the vMCP dual-era test helpers. thv proxy
  needed a different approach: it silently substitutes a different
  port on conflict for a nonzero request (no error to retry on) and
  its real bind can lag port selection by a full OAuth exchange, so
  those tests instead pass --port 0 and read the real bound port back
  from the subprocess's own stdout.

Production callers with the same root cause (Docker port bindings,
in-process OAuth/proxy binders) are tracked separately in #6141.

Generated with Claude Code (https://claude.com/claude-code)
@github-actions github-actions Bot added the size/L Large PR: 600-999 lines changed label Jul 29, 2026
@codecov

codecov Bot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 72.51%. Comparing base (f805322) to head (04399b2).
⚠️ Report is 23 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6142      +/-   ##
==========================================
+ Coverage   72.34%   72.51%   +0.17%     
==========================================
  Files         731      734       +3     
  Lines       75748    75939     +191     
==========================================
+ Hits        54799    55070     +271     
+ Misses      17047    16974      -73     
+ Partials     3902     3895       -7     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@jhrozek
jhrozek merged commit 3d44435 into main Jul 29, 2026
78 of 79 checks passed
@jhrozek
jhrozek deleted the worktree-toctou-port branch July 29, 2026 13:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Large PR: 600-999 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants