Skip to content

fix(router): only trust router's bound ports when it is actually running, fixes #8293 - #8648

Closed
rfay wants to merge 1 commit into
ddev:mainfrom
rfay:20260801_rfay_fix_router_port_race
Closed

rfay wants to merge 1 commit into
ddev:mainfrom
rfay:20260801_rfay_fix_router_port_race

Conversation

@rfay

@rfay rfay commented Aug 1, 2026

Copy link
Copy Markdown
Member

The Issue

#8638 added a retry loop to TestUseEphemeralPort for the case where the db/web container's host port (drawn fresh from the kernel by Docker on every docker-compose up, since it's published with no fixed host port) loses a bind race. That retry helps there because each attempt draws a different port.

CI kept failing anyway, on a different race, in a way the retry loop cannot help with: this run

router_test.go:304:
    Error: Received unexpected error:
    failed to start ddev-router: Error response from daemon: failed to
    set up container networking: driver failed programming external
    connectivity on endpoint ddev-router: failed to bind host port for
    127.0.0.1:33004:172.18.0.7:33004/tcp: address already in use

With DDEV_DEBUG on, the log shows what happened:

  1. DDEV's own router-port allocator (GetAvailableRouterPort in pkg/ddevapp/router.go) checks port 33004, finds it free, and assigns it.
  2. Roughly 10s later, the actual docker-compose up for ddev-router fails to bind 33004: something else grabbed it in that window. This part is a genuine, unavoidable TOCTOU race, just like the one test(router): make TestUseEphemeralPort resilient to host port races, fixes #8293 (#8638) [skip ci] #8638 fixed for the db/web port, except here it's on DDEV's own dynamically-chosen router port.
  3. Every retry after that logs proposedPort 33004 already bound on ddev-router, accepting it and hands back the exact same port. The retry loop never actually tries a different port, so it fails identically three times in a row.

The reason for (3): GetBoundHostPorts() reads a container's configured HostConfig.PortBindings (the port it asked Docker to bind), not what it actually succeeded in binding. FindDdevRouter() looks up containers with ContainerList(All: true), so it finds the leftover ddev-router container from the failed attempt even though it's not running. GetAvailableRouterPort and AllocateAvailablePortForRouter treat that stale HostConfig entry as proof the router legitimately owns the port, and keep re-offering it forever.

StartDdevRouter() already has the right instinct for this (router.State != "running" triggers removal and recreation), but that check only runs later in app.Start(), after the port has already been poisoned.

How This PR Solves The Issue

GetAvailableRouterPort() and AllocateAvailablePortForRouter() now only trust the router's existing port bindings when the router container's state is "running". A container that merely attempted (and failed) to bind a port no longer poisons subsequent allocations with the same broken port.

This preserves the existing "trust the router regardless of health status" behavior for a router that's running but unhealthy (e.g. broken Traefik config) — only containers that aren't running at all are now excluded.

No test changes; #8638 already fixed the retry loop and port assertions, and this closes the remaining gap the retries couldn't cover.

Manual Testing Instructions

DDEV_NO_INSTRUMENTATION=true go test -v -timeout 15m \
  -run 'TestGlobalPortOverride|TestProjectPortOverride|TestRouterConfigOverride|TestAllocateAvailablePortForRouter|TestUseEphemeralPort' \
  ./pkg/ddevapp/

To exercise the fix directly: start a project so ddev-router binds an ephemeral port, then kill the router container without going through ddev stop so it's left in an exited state while still holding that port in its config, then start another project needing an ephemeral port and confirm it picks a fresh one instead of reusing the dead container's port.

Automated Testing Overview

Ran the full router_test.go suite locally: TestGlobalPortOverride, TestProjectPortOverride, TestRouterConfigOverride, TestAllocateAvailablePortForRouter, and TestUseEphemeralPort all pass. make staticrequired reports 0 issues.

Release/Deployment Notes

None. Internal port-allocation logic only; no user-visible or config changes.

…ing, fixes ddev#8293

## The Issue

- Fixes ddev#8293 (follow-up to ddev#8638, which did not fully resolve it)

