Skip to content

Commit 3622a97

Browse files
fix(realtime): validate beta WebSocket authentication profiles (#4218)
A bare workload-identity or Bedrock client could attempt a beta Realtime handshake without applying its configured authentication. Reject those unsupported profiles locally before credential refresh or connection, and enforce the documented X.509 WebSocket exclusion. Preserve explicit `Authorization` settings for other clients, including default and connection headers, case-insensitive overrides, and removal with `omit`. Document this compatibility boundary without adding provider token exchange or signing. Validation: - Before the change: 8 refusal cases failed and 16 explicit-header compatibility cases passed. - After the change: all 24 profile tests passed. - All 74 focused tests passed, including existing beta Azure and redirect controls; the same 74 passed against a locally built, non-editable wheel. - Ruff formatting, lint, and diff checks passed. --------- Co-authored-by: markstuart-oai <[email protected]>
1 parent 83ed269 commit 3622a97

4 files changed

Lines changed: 172 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,10 @@ The Realtime API enables you to build low-latency, multi-modal conversational ex
390390

391391
Under the hood the SDK uses the [`websockets`](https://websockets.readthedocs.io/en/stable/) library to manage connections.
392392

393+
The retained `client.beta.realtime` interface does not exchange workload-identity tokens or sign Bedrock requests. A client using either method must supply its own `Authorization` settings through `default_headers` or `connect(extra_headers=...)`. Otherwise, the SDK rejects the WebSocket connection locally.
394+
395+
Connection headers override default headers case-insensitively, and `omit` removes a header. These settings preserve the caller's header choices without enabling provider authentication. X.509 workload identity supports HTTP only. Beta WebSockets always reject X.509 clients, even with explicit headers.
396+
393397
The Realtime API works through a combination of client-sent events and server-sent events. Clients can send events to do things like update session configuration or send text and audio inputs. Server events confirm when audio responses have completed, or when a text response from the model has been received. A full event reference can be found [here](https://platform.openai.com/docs/api-reference/realtime-client-events) and a guide can be found [here](https://platform.openai.com/docs/guides/realtime).
394398

395399
Basic text based example:

‎src/openai/lib/_client_auth.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,17 @@ def _has_omitted_header(headers: Headers, header: str) -> bool:
5151
)
5252

5353

54+
def _validate_beta_realtime_auth(self: _sdk_client.OpenAI | _sdk_client.AsyncOpenAI, extra_headers: Headers) -> None:
55+
if _sdk_client.is_x509_workload_identity(self.workload_identity):
56+
raise _sdk_client.OpenAIError("This authentication method is not supported by WebSocket connections")
57+
if (self.workload_identity is not None or self._provider_runtime is not None) and not (
58+
_has_header(self.default_headers, "Authorization") or _has_header(extra_headers, "Authorization")
59+
):
60+
# Retained beta connections allow caller-owned authentication, including
61+
# an explicit Omit. They do not exchange or sign provider credentials.
62+
raise _sdk_client.OpenAIError("This authentication method is not supported by WebSocket connections")
63+
64+
5465
def _set_request_api_key(
5566
self: _sdk_client.OpenAI | _sdk_client.AsyncOpenAI, options: FinalRequestOptions, api_key: str
5667
) -> None:

‎src/openai/resources/beta/realtime/realtime.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,9 @@ async def __aenter__(self) -> AsyncRealtimeConnection:
351351
await connection.close()
352352
```
353353
"""
354+
from ....lib._client_auth import _validate_beta_realtime_auth
355+
356+
_validate_beta_realtime_auth(self.__client, self.__extra_headers)
354357
try:
355358
from ....lib._websocket import _WebSocketConnect as connect
356359
except ImportError as exc:
@@ -538,6 +541,9 @@ def __enter__(self) -> RealtimeConnection:
538541
connection.close()
539542
```
540543
"""
544+
from ....lib._client_auth import _validate_beta_realtime_auth
545+
546+
_validate_beta_realtime_auth(self.__client, self.__extra_headers)
541547
try:
542548
from websockets.sync.client import connect
543549
except ImportError as exc:
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
"""Offline beta Realtime provider preflight and explicit-header compatibility."""
2+
3+
from __future__ import annotations
4+
5+
import threading
6+
from typing import Any
7+
8+
import httpx2
9+
import pytest
10+
from websockets.sync.server import serve
11+
12+
import openai
13+
from openai.auth import WorkloadIdentity, x509_workload_identity
14+
from openai.providers import bedrock
15+
16+
17+
@pytest.fixture(autouse=True)
18+
def synthetic_environment(monkeypatch: pytest.MonkeyPatch) -> None:
19+
for name in (
20+
"OPENAI_API_KEY",
21+
"OPENAI_ADMIN_KEY",
22+
"OPENAI_BASE_URL",
23+
"OPENAI_ORG_ID",
24+
"OPENAI_PROJECT_ID",
25+
"OPENAI_CUSTOM_HEADERS",
26+
"OPENAI_WEBHOOK_SECRET",
27+
):
28+
monkeypatch.delenv(name, raising=False)
29+
monkeypatch.setenv("NO_PROXY", "127.0.0.1")
30+
monkeypatch.setenv("no_proxy", "127.0.0.1")
31+
32+
33+
def identity(kind: str, callbacks: list[str]) -> dict[str, Any]:
34+
def token() -> str:
35+
callbacks.append("token")
36+
raise AssertionError("implicit provider credential callback must not run")
37+
38+
if kind == "bedrock":
39+
return {"provider": bedrock(region="us-east-1", token_provider=token)}
40+
if kind == "workload":
41+
return {
42+
"workload_identity": WorkloadIdentity(
43+
identity_provider_id="idp_synthetic",
44+
service_account_id="sa_synthetic",
45+
provider={"token_type": "jwt", "get_token": token},
46+
)
47+
}
48+
return {
49+
"workload_identity": x509_workload_identity(
50+
identity_provider_id="idp_synthetic", service_account_id="sa_synthetic"
51+
)
52+
}
53+
54+
55+
async def connect(
56+
mode: str, kind: str, defaults: dict[str, Any], extra: dict[str, Any]
57+
) -> tuple[BaseException | None, list[str], list[list[str]]]:
58+
callbacks: list[str] = []
59+
upgrades: list[list[str]] = []
60+
headers_captured = threading.Event()
61+
62+
def issuer(_request: httpx2.Request) -> httpx2.Response:
63+
callbacks.append("issuer")
64+
raise AssertionError("implicit HTTP exchange must not run")
65+
66+
def peer(socket: Any) -> None:
67+
assert socket.request.path.startswith("/v1/realtime?")
68+
assert socket.request.headers["X-Beta-Client"] == "synthetic-default"
69+
assert socket.request.headers["X-Beta-Connection"] == "synthetic-extra"
70+
upgrades.append(socket.request.headers.get_all("Authorization"))
71+
headers_captured.set()
72+
socket.close(1000)
73+
74+
auth = identity(kind, callbacks)
75+
defaults = {"X-Beta-Client": "synthetic-default", **defaults}
76+
extra = {"X-Beta-Connection": "synthetic-extra", **extra}
77+
refused: BaseException | None = None
78+
with serve(peer, "127.0.0.1", 0, close_timeout=1) as server:
79+
worker = threading.Thread(target=server.serve_forever)
80+
worker.start()
81+
try:
82+
url = f"ws://127.0.0.1:{server.socket.getsockname()[1]}/v1"
83+
if mode == "sync":
84+
with openai.OpenAI(
85+
**auth,
86+
default_headers=defaults,
87+
websocket_base_url=url,
88+
http_client=httpx2.Client(transport=httpx2.MockTransport(issuer), trust_env=False),
89+
max_retries=0,
90+
) as client:
91+
try:
92+
with client.beta.realtime.connect(model="gpt-realtime", extra_headers=extra):
93+
assert headers_captured.wait(3), "Peer did not record upgrade headers"
94+
except openai.OpenAIError as failure:
95+
refused = failure
96+
else:
97+
async with openai.AsyncOpenAI(
98+
**auth,
99+
default_headers=defaults,
100+
websocket_base_url=url,
101+
http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(issuer), trust_env=False),
102+
max_retries=0,
103+
) as client:
104+
try:
105+
async with client.beta.realtime.connect(model="gpt-realtime", extra_headers=extra):
106+
assert headers_captured.wait(3), "Peer did not record upgrade headers"
107+
except openai.OpenAIError as failure:
108+
refused = failure
109+
finally:
110+
server.shutdown()
111+
worker.join(3)
112+
assert not worker.is_alive()
113+
return refused, callbacks, upgrades
114+
115+
116+
@pytest.mark.parametrize("mode", ["sync", "async"])
117+
@pytest.mark.parametrize("kind", ["workload", "x509", "bedrock"])
118+
async def test_bare_beta_provider_is_rejected_before_credentials_or_upgrade(mode: str, kind: str) -> None:
119+
refused, callbacks, upgrades = await connect(mode, kind, {}, {})
120+
assert refused is not None and "not supported by WebSocket" in str(refused)
121+
assert callbacks == [] and upgrades == []
122+
123+
124+
@pytest.mark.parametrize("mode", ["sync", "async"])
125+
async def test_x509_explicit_header_does_not_enable_unsupported_websocket_profile(mode: str) -> None:
126+
refused, callbacks, upgrades = await connect(mode, "x509", {}, {"Authorization": "Bearer synthetic-manual"})
127+
assert refused is not None and "not supported by WebSocket" in str(refused)
128+
assert callbacks == [] and upgrades == []
129+
130+
131+
@pytest.mark.parametrize("mode", ["sync", "async"])
132+
@pytest.mark.parametrize("kind", ["workload", "bedrock"])
133+
@pytest.mark.parametrize("header_profile", ["default", "extra", "override", "omit"])
134+
async def test_beta_explicit_authorization_policy_is_preserved(mode: str, kind: str, header_profile: str) -> None:
135+
defaults: dict[str, Any] = {}
136+
extra: dict[str, Any] = {}
137+
expected = ["Bearer synthetic-manual"]
138+
if header_profile == "default":
139+
defaults = {"authorization": "Bearer synthetic-manual"}
140+
elif header_profile == "extra":
141+
extra = {"authorization": "Bearer synthetic-manual"}
142+
elif header_profile == "override":
143+
defaults = {"Authorization": "Bearer synthetic-overridden"}
144+
extra = {"AUTHORIZATION": "Bearer synthetic-manual"}
145+
else:
146+
defaults = {"Authorization": "Bearer synthetic-overridden"}
147+
extra = {"authorization": openai.omit}
148+
expected = []
149+
refused, callbacks, upgrades = await connect(mode, kind, defaults, extra)
150+
assert refused is None and callbacks == []
151+
assert upgrades == [expected]

0 commit comments

Comments
 (0)