Skip to content

tcp: allow a TCP tunnel upstream to half close the stream - #47378

Open
fl0Lec wants to merge 2 commits into
envoyproxy:mainfrom
DataDog:fl/tcp-tunnel-upstream-half-close
Open

fl0Lec wants to merge 2 commits into
envoyproxy:mainfrom
DataDog:fl/tcp-tunnel-upstream-half-close

Conversation

@fl0Lec

@fl0Lec fl0Lec commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Commit Message: tcp: allow a TCP tunnel upstream to half close the stream

Additional Description:

envoy.reloadable_features.allow_multiplexed_upstream_half_close lets an HTTP/2 or HTTP/3 upstream half close before the downstream. When it landed, TcpUpstream was given a force close so that TCP proxy behaviour stayed the same. That force close reads the same runtime guard:

force_reset_on_upstream_half_close_(Runtime::runtimeFeatureEnabled(
    "envoy.reloadable_features.allow_multiplexed_upstream_half_close")),
...
const bool force_reset =
    force_reset_on_upstream_half_close_ && end_stream && !downstream_complete_;

So the two behaviours cannot be separated: enabling independent half close for a TCP tunnel also enables the force close that cancels it out.

For a tunnel carrying a one way download, downstream_complete_ is never true — the client keeps its half of the tunnel open for the life of the stream, so it never sends end_stream. The upstream's half close therefore always becomes a full stream reset, and that reset discards whatever response data the downstream codec has not serialised yet. The client sees complete response headers, a truncated body, and a stream reset.

This gates the force close behind a separate guard, envoy.reloadable_features.tcp_tunnel_allow_upstream_half_close, on by default. Enabling independent half close is then sufficient on its own: the upstream half close propagates downstream as an end of stream, and the stream closes once the client half closes its own side. Turning the new guard off restores the force close.

allow_multiplexed_upstream_half_close deliberately remains in the condition, and is now commented, because it is a lifetime precondition rather than configuration: it is what guarantees the decodeData() call does not destroy the TcpUpstream object, which is what makes the access to upstream_request_ immediately afterwards safe. Replacing it with the new guard alone would make a use after free reachable purely by configuration.

I also verified that the tunnel stays usable in the remaining direction after the upstream half close: with an origin that half closes and then keeps reading, data the client sends on its still open half still arrives. That is why the upstream socket is intentionally not closed on FIN — closing it would release the file descriptor at the cost of silently dropping client to origin bytes.

Reproducing

client -> envoy -> origin, no TLS and no other proxies. The origin sends 16 MiB then half closes; the client CONNECTs, counts bytes, and reports any stream reset.

envoy.yaml
static_resources:
  listeners:
  - name: connect
    address: { socket_address: { address: 0.0.0.0, port_value: 8080 } }
    filter_chains:
    - filters:
      - name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          stat_prefix: connect
          codec_type: HTTP2
          http2_protocol_options: { allow_connect: true }
          route_config:
            name: local
            virtual_hosts:
            - name: all
              domains: ["*"]
              routes:
              - match: { connect_matcher: {} }
                route:
                  cluster: origin
                  upgrade_configs:
                  - upgrade_type: CONNECT
                    connect_config: {}
          http_filters:
          - name: envoy.filters.http.router
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
  clusters:
  - name: origin
    connect_timeout: 5s
    type: STRICT_DNS
    load_assignment:
      cluster_name: origin
      endpoints:
      - lb_endpoints:
        - endpoint: { address: { socket_address: { address: origin, port_value: 9000 } } }
layered_runtime:
  layers:
  - name: static
    static_layer:
      envoy.reloadable_features.allow_multiplexed_upstream_half_close: true
origin.py — sends 16 MiB, then half closes
import socket
PAYLOAD = 16 * 1024 * 1024
with socket.create_server(("0.0.0.0", 9000), reuse_port=True) as server:
  print(f"origin: serving {PAYLOAD} bytes", flush=True)
  connection, _ = server.accept()
  with connection:
    connection.sendall(b"x" * PAYLOAD)
    connection.shutdown(socket.SHUT_WR)
    print("origin: sent everything, half-closed", flush=True)