ddev#8638 added a retry loop to `TestUseEphemeralPort` for the case where the
db/web container's host port (drawn fresh from the kernel by Docker on every
`docker-compose up`, since it's published with no fixed host port) loses a
bind race. That retry helps there because each attempt draws a different
port.

CI kept failing anyway, on a different race, in a way the retry loop cannot
help with: https://github.com/ddev/ddev/actions/runs/30709764475/job/91395069771

    router_test.go:304:
        Error: Received unexpected error:
        failed to start ddev-router: Error response from daemon: failed to
        set up container networking: driver failed programming external
        connectivity on endpoint ddev-router: failed to bind host port for
        127.0.0.1:33004:172.18.0.7:33004/tcp: address already in use

With `DDEV_DEBUG` on, the log shows what happened:

1. DDEV's own router-port allocator (`GetAvailableRouterPort` in
   `pkg/ddevapp/router.go`) checks port 33004, finds it free, and assigns it.
2. Roughly 10s later, the actual `docker-compose up` for `ddev-router` fails
   to bind 33004: something else grabbed it in that window. This part is a
   genuine, unavoidable TOCTOU race, just like the one ddev#8638 fixed for the
   db/web port, except here it's on DDEV's own dynamically-chosen router
   port.
3. Every retry after that logs `proposedPort 33004 already bound on
   ddev-router, accepting it` and hands back the exact same port. The retry
   loop never actually tries a different port, so it fails identically three
   times in a row.

The reason for (3): `GetBoundHostPorts()` reads a container's *configured*
`HostConfig.PortBindings` (the port it asked Docker to bind), not what it
actually succeeded in binding. `FindDdevRouter()` looks up containers with
`ContainerList(All: true)`, so it finds the leftover `ddev-router` container
from the failed attempt even though it's not running. `GetAvailableRouterPort`
and `AllocateAvailablePortForRouter` treat that stale HostConfig entry as
proof the router legitimately owns the port, and keep re-offering it forever.

`StartDdevRouter()` already has the right instinct for this
(`router.State != "running"` triggers removal and recreation), but that
check only runs later in `app.Start()`, after the port has already been
poisoned.

## How This PR Solves The Issue

`GetAvailableRouterPort()` and `AllocateAvailablePortForRouter()` now only
trust the router's existing port bindings when the router container's state
is `"running"`. A container that merely attempted (and failed) to bind a
port no longer poisons subsequent allocations with the same broken port.

This preserves the existing "trust the router regardless of health status"
behavior for a router that's running but unhealthy (e.g. broken Traefik
config) — only containers that aren't running at all are now excluded.

No test changes; ddev#8638 already fixed the retry loop and port assertions, and
this closes the remaining gap the retries couldn't cover.

## Manual Testing Instructions

```bash
DDEV_NO_INSTRUMENTATION=true go test -v -timeout 15m \
  -run 'TestGlobalPortOverride|TestProjectPortOverride|TestRouterConfigOverride|TestAllocateAvailablePortForRouter|TestUseEphemeralPort' \
  ./pkg/ddevapp/
```

To exercise the fix directly: start a project so `ddev-router` binds an
ephemeral port, then kill the router container without going through
`ddev stop` so it's left in an `exited` state while still holding that port
in its config, then start another project needing an ephemeral port and
confirm it picks a fresh one instead of reusing the dead container's port.

## Automated Testing Overview

Ran the full `router_test.go` suite locally: `TestGlobalPortOverride`,
`TestProjectPortOverride`, `TestRouterConfigOverride`,
`TestAllocateAvailablePortForRouter`, and `TestUseEphemeralPort` all pass.
`make staticrequired` reports 0 issues.

## Release/Deployment Notes

None. Internal port-allocation logic only; no user-visible or config
changes.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@github-actions github-actions Bot added the bugfix label Aug 1, 2026
@github-actions

github-actions Bot commented Aug 1, 2026

Copy link
Copy Markdown

@rfay

rfay commented Aug 2, 2026

Copy link
Copy Markdown
Member Author

