Skip to content

fix(plugins): redact API keys from rejected websocket handshakes - #7032

Merged
davidzhao merged 2 commits into
livekit:mainfrom
aniketwaghh:fix-ws-handshake-key-leak
Aug 30, 2026
Merged

davidzhao merged 2 commits into
livekit:mainfrom
aniketwaghh:fix-ws-handshake-key-leak

Conversation

@aniketwaghh

Copy link
Copy Markdown
Contributor

Summary

WSServerHandshakeError subclasses aiohttp.ClientResponseError, so it is neither an aiohttp.ClientConnectorError nor an asyncio.TimeoutError. Six credentialed ws_connect sites still wrapped the connect in except (aiohttp.ClientConnectorError, asyncio.TimeoutError), so a rejected upgrade matched neither handler and escaped uncaught, carrying RequestInfo and therefore the auth header.

Same failure as #6739, which #6740 fixed for cartesia. That reporter asked whether it was "the cartesia plugin, or more g[enerally]"; these are the sites where it was still reachable.

plugin file
deepgram stt.py, stt_v2.py
simplismart stt.py
smallestai stt.py
xai stt.py, tts.py

Fixes #7031

Approach

The shape from #6740, applied unchanged: handle asyncio.TimeoutError and aiohttp.ClientResponseError separately, re-raise with from None, and surface only the status and type(e).__name__ rather than str(e) or repr(e).

I scoped this by parsing every try block containing a credentialed ws_connect and reading which exception types its handlers actually name, rather than grepping. My first grep pass wrongly cleared deepgram/stt.py, which is why the count is from the AST walk. The other ten credentialed sites already catch the response error or re-raise with from None, and are untouched here.

Verification

A local server refusing the upgrade with 401, called with deepgram's exact call shape.

Before:

