Skip to content

Negotiate WebSocket v5 in the async exec client - #2797

Merged
kubernetes-prow[bot] merged 3 commits into
kubernetes-client:masterfrom
brendandburns:agent/p2-issue-14
Nov 24, 2026
Merged

kubernetes-prow[bot] merged 3 commits into
kubernetes-client:masterfrom
brendandburns:agent/p2-issue-14

Conversation

@brendandburns

@brendandburns brendandburns commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Async exec offered only v4.channel.k8s.io, causing upgrade failures with servers requiring v5. The client now offers v5 with v4 fallback and handles v5 channel-close frames in buffered responses.

Negotiation: Use aiohttp’s subprotocol negotiation and preserve explicitly configured subprotocol headers.
Sec-WebSocket-Protocol: v5.channel.k8s.io,v4.channel.k8s.io
Channel closure: Buffered responses stop collecting data from a channel after its v5 close frame while continuing to collect other channels.
Raw streams: Return the unprocessed aiohttp WebSocket; callers remain responsible for channel framing and close messages.

Fixes: #2355

Negotiate `v5.channel.k8s.io` (with `v4.channel.k8s.io` fallback) and handle v5 channel-close frames in `kubernetes.aio.stream.WsApiClient` for async pod exec.

* fix: negotiate async WebSocket v5 with v4 fallback
@kubernetes-prow kubernetes-prow Bot added do-not-merge/release-note-label-needed Indicates that a PR should not merge because it's missing one of the release note labels. needs-kind Indicates a PR lacks a `kind/foo` label and requires one. cncf-cla: yes Indicates the PR's author has signed the CNCF CLA. labels Nov 19, 2026
@kubernetes-prow
kubernetes-prow Bot requested review from roycaihw and yliaog November 19, 2026 02:41
@kubernetes-prow kubernetes-prow Bot added the size/L Denotes a PR that changes 100-499 lines, ignoring generated files. label Nov 19, 2026
@aojea

aojea commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

I see, so we have two codepaths and we only have v5 implemented in one of the clients @yliaog ? #2486

@aojea

aojea commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

can we have an e2e test?

@yliaog

yliaog commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Yes, we have two, one sync, one async in the repo.

/assign @aojea

@aojea

aojea commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

@brendandburns is it possible to have an e2e test that exercises the entire path end to end?

@brendandburns

Copy link
Copy Markdown
Contributor Author

@aojea e2e test added.

@roycaihw roycaihw left a comment

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.

LGTM.

/kind bug
/approve

@kubernetes-prow kubernetes-prow Bot added release-note Denotes a PR that will be considered when it comes time to generate release notes. kind/bug Categorizes issue or PR as related to a bug. approved Indicates a PR has been approved by an approver from all required OWNERS files. and removed do-not-merge/release-note-label-needed Indicates that a PR should not merge because it's missing one of the release note labels. needs-kind Indicates a PR lacks a `kind/foo` label and requires one. labels Nov 24, 2026
Comment on lines +126 to +138
protocol_header = next(
(key for key in headers if key.lower() == 'sec-websocket-protocol'),
None,
)
if protocol_header is None:
protocols = [V5_CHANNEL_PROTOCOL, V4_CHANNEL_PROTOCOL]
headers['sec-websocket-protocol'] = ','.join(protocols)
else:
protocols = [
protocol.strip()
for protocol in headers[protocol_header].split(',')
if protocol.strip()
]

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.

Small thing here: if the caller passes a headers dict without sec-websocket-protocol, setting headers['sec-websocket-protocol'] mutates their dict in place. Making a shallow copy first avoids that. Also, if someone explicitly passes an empty or whitespace-only Sec-WebSocket-Protocol header, protocols ends up empty and aiohttp leaves the empty header on the wire instead of falling back or failing cleanly.

Comment thread kubernetes/aio/stream/ws_client.py Outdated
Comment on lines +158 to +160
data = msg.data
if len(data) > 1:
channel = data[0] if isinstance(data, bytes) else ord(data[0])

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.

We should check msg.type before touching msg.data. In aiohttp, async for msg in ws only stops on CLOSE/CLOSING/CLOSED, so a WSMsgType.ERROR message (for instance from a parser error or heartbeat timeout) still comes through here with msg.data set to the exception. Calling len(data) will mask the real failure with a TypeError instead of raising ws.exception() or msg.data. Non-data message types should be skipped.

Comment thread kubernetes/aio/stream/ws_client.py Outdated
Comment on lines +162 to +170
channel == CLOSE_CHANNEL
and ws.protocol == V5_CHANNEL_PROTOCOL
):
closed_channel = (
data[1] if isinstance(data, bytes) else ord(data[1])
)
closed_channels.add(closed_channel)
continue
if channel in closed_channels:

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.