Closing as superseded — #8653 includes this exact fix (the router.State == "running" guard in AllocateAvailablePortForRouter() and GetAvailableRouterPort()) as part of a broader router-port-substitution change for #8644. The new substitution-reuse logic in #8653 sits on the same FindDdevRouter() result this PR guards, so it needed the identical protection anyway.

@rfay rfay closed this Aug 2, 2026
rfay added a commit to rfay/ddev that referenced this pull request Aug 8, 2026
## The Issue

Related to ddev#8648 (open, targets `main` directly, not yet merged), which
fixes ddev#8293: a `ddev-router` container that exists but isn't running - for
example one that lost a TOCTOU port-bind race, or crashed - still reports
the port it *tried* to bind in its `HostConfig.PortBindings`. The prior code
in `AllocateAvailablePortForRouter()` and `GetAvailableRouterPort()` treated
any container found by `FindDdevRouter()` as a trustworthy source of bound
ports regardless of its state, so a dead container's stale, never-actually-
bound port kept getting reoffered on every subsequent call.

This branch's earlier commits added a second, related trust decision on top
of the same `FindDdevRouter()` result: `GetAvailableRouterPort()` now also
checks the router's `RouterPortSubstitutionsLabel` (via
`knownRouterPortSubstitutions()`) to decide whether a proposed port that
looks free should still be treated as substituted. That check inherits the
identical vulnerability - a non-running router's label and stale
`HostConfig` entries could combine to convince a new project to reuse a
port that was never actually bound.

## How This PR Solves The Issue

Adopt the same fix ddev#8648 applies upstream: both `AllocateAvailablePortForRouter()`
and `GetAvailableRouterPort()` now only trust `FindDdevRouter()`'s bound-ports
result when `router.State == "running"`. This protects the pre-existing
"already bound" check and, as a side effect requiring no additional code,
also protects the new substitution-reuse check: `routerPortsAlreadyBound`
stays empty whenever the router isn't running, so the
`nodeps.ArrayContainsString(routerPortsAlreadyBound, ephemeralPort)` guard on
the substitution-reuse path correctly declines to trust a stale label from a
dead container, falling through to fresh negotiation instead.

`generateRouterCompose()`'s own use of `knownRouterPortSubstitutions()` (to
carry a substitution forward into a recreated router) is deliberately left
unguarded by container state: it only runs during an actual recreation, and
its existing pruning against the active projects' real configured ports -
themselves only ever set through the now-guarded decision points - is the
correct safety net there, not the old router's liveness.

## Manual Testing Instructions

Same recipe as ddev#8648: start a project so `ddev-router` binds an ephemeral
port, kill the router container directly (not via `ddev stop`) so it's left
`exited` while still holding that port in its config, then start another
project needing an ephemeral port and confirm it picks a fresh one instead
of reusing the dead container's port.

## Automated Testing Overview

Re-ran `TestGlobalPortOverride`, `TestProjectPortOverride`,
`TestRouterConfigOverride`, `TestAllocateAvailablePortForRouter`,
`TestUseEphemeralPort`, and this branch's
`TestRouterPortSubstitutionPersistsAcrossProjects` - all pass with the guard
in place. `make staticrequired` reports 0 issues.

## Release/Deployment Notes

None. Internal port-allocation logic only.

Co-Authored-By: Claude Fable 5 <[email protected]>
rfay added a commit to rfay/ddev that referenced this pull request Aug 11, 2026
## The Issue

Related to ddev#8648 (open, targets `main` directly, not yet merged), which
fixes ddev#8293: a `ddev-router` container that exists but isn't running - for
example one that lost a TOCTOU port-bind race, or crashed - still reports
the port it *tried* to bind in its `HostConfig.PortBindings`. The prior code
in `AllocateAvailablePortForRouter()` and `GetAvailableRouterPort()` treated
any container found by `FindDdevRouter()` as a trustworthy source of bound
ports regardless of its state, so a dead container's stale, never-actually-
bound port kept getting reoffered on every subsequent call.