client.py — HTTP/2 CONNECT, counts bytes and any reset
import socket, sys, time
import h2.config, h2.connection, h2.events, h2.settings
EXPECTED = 16 * 1024 * 1024
for _ in range(30):
  try:
    sock = socket.create_connection(("envoy", 8080), timeout=5)
    sock.settimeout(30)
    break
  except OSError: time.sleep(0.5)
c = h2.connection.H2Connection(config=h2.config.H2Configuration(
    client_side=True, header_encoding="utf-8", validate_outbound_headers=False))
c.initiate_connection()
c.update_settings({h2.settings.SettingCodes.INITIAL_WINDOW_SIZE: EXPECTED + 65535})
c.send_headers(1, [(":method", "CONNECT"), (":authority", "origin:9000")], end_stream=False)
sock.sendall(c.data_to_send())
received, status, reset, done = 0, None, None, False
deadline = time.monotonic() + 60
while time.monotonic() < deadline and not done:
  payload = sock.recv(1 << 20)
  if not payload: break
  for ev in c.receive_data(payload):
    if isinstance(ev, h2.events.ResponseReceived): status = dict(ev.headers).get(":status")
    elif isinstance(ev, h2.events.DataReceived):
      received += len(ev.data)
      c.acknowledge_received_data(ev.flow_controlled_length, ev.stream_id)
    elif isinstance(ev, h2.events.StreamReset): reset = ev.error_code; done = True
    elif isinstance(ev, h2.events.StreamEnded): done = True
  out = c.data_to_send()
  if out: sock.sendall(out)
print(f"status={status} received={received} expected={EXPECTED} reset={reset}", flush=True)
sys.exit(0 if (status == "200" and received == EXPECTED and reset is None) else 1)
docker-compose.yaml
services:
  origin:
    image: python:3.12-alpine
    command: ["python", "/work/origin.py"]
    volumes: [./origin.py:/work/origin.py:ro]
  envoy:
    image: ${ENVOY_IMAGE:-envoyproxy/envoy-dev:latest}
    command: ["envoy", "-c", "/etc/envoy/envoy.yaml"]
    volumes: [./envoy.yaml:/etc/envoy/envoy.yaml:ro]
  client:
    image: python:3.12-alpine
    depends_on: [origin, envoy]
    command: >-
      sh -c "pip install --no-cache-dir --quiet h2==4.2.0 && python /work/client.py"
    volumes: [./client.py:/work/client.py:ro]
docker compose up --abort-on-container-exit --exit-code-from client
# Envoy allow_multiplexed_upstream_half_close received / expected reset
1 envoyproxy/envoy:v1.39-latest off (default) 243,854 / 16,777,216 INTERNAL_ERROR
2 envoyproxy/envoy:v1.39-latest on 245,757 / 16,777,216 CONNECT_ERROR
3 this branch on 16,777,216 / 16,777,216 none

Rows 1 and 2 are the same data loss reached by two different paths. With the guard off, the connection manager resets the stream in doEndStream(), because a CONNECT tunnel never observes the last downstream byte. With the guard on, the connection manager correctly defers to checkAndCloseStreamIfFullyClosed() and does not reset, but TcpUpstream force closes instead and the payload is lost anyway. Enabling the guard today therefore only changes which component resets the stream, not the outcome — which is why the two behaviours have to be separable.

Row 1 is a separate defect in the connection manager and is out of scope here; this PR turns row 2 into row 3.

Reproduced identically on envoyproxy/envoy-dev:latest (262,141 / 16,777,216, CONNECT_ERROR), so this is not specific to the stable branch.

One disclosure on row 3: it is a build of this change on a 1.39 based tree. The code in upstream_request.cc is byte identical on main and the patch applies cleanly, but I have not yet been able to run a full upstream main build locally.

Risk Level: Medium — changes stream teardown for TCP tunnels, but only when allow_multiplexed_upstream_half_close is enabled, which is off by default. A deployment already running that guard with TCP tunnelling loses the force close unless it sets the new guard to false.

Testing: New integration test ConnectTerminationIntegrationTest.UpstreamHalfCloseWithoutForceReset. UpstreamCloseWithHalfCloseEnabled now requests the force close explicitly, since its waitForAnyTermination() would otherwise accept the new clean end of stream and quietly stop covering the reset it is named for.

Docs Changes: N/A

Release Notes: Added under changelogs/current/behavior_changes/, since a deployment already running allow_multiplexed_upstream_half_close with TCP tunnelling no longer gets the force close unless it sets the new guard to false.

Platform Specific Features: N/A

Runtime guard: envoy.reloadable_features.tcp_tunnel_allow_upstream_half_close

@repokitteh-read-only

Copy link
Copy Markdown

As a reminder, PRs marked as draft will not be automatically assigned reviewers,
or be handled by maintainer-oncall triage.

Please mark your PR as ready when you want it to be reviewed!

🐱

Caused by: #47378 was opened by fl0Lec.

see: more, trace.

@fl0Lec
fl0Lec force-pushed the fl/tcp-tunnel-upstream-half-close branch from 5858d3a to 06df48e Compare September 11, 2026 13:19
@fl0Lec

fl0Lec commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

/retest

allow_multiplexed_upstream_half_close lets an HTTP/2 or HTTP/3 upstream half
close before the downstream. When it was introduced TcpUpstream was given a
force close so that TCP proxy teardown stayed the same, and that force close
reads the same runtime guard. The two behaviours are therefore inseparable:
enabling independent half close for a TCP tunnel also enables the force close
that cancels it out.

For a tunnel carrying a one way download downstream_complete_ is never true,
because the client keeps its half of the tunnel open for the life of the stream
and so never sends end_stream. The upstream's half close therefore always
becomes a full stream reset, and that reset discards whatever response data the
downstream codec has not serialised yet. The client sees a complete set of
response headers, a truncated body, and a stream reset.

The force close is now selected by
envoy.reloadable_features.tcp_tunnel_allow_upstream_half_close, on by default,
so enabling independent half close is sufficient on its own: the half close is
propagated downstream as an end of stream, the upstream connection is left open
so the downstream to upstream direction keeps working, and it is closed when the
stream is torn down. Setting the new guard to false restores the force close.

allow_multiplexed_upstream_half_close remains the first term of
force_reset_on_upstream_half_close_ because it is a lifetime precondition rather
than configuration: with it disabled the decodeData() call closes the stream and
destroys the TcpUpstream object, so it is what keeps the dereference of
upstream_request_ after that call unreachable. Adding a second term can only
narrow the set of configurations that reach the dereference, never widen it.

The onUpstreamData comment is rewritten around those two configurations. It also
drops the note claiming Envoy cannot distinguish a half closed TCP peer from a
fully closed one: TcpUpstream enables half close semantics on this connection,
and ConnectionImpl::onReadReady only turns a read EOF into a connection close
when half close is disabled, so a FIN arrives as end_stream with the connection
still open while a full close raises onEvent(). What a FIN does not indicate is
whether the peer is still reading, which only surfaces when a later write fails.

Signed-off-by: Florent Lecoultre <[email protected]>
@fl0Lec
fl0Lec force-pushed the fl/tcp-tunnel-upstream-half-close branch from 06df48e to 2bb6f32 Compare September 14, 2026 09:37
@fl0Lec
fl0Lec marked this pull request as ready for review September 14, 2026 13:08
@repokitteh-read-only

Copy link
Copy Markdown

CC @envoyproxy/runtime-guard-changes: FYI only for changes made to (source/common/runtime/runtime_features.cc).

🐱

Caused by: #47378 was ready_for_review by fl0Lec.

see: more, trace.

@fl0Lec

fl0Lec commented Sep 18, 2026

Copy link
Copy Markdown
Contributor Author

cc:@yanavlasov as you originally made #34461

Conflict in runtime_features.cc: main removed the
tcp_proxy_odcds_over_ads_fix guard in f307a7d while this branch added
tcp_tunnel_allow_upstream_half_close immediately after it. Took main's removal
and kept only the new guard, which stays in alphabetical position between
tap_honor_tap_enabled and test_feature_true.

Signed-off-by: Florent Lecoultre <[email protected]>
@ggreenway ggreenway assigned yanavlasov and unassigned ggreenway Sep 28, 2026
@ggreenway

Copy link
Copy Markdown
Member

Reassigning to @yanavlasov because he touched this code last. Also, should the previous runtime flag be removed now (was added 2 years ago) for clarity?

@fl0Lec

fl0Lec commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

I am fine with removing the previous runtime flag. But it should probably be done in another PR.
I am fine to create that PR and stack that one on top of it if it works for you @yanavlasov

@fl0Lec

This comment was marked as off-topic.

@nezdolik

nezdolik commented Oct 9, 2026

Copy link
Copy Markdown
Member

ping for review @yanavlasov

@KBaichoo

Copy link
Copy Markdown
Contributor

PTAL when you have a chance @yanavlasov

@botengyao

Copy link
Copy Markdown
Member

gentle ping @yanavlasov for a review, thanks!

@wdauchy

wdauchy commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

gentle ping @yanavlasov for a review, thanks!

from a discussion with Yan, I think we should instead target #48648

yanavlasov pushed a commit that referenced this pull request Oct 30, 2026
… for TCP upstreams (#48648)

Remove the
`envoy.reloadable_features.allow_multiplexed_upstream_half_close`
runtime guard. HTTP upstreams no longer half close before the
downstream, so the compensating resets in the HTTP/1 codec and in
`TcpUpstream` are removed.

Half close is kept for TCP upstreams with an HTTP/2 or HTTP/3
downstream, where END_STREAM maps to a TCP FIN (RFC 9113 §8.5). HTTP/1
downstreams can only end a CONNECT response by closing the connection,
so they keep the reset. The router enables it per stream when the conn
pool supports it (`GenericConnPool::supportsIndependentHalfClose()`),
through the new `DownstreamStreamFilterCallbacks::enableHalfClose()`.

Additional Description:
Follows @yanavlasov's proposal in #48316 to remove the flag. TCP tunnels
still need half close: without it, an origin that FINs after a download
resets the stream and the client gets a truncated body (#47378). This
supersedes the TCP part of #47378 (cc @fl0Lec) and makes #48316
unnecessary.

The decision uses the conn pool, not the route: the `http` upstream
factory ignores the requested protocol, so a CONNECT route can still
reach an HTTP/1 upstream (the #48316 crash path).

Risk Level: Medium. TCP tunnels now end with an end of stream instead of
a reset when the upstream half closes first. Revert with
`envoy.reloadable_features.tcp_tunnel_allow_upstream_half_close=false`.
Testing: Router unit tests, and
`ConnectTerminationIntegrationTest.UpstreamHalfCloseKeepsTunnelOpen` /
`UpstreamCloseWithHalfCloseDisabled`. Tests that only covered HTTP
upstream half close are removed.
Docs Changes: HTTP lifecycle in `http_connection_management.rst` and
`life_of_a_request.rst`.
Release Notes: Added.
Platform Specific Features: N/A
Runtime guard:
`envoy.reloadable_features.tcp_tunnel_allow_upstream_half_close`

AI assistance: prepared with AI assistance (Cursor agent). We reviewed
and understand all of it.

Signed-off-by: William Dauchy <[email protected]>
@RyanTheOptimist

Copy link
Copy Markdown
Contributor

/wait

This branch has not been deployed

No deployments
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.

8 participants