WSServerHandshakeError escaped the handler
WSServerHandshakeError(RequestInfo(url=URL('http://127.0.0.1:8781/v1/listen?model=nova-2'),
method='GET', headers=<CIMultiDictProxy('Host': '127.0.0.1:8781',
'Authorization': 'Token dg_live_SUPERSECRET_abcdef0123456789', ...
API KEY PRESENT IN EXCEPTION REPR: True

After, the same request raises APIStatusError: Invalid response status, status_code 401, __cause__ None, and the key appears in neither str() nor repr().

Checked what actually reaches a log, since that was the reported symptom:

KEY in traceback.print_exc() output:   False
KEY in logger.exception() output:      False

One thing worth stating plainly: raise ... from None suppresses __cause__ and sets __suppress_context__, so tracebacks and logging.exception omit the original error, which is the #6739 symptom. The original exception object does remain on __context__, so an error reporter that walks the context chain and ignores the suppress flag could still reach it. That is equally true of the cartesia fix in #6740; I have kept the same shape rather than diverge. Happy to go further if you would rather these paths scrub RequestInfo explicitly.

Tests

tests/test_ws_handshake_credential_redaction.py, mirroring tests/test_plugin_cartesia_tts.py from #6740: construct a WSServerHandshakeError whose RequestInfo headers carry the key, drive the real _connect_ws, and assert APIStatusError with the status preserved, the key absent from str and repr, and __cause__ None. Marked per plugin so they run under the existing --plugin filtering.

ruff check and ruff format clean on all seven files.

WSServerHandshakeError subclasses ClientResponseError, so it is neither a ClientConnectorError nor an asyncio.TimeoutError. Six credentialed ws_connect sites caught only those two, letting a 401/403 upgrade escape carrying RequestInfo, whose headers hold the key.

Apply the shape used for cartesia in livekit#6740: handle the response error separately and re-raise with 'from None', surfacing only the status and the exception type.

Affects deepgram (stt, stt_v2), simplismart, smallestai and xai (stt, tts).

Fixes livekit#7031
@aniketwaghh
aniketwaghh requested a review from a team as a code owner August 29, 2026 02:10
@CLAassistant

CLAassistant commented Aug 29, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@devin-ai-integration devin-ai-integration Bot left a comment •

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.

Note

This report is out of date. Scroll down for Devin Review's latest report on this PR.

🔍 Devin Review: 1 flag

Not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)

Devin Review

…logging

The catch-all added for credential redaction also covered the statements that run after a successful connect, including a read of the private ws._response attribute. An AttributeError there would have been converted into a retryable APIConnectionError, masking the bug and spinning the reconnect loop.

Narrow each try to the connect call, matching the scope cartesia guards in livekit#6740.

@devin-ai-integration devin-ai-integration Bot left a comment

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.

Devin Review found 1 new potential issue.

1 flag not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)

Devin Review

Comment on lines +792 to +797
ws_headers = {
k: v for k, v in ws._response.headers.items() if k.startswith("dg-") or k == "Date"
}
logger.debug(
"Established new Deepgram STT WebSocket connection:",
extra={"headers": ws_headers},

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.

🟨 Provider headers bypass PII redaction

Successful connections log all dg-* response headers under headers. Sensitive provider metadata cannot be redacted because the key lacks a pii segment.

Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

@aniketwaghh

Copy link
Copy Markdown
Contributor Author

Pushed faf17dd after a second look at the scope of the catch-all.

The first commit kept each plugin's existing try boundary and only swapped the handlers. In deepgram (stt.py, stt_v2.py) and smallestai that boundary also covers the statements that run after a successful connect, including a read of the private ws._response attribute. So an AttributeError there, from an aiohttp change rather than a connection problem, would have been converted into a retryable APIConnectionError and hidden behind a "failed to connect" message while the reconnect loop kept going. Before this PR it would have propagated. Narrowing each try to the connect call removes that and matches the scope cartesia guards in #6740, which wraps exactly one statement.

Two things I checked while I was in here, in case they come up in review.

APIStatusError already derives retryability from the status, so a 401 or 403 comes back non-retryable and the stream stops instead of reconnecting against a key that will keep failing. That is a change from today, where the handshake error escapes the handler entirely.

ClientConnectorError no longer has its own clause and now lands in the catch-all, so its message gains a (ClientConnectorError) suffix. Retryability is unchanged.

Redaction and lint are unchanged after the narrowing: 0 unguarded credentialed ws_connect sites, and the key is absent from both traceback.print_exc() and logging.exception output.

@aniketwaghh

Copy link
Copy Markdown
Contributor Author

On the header-logging flag at stt.py:792-797: that block predates this PR. It came in with #6444 and this branch only dedents it, moving it out of the try in faf17dd. Removed and added lines are identical once you strip indentation.

The convention point looks right to me though. extra={"headers": ws_headers} does not carry an lk.pii. prefix, so it is outside the redaction path that lk.pii.dtmf_inputs and lk.pii.arguments use elsewhere in the SDK. What lands there is Deepgram response headers filtered to dg-* plus Date, so request ids and model metadata rather than credentials or caller data, and it is behind logger.debug. Lower stakes than what this PR is about, and a different concern from the request-side leak.

Leaving it out to keep this PR to the credential path. Happy to open a separate one for the lk.pii. prefix if you want it, here and anywhere else extra= carries provider metadata.

luzmariatorres895-ops

This comment was marked as off-topic.

@davidzhao
davidzhao merged commit 79d9992 into livekit:main Aug 30, 2026
17 checks passed
aniketwaghh added a commit to aniketwaghh/aniketwaghh that referenced this pull request Aug 30, 2026
livekit/agents#7032 was approved and merged by davidzhao on 2026-08-30, so the
API-key redaction fix moves into the merged table - five merged PRs now.

Adds n8n#37359 to the hidden in-review list.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

API keys leak into logs when a websocket upgrade is rejected (6 sites still unguarded after #6740)

4 participants