This branch's earlier commits added a second, related trust decision on top
of the same `FindDdevRouter()` result: `GetAvailableRouterPort()` now also
checks the router's `RouterPortSubstitutionsLabel` (via
`knownRouterPortSubstitutions()`) to decide whether a proposed port that
looks free should still be treated as substituted. That check inherits the
identical vulnerability - a non-running router's label and stale
`HostConfig` entries could combine to convince a new project to reuse a
port that was never actually bound.

## How This PR Solves The Issue

Adopt the same fix ddev#8648 applies upstream: both `AllocateAvailablePortForRouter()`
and `GetAvailableRouterPort()` now only trust `FindDdevRouter()`'s bound-ports
result when `router.State == "running"`. This protects the pre-existing
"already bound" check and, as a side effect requiring no additional code,
also protects the new substitution-reuse check: `routerPortsAlreadyBound`
stays empty whenever the router isn't running, so the
`nodeps.ArrayContainsString(routerPortsAlreadyBound, ephemeralPort)` guard on
the substitution-reuse path correctly declines to trust a stale label from a
dead container, falling through to fresh negotiation instead.

`generateRouterCompose()`'s own use of `knownRouterPortSubstitutions()` (to
carry a substitution forward into a recreated router) is deliberately left
unguarded by container state: it only runs during an actual recreation, and
its existing pruning against the active projects' real configured ports -
themselves only ever set through the now-guarded decision points - is the
correct safety net there, not the old router's liveness.

## Manual Testing Instructions

Same recipe as ddev#8648: start a project so `ddev-router` binds an ephemeral
port, kill the router container directly (not via `ddev stop`) so it's left
`exited` while still holding that port in its config, then start another
project needing an ephemeral port and confirm it picks a fresh one instead
of reusing the dead container's port.

## Automated Testing Overview

Re-ran `TestGlobalPortOverride`, `TestProjectPortOverride`,
`TestRouterConfigOverride`, `TestAllocateAvailablePortForRouter`,
`TestUseEphemeralPort`, and this branch's
`TestRouterPortSubstitutionPersistsAcrossProjects` - all pass with the guard
in place. `make staticrequired` reports 0 issues.

## Release/Deployment Notes

None. Internal port-allocation logic only.

Co-Authored-By: Claude Fable 5 <[email protected]>
rfay added a commit to rfay/ddev that referenced this pull request Aug 13, 2026
## The Issue

Related to ddev#8648 (open, targets `main` directly, not yet merged), which
fixes ddev#8293: a `ddev-router` container that exists but isn't running - for
example one that lost a TOCTOU port-bind race, or crashed - still reports
the port it *tried* to bind in its `HostConfig.PortBindings`. The prior code
in `AllocateAvailablePortForRouter()` and `GetAvailableRouterPort()` treated
any container found by `FindDdevRouter()` as a trustworthy source of bound
ports regardless of its state, so a dead container's stale, never-actually-
bound port kept getting reoffered on every subsequent call.

This branch's earlier commits added a second, related trust decision on top
of the same `FindDdevRouter()` result: `GetAvailableRouterPort()` now also
checks the router's `RouterPortSubstitutionsLabel` (via
`knownRouterPortSubstitutions()`) to decide whether a proposed port that
looks free should still be treated as substituted. That check inherits the
identical vulnerability - a non-running router's label and stale
`HostConfig` entries could combine to convince a new project to reuse a
port that was never actually bound.

## How This PR Solves The Issue

Adopt the same fix ddev#8648 applies upstream: both `AllocateAvailablePortForRouter()`
and `GetAvailableRouterPort()` now only trust `FindDdevRouter()`'s bound-ports
result when `router.State == "running"`. This protects the pre-existing
"already bound" check and, as a side effect requiring no additional code,
also protects the new substitution-reuse check: `routerPortsAlreadyBound`
stays empty whenever the router isn't running, so the
`nodeps.ArrayContainsString(routerPortsAlreadyBound, ephemeralPort)` guard on
the substitution-reuse path correctly declines to trust a stale label from a
dead container, falling through to fresh negotiation instead.

