Files
coder/coderd
Bobby Ho 5b82b04a78 fix(coderd): use a port outside the OS range in the TCP dial failure test (#32541)
## Summary

Fixes a flaky `TestServerTailnet_ReverseProxy_TCPDialFailure` (~2% CI failure rate) caused by a port race.

Previously, `testutil.RandomPort` selected a port by briefly opening and closing a listener. Another parallel test could claim that port before the connection attempt, causing an unexpected success instead of a connection refusal.

This PR introduces `closedPort`, which selects an unused port from **20000–29999**, outside the default ephemeral port ranges on Linux, macOS, and Windows. It checks both `127.0.0.1` and `::1`, since the agent may attempt either address.

Refs [CORE-756](https://linear.app/codercom/issue/CORE-756/flake-testservertailnet-reverseproxy-tcpdialfailure)

## Changes

- Add `closedPort` in `coderd/tailnet_test.go` and replace the `testutil.RandomPort` call.
- Skip ports already accepting connections on IPv4 or IPv6.
- Keep existing assertions unchanged. No production code changes.

**Limitation:** This mitigates rather than eliminates the race. Another process could explicitly bind the selected port after the check, although the OS will not assign it automatically as an ephemeral port.

## Testing

| Scenario | Result |
|---|---|
| Before fix: 9,600 parallel Linux runs | 1 failure |
| After fix: 9,600 parallel Linux runs | **0 failures** |
| Ports 20000 and 20001 occupied | Pass; selects 20002 |
| Remove expected dial log fields | Test fails as expected |
| macOS: 20 consecutive runs | Pass |
| `golangci-lint` | 0 issues |

Windows remains untested.

## Expected Behavior

The test continues to verify that a failed TCP dial returns HTTP 502 and logs `agent_id`, `dial_phase=tcp_dial`, and `tcp_dial_after`, while reducing failures caused by port collisions.
2026-11-23 09:08:10 -07:00
..