In v5, the close signal is strictly a 2-byte binary frame ([255, channel], matching wsstream/conn.go on the server side which checks len(data) != 2). Checking len(data) > 1 here will silently accept malformed frames like b'\xff\x01extra' as a valid close, and doing ord(data[0]) == CLOSE_CHANNEL on a text frame would treat a frame starting with 'ÿ' (U+00FF) as a close signal. We should restrict CLOSE_CHANNEL handling to WSMsgType.BINARY frames with len(data) == 2, and drop any other frame on CLOSE_CHANNEL.

Comment thread kubernetes/aio/stream/ws_client.py Outdated
Comment on lines +173 to +176
if isinstance(data, bytes):
data = data.decode('utf-8')
if data and channel in [STDOUT_CHANNEL, STDERR_CHANNEL]:
resp_all += data

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.

Two issues with decoding here. First, data.decode('utf-8') runs before checking whether channel is stdout or stderr, so non-UTF-8 bytes on any ignored channel (including b'\xff\x80' on a v4 connection) will raise UnicodeDecodeError even though we were going to drop the frame.

Second, decoding each WebSocket frame independently with strict UTF-8 will fail whenever the server splits a multi-byte UTF-8 character across two frames, or if the command writes invalid UTF-8 bytes (the sync client uses 'replace' for that reason). Keeping a per-channel codecs.getincrementaldecoder('utf-8')('replace') for stdout and stderr handles interleaved frames and split characters cleanly, and we can flush a channel's decoder with final=True when its v5 close frame arrives (and flush any remaining open channels after the loop ends).

Comment thread kubernetes/aio/stream/ws_client_test.py Outdated

class WsMock:
def __init__(self):
def __init__(self, messages=None, protocol=None):

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.

WsMock currently yields WsResponse objects without a type attribute instead of aiohttp.WSMessage, which is why the WSMsgType.ERROR case wasn't caught. Updating the mock to emit WSMessage and adding unit tests for v4 ignoring b'\xff\x01' / b'\xff\x80', malformed close frames (b'\xff', b'\xff\x01\x02'), 1-byte empty frames like b'\x01', split multi-byte UTF-8 across frames (including flushing on v5 close), and WSMsgType.ERROR would lock down all of these edge cases.

Comment on lines +82 to +83
'value=$(cat); printf "received:%s" "$value"; '
'printf error-output >&2'],

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.

Nit: assertIn('stdout', result) and assertIn('stderr', result) would still pass if stray channel bytes or duplicated output leaked into the buffer. Asserting len(result) == len('stdout') + len('stderr') alongside those two checks (or splitting into single-stream checks) would keep it order-independent while still catching extra bytes.

@aojea

aojea commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

some comments but almost there

@linux-foundation-easycla

linux-foundation-easycla Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

@kubernetes-prow kubernetes-prow Bot added cncf-cla: no Indicates the PR's author has not signed the CNCF CLA. and removed cncf-cla: yes Indicates the PR's author has signed the CNCF CLA. labels Nov 24, 2026
@brendandburns

Copy link
Copy Markdown
Contributor Author

@aojea I believe all comments are addressed, please take another look.

Address review feedback on protocol headers, message errors, strict v5 channel closes, incremental decoding, and regression coverage.
@kubernetes-prow kubernetes-prow Bot added cncf-cla: yes Indicates the PR's author has signed the CNCF CLA. and removed cncf-cla: no Indicates the PR's author has not signed the CNCF CLA. labels Nov 24, 2026
@aojea

aojea commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

/lgtm
/approve

Thanks

@kubernetes-prow

Copy link
Copy Markdown
Contributor

@aojea: changing LGTM is restricted to collaborators

Details

In response to this:

/lgtm
/approve

Thanks

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@roycaihw

Copy link
Copy Markdown
Member

/lgtm
/approve

@kubernetes-prow kubernetes-prow Bot added the lgtm "Looks good to me", indicates that a PR is ready to be merged. label Nov 24, 2026
@kubernetes-prow

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: aojea, brendandburns, roycaihw

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

@kubernetes-prow
kubernetes-prow Bot merged commit be35e0e into kubernetes-client:master Nov 24, 2026
10 checks passed
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. cncf-cla: yes Indicates the PR's author has signed the CNCF CLA. kind/bug Categorizes issue or PR as related to a bug. lgtm "Looks good to me", indicates that a PR is ready to be merged. release-note Denotes a PR that will be considered when it comes time to generate release notes. 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.

sec-websocket-protocol header defaults to v4.channel.k8s.io causing HTTP 400

4 participants