`generateRouterCompose()`'s own use of `knownRouterPortSubstitutions()` (to
carry a substitution forward into a recreated router) is deliberately left
unguarded by container state: it only runs during an actual recreation, and
its existing pruning against the active projects' real configured ports -
themselves only ever set through the now-guarded decision points - is the
correct safety net there, not the old router's liveness.

## Manual Testing Instructions

Same recipe as ddev#8648: start a project so `ddev-router` binds an ephemeral
port, kill the router container directly (not via `ddev stop`) so it's left
`exited` while still holding that port in its config, then start another
project needing an ephemeral port and confirm it picks a fresh one instead
of reusing the dead container's port.

## Automated Testing Overview

Re-ran `TestGlobalPortOverride`, `TestProjectPortOverride`,
`TestRouterConfigOverride`, `TestAllocateAvailablePortForRouter`,
`TestUseEphemeralPort`, and this branch's
`TestRouterPortSubstitutionPersistsAcrossProjects` - all pass with the guard
in place. `make staticrequired` reports 0 issues.

## Release/Deployment Notes

None. Internal port-allocation logic only.

Co-Authored-By: Claude Fable 5 <[email protected]>
rfay added a commit to rfay/ddev that referenced this pull request Aug 13, 2026
## The Issue

Related to ddev#8648 (open, targets `main` directly, not yet merged), which
fixes ddev#8293: a `ddev-router` container that exists but isn't running - for
example one that lost a TOCTOU port-bind race, or crashed - still reports
the port it *tried* to bind in its `HostConfig.PortBindings`. The prior code
in `AllocateAvailablePortForRouter()` and `GetAvailableRouterPort()` treated
any container found by `FindDdevRouter()` as a trustworthy source of bound
ports regardless of its state, so a dead container's stale, never-actually-
bound port kept getting reoffered on every subsequent call.

This branch's earlier commits added a second, related trust decision on top
of the same `FindDdevRouter()` result: `GetAvailableRouterPort()` now also
checks the router's `RouterPortSubstitutionsLabel` (via
`knownRouterPortSubstitutions()`) to decide whether a proposed port that
looks free should still be treated as substituted. That check inherits the
identical vulnerability - a non-running router's label and stale
`HostConfig` entries could combine to convince a new project to reuse a
port that was never actually bound.

## How This PR Solves The Issue

Adopt the same fix ddev#8648 applies upstream: both `AllocateAvailablePortForRouter()`
and `GetAvailableRouterPort()` now only trust `FindDdevRouter()`'s bound-ports
result when `router.State == "running"`. This protects the pre-existing
"already bound" check and, as a side effect requiring no additional code,
also protects the new substitution-reuse check: `routerPortsAlreadyBound`
stays empty whenever the router isn't running, so the
`nodeps.ArrayContainsString(routerPortsAlreadyBound, ephemeralPort)` guard on
the substitution-reuse path correctly declines to trust a stale label from a
dead container, falling through to fresh negotiation instead.

`generateRouterCompose()`'s own use of `knownRouterPortSubstitutions()` (to
carry a substitution forward into a recreated router) is deliberately left
unguarded by container state: it only runs during an actual recreation, and
its existing pruning against the active projects' real configured ports -
themselves only ever set through the now-guarded decision points - is the
correct safety net there, not the old router's liveness.

## Manual Testing Instructions

Same recipe as ddev#8648: start a project so `ddev-router` binds an ephemeral
port, kill the router container directly (not via `ddev stop`) so it's left
`exited` while still holding that port in its config, then start another
project needing an ephemeral port and confirm it picks a fresh one instead
of reusing the dead container's port.

## Automated Testing Overview

Re-ran `TestGlobalPortOverride`, `TestProjectPortOverride`,
`TestRouterConfigOverride`, `TestAllocateAvailablePortForRouter`,
`TestUseEphemeralPort`, and this branch's
`TestRouterPortSubstitutionPersistsAcrossProjects` - all pass with the guard
in place. `make staticrequired` reports 0 issues.

## Release/Deployment Notes

None. Internal port-allocation logic only.

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add retry for "bind: address already in use" error in rootless

1 participant