Skip to content

feat(keycardai-oauth): get resource tokens from the local Keycard agent - #435

Open
benburkert wants to merge 12 commits into
mainfrom
local-agent-token-source
Open

benburkert wants to merge 12 commits into
mainfrom
local-agent-token-source

Conversation

@benburkert

@benburkert benburkert commented Nov 17, 2026 •

Copy link
Copy Markdown

Summary

Implements Local Agent Token Source (keycard-sdk-spec specs/delegated-access/local-agent-token-source.md at 21b11f0) in keycardai-oauth.

  • AgentTokenSource.resource_token(resource, scopes) calls the agent's Connect IssueToken procedure (JSON over HTTP/1.1) on a Unix socket. No default timeout is applied; cancellation bounds the call.
  • Socket resolution follows the spec's three ordered rules: socket=, then KEYCARD_SOCKET, then the keycard agent daemon's default socket, resolved from the environment as the CLI resolves it. It reads env (default os.environ) on every call, never keycard.toml, and touches nothing on disk.
  • Errors join the existing hierarchy: AgentError (Connect code/message, read-only retryable) and AgentResponseError (an unusable 200) are OAuthError subclasses; ConfigError, NetworkError and OAuthHttpError are reused. The network error names the socket and the rule that chose it, and suggests keycard agent start / keycard run for the default socket. Messages never include the token.
  • AgentCode plus the predicates is_declined, is_rate_limited, is_prompter_unavailable, is_authorization_required, is_application_not_found and is_unavailable, which follow the cause chain (__cause__ and OAuthError.cause, not __context__).
  • ResourceAuth is the resource transport: an httpx.Auth for httpx.AsyncClient that sets Authorization: Bearer, replacing any existing value. It refuses a sync httpx.Client rather than send the request unauthenticated.
  • Example: packages/oauth/examples/agent_token_source (path dependency on the source tree).

The SDK does not cache tokens; the agent does (keycardlabs/cli#1343), so every call is one request to the agent. SDK caching is a follow-up: unit rows 19-23 are out of scope, and row 18 asserts two requests.

Replaces the draft in #382, which cached tokens in the SDK and, with KEYCARD_SOCKET unset, raised ConfigError instead of resolving the daemon's default socket, failing integration rows 7 and 8.

Open question for review

The transport is named ResourceAuth, to avoid confusion with httpx's own transports. The spec's same-concept-same-name principle argues for ResourceTransport, which Go and Ruby use. Rename before merge?

Review fixes

The od-review pass added 11 commits (196d3af..8816ea7). Each is listed with its finding in the review comment. Behavior changes:

  • The predicates follow OAuthError.cause.
  • A malformed scopes in a 200 leaves scope absent and keeps the token.
  • A 200 body over 1 MiB is an AgentResponseError.
  • A control character in org/zone is a ConfigError.
  • expiresAt accepts ASCII digits only.
  • The decode error no longer rides __context__.
  • The socket transport skips the CA bundle.

Test plan

  • oauth pytest tests/: 745 passed at 8816ea7; agent.py at 100% (715 before the review fixes)
  • Unit rows 1-18 and 24-38 as test_row_NN_* in tests/keycardai/oauth/test_agent.py
  • Integration rows 1-8 (the SDK-observable part) in test_agent_integration.py, against a fake agent (Starlette + uvicorn on a real Unix socket); no keycard binary, no network
  • just check (ruff) at 8816ea7
  • just typecheck (ty), cz check, and Python 3.10/3.12: passed at 81a84ef, not yet re-run after the review fixes (only 3.11 was run locally)
  • localdev: Integration rows 1-8 all pass against a real keycard agent daemon and zone at 8816ea7 (keycardlabs/e2e-sdk-localdev results/python; the report at that SHA is not yet committed there)

🤖 Generated with Claude Code

AgentTokenSource asks the local Keycard agent for an access token for a
named resource over the agent's IssueToken procedure, a Connect unary call
spoken as JSON over a Unix socket, so an application running beside the
Keycard CLI holds no application credential. It implements
specs/delegated-access/local-agent-token-source.md from keycard-sdk-spec
(21b11f0).

The socket is the socket option, else KEYCARD_SOCKET, else the keycard
agent daemon's default socket, resolved from the environment the way the
CLI resolves it (KEYCARD_AGENT_DIR, XDG_RUNTIME_DIR, XDG_STATE_HOME,
KEYCARD_HOME, HOME), never from keycard.toml and without touching disk.
Resolution runs on every call. An unreachable socket raises NetworkError
naming the path and the rule that chose it, and suggests `keycard agent
start` or `keycard run` when the default was used.

Refusals raise AgentError, an OAuthError carrying the Connect code, with
is_declined, is_rate_limited, is_prompter_unavailable,
is_authorization_required, is_application_not_found and is_unavailable
following the cause chain. An unusable 200 response raises
AgentResponseError, which never includes the token. ResourceAuth is the
resource transport, an httpx.Auth for httpx.AsyncClient that refuses a
synchronous client rather than sending the request unauthenticated.

The SDK does not cache tokens; the agent does (keycardlabs/cli#1343), so
every call is one request to it. Tests cover the spec's non-caching unit
rows and the SDK-observable part of its integration rows against a fake
agent, a Starlette app under uvicorn on a real Unix socket.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Release preview

keycardai-oauth 0.36.0 → 0.37.0 (minor)

  • test(keycardai-oauth): pin agent token source behavior that mutants survived
  • Each test below fails against a mutant that the existing suite let pass:
    • the expiry's fraction: a fractional clock, and a one-digit fraction
      (dropping + nanos / 1e9, and ljust turned rjust)
  • a +05:30 offset (offset minutes dropped)
  • scopes sent unsorted and with duplicates, as given
  • a 201, 204 or 302 as an HTTP error (!= 200 turned >= 400)
  • a non-string Connect message dropped to ""
  • empty KEYCARD_AGENT_DIR, XDG_RUNTIME_DIR, XDG_STATE_HOME, KEYCARD_HOME,
    socket= and HOME treated as unset
  • ResourceAuth copying its scopes, and asking with [] when given none
  • test(keycardai-oauth): share one Unix-socket server helper, under /tmp
    • short_tmp honoured TMPDIR, which on macOS leaves 9 bytes of the 104-byte
      socket path limit for the deepest default socket, and a long TMPDIR
      failed 11 agent tests. It now uses /tmp where that exists.
  • The resource server in the integration tests copied FakeAgent's uvicorn
    start loop without its task.done() check, so a bind failure spun
    forever. Both now go through serve_on_uds, which surfaces it.
  • agent_server stopped its agents one at a time, so one failure skipped
    the rest; an AsyncExitStack now stops every one.
  • fix(keycardai-oauth): refuse a control character in the agent's org or zone
  • org and zone become the Keycard-Org and Keycard-Zone headers. A CR, LF or
    other C0 byte in either was refused by h11 mid-send as a TransportError,
    which surfaced as a NetworkError: retryable, and blaming the socket for a
    caller's bad value. It is now a ConfigError before the socket is resolved,
    using the same control-character rule as the token check.
  • fix(keycardai-oauth): bound the agent's success response at 1 MiB
  • The error body was read to a 64 KiB prefix, but a 200 body was read with
    aread(), unbounded. The socket's owner is not checked, so a peer on it
    could stream an endless or decompression-amplified body. A 200 body over
    1 MiB is now an AgentResponseError. A new test streams an endless body on
    both paths, pinning the early break that a fully buffered MockTransport
    body could not observe.
  • fix(keycardai-oauth): accept only ASCII digits in the agent's expiresAt
  • Python's \d matches any Unicode decimal digit and int() accepts them, so
    "٢٠٣٠-01-01T00:00:00Z" parsed as a valid expiry. RFC 3339 allows ASCII
    digits only. The comment above the pattern also overstated what 3.11's
    fromisoformat fixes: nine fractional digits exceed datetime on every
    version.
  • fix(keycardai-oauth): keep the token when the agent's scopes are malformed
  • The spec sets the token's scope to the agent's scopes "when the response
    carries a non-empty list; absent otherwise", and its error table makes
    only a bad body, token or expiresAt an agent response error. A scopes
    value that is not a list of strings now leaves scope absent instead of
    discarding a usable token.
  • fix(keycardai-oauth): keep the agent's response body off context
  • raise ... from None suppresses the JSONDecodeError in tracebacks but
    leaves it on context, and its .doc is the whole response body, token
    included, for any code that walks the chain. The error is now raised
    outside the except block, and row 32 asserts context is None, with a
    malformed body that carries a token.
  • perf(keycardai-oauth): skip the CA bundle on the agent's Unix socket
  • httpx.AsyncHTTPTransport builds an SSL context in its constructor even for
    a uds transport, loading certifi each time: 9.09 ms per construction
    against 0.08 ms with verify=False (httpx 0.28.1). The transport is built
    per call because the socket is resolved per call, and ResourceAuth calls
    once per request, so every authenticated request paid it. TLS never
    applies on the plain-HTTP socket.
  • test(keycardai-oauth): make the empty-resource row fail without its check
  • With env={} socket resolution raised ConfigError on its own, so row 5
    passed with the empty-resource check deleted. Resolution now fails the
    test if it runs, and the error must name the resource.
  • fix(keycardai-oauth): agent predicates follow OAuthError.cause
  • OAuthError(message, cause) stores the wrapped error in .cause without
    setting cause, so an AgentError wrapped the way this SDK wraps errors
    was invisible to is_declined and the other predicates. The spec requires
    them to see through the language's wrapping chain. context stays
    unfollowed: raising inside except AgentError is a new failure.
  • feat(keycardai-oauth): get resource tokens from the local Keycard agent
  • AgentTokenSource asks the local Keycard agent for an access token for a
    named resource over the agent's IssueToken procedure, a Connect unary call
    spoken as JSON over a Unix socket, so an application running beside the
    Keycard CLI holds no application credential. It implements
    specs/delegated-access/local-agent-token-source.md from keycard-sdk-spec
    (21b11f0).
  • The socket is the socket option, else KEYCARD_SOCKET, else the keycard
    agent daemon's default socket, resolved from the environment the way the
    CLI resolves it (KEYCARD_AGENT_DIR, XDG_RUNTIME_DIR, XDG_STATE_HOME,
    KEYCARD_HOME, HOME), never from keycard.toml and without touching disk.
    Resolution runs on every call. An unreachable socket raises NetworkError
    naming the path and the rule that chose it, and suggests keycard agent start or keycard run when the default was used.
  • Refusals raise AgentError, an OAuthError carrying the Connect code, with
    is_declined, is_rate_limited, is_prompter_unavailable,
    is_authorization_required, is_application_not_found and is_unavailable
    following the cause chain. An unusable 200 response raises
    AgentResponseError, which never includes the token. ResourceAuth is the
    resource transport, an httpx.Auth for httpx.AsyncClient that refuses a
    synchronous client rather than sending the request unauthenticated.
  • The SDK does not cache tokens; the agent does (keycardlabs/cli#1343), so
    every call is one request to it. Tests cover the spec's non-caching unit
    rows and the SDK-observable part of its integration rows against a fake
    agent, a Starlette app under uvicorn on a real Unix socket.

No other package releases.


This comment was automatically generated by the release preview workflow.

benburkert and others added 11 commits November 18, 2026 15:26
OAuthError(message, cause) stores the wrapped error in .cause without
setting __cause__, so an AgentError wrapped the way this SDK wraps errors
was invisible to is_declined and the other predicates. The spec requires
them to see through the language's wrapping chain. __context__ stays
unfollowed: raising inside `except AgentError` is a new failure.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…heck

With env={} socket resolution raised ConfigError on its own, so row 5
passed with the empty-resource check deleted. Resolution now fails the
test if it runs, and the error must name the resource.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
httpx.AsyncHTTPTransport builds an SSL context in its constructor even for
a uds transport, loading certifi each time: 9.09 ms per construction
against 0.08 ms with verify=False (httpx 0.28.1). The transport is built
per call because the socket is resolved per call, and ResourceAuth calls
once per request, so every authenticated request paid it. TLS never
applies on the plain-HTTP socket.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
`raise ... from None` suppresses the JSONDecodeError in tracebacks but
leaves it on __context__, and its .doc is the whole response body, token
included, for any code that walks the chain. The error is now raised
outside the except block, and row 32 asserts __context__ is None, with a
malformed body that carries a token.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…ormed

The spec sets the token's scope to the agent's scopes "when the response
carries a non-empty list; absent otherwise", and its error table makes
only a bad body, token or expiresAt an agent response error. A scopes
value that is not a list of strings now leaves scope absent instead of
discarding a usable token.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Python's \d matches any Unicode decimal digit and int() accepts them, so
"٢٠٣٠-01-01T00:00:00Z" parsed as a valid expiry. RFC 3339 allows ASCII
digits only. The comment above the pattern also overstated what 3.11's
fromisoformat fixes: nine fractional digits exceed datetime on every
version.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The error body was read to a 64 KiB prefix, but a 200 body was read with
aread(), unbounded. The socket's owner is not checked, so a peer on it
could stream an endless or decompression-amplified body. A 200 body over
1 MiB is now an AgentResponseError. A new test streams an endless body on
both paths, pinning the early break that a fully buffered MockTransport
body could not observe.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…r zone

org and zone become the Keycard-Org and Keycard-Zone headers. A CR, LF or
other C0 byte in either was refused by h11 mid-send as a TransportError,
which surfaced as a NetworkError: retryable, and blaming the socket for a
caller's bad value. It is now a ConfigError before the socket is resolved,
using the same control-character rule as the token check.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…imeout notes

- On Windows the CLI's default agent endpoint is the named pipe
  \\.\pipe\keycard-agent (config_windows.go), not "a Unix socket"; the
  error now says so, and the docstring's transcription claim is scoped to
  the Unix AgentSocketPath.
- asyncio.timeout is 3.11+, and the package supports 3.10, so the
  README and docstring name asyncio.wait_for first.
- Drop the README snippet's unused is_declined import, and have the
  example smoke test assert main is a coroutine function, as its
  docstring says.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
- short_tmp honoured TMPDIR, which on macOS leaves 9 bytes of the 104-byte
  socket path limit for the deepest default socket, and a long TMPDIR
  failed 11 agent tests. It now uses /tmp where that exists.
- The resource server in the integration tests copied FakeAgent's uvicorn
  start loop without its task.done() check, so a bind failure spun
  forever. Both now go through serve_on_uds, which surfaces it.
- agent_server stopped its agents one at a time, so one failure skipped
  the rest; an AsyncExitStack now stops every one.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…urvived

Each test below fails against a mutant that the existing suite let pass:

- the expiry's fraction: a fractional clock, and a one-digit fraction
  (dropping `+ nanos / 1e9`, and ljust turned rjust)
- a +05:30 offset (offset minutes dropped)
- scopes sent unsorted and with duplicates, as given
- a 201, 204 or 302 as an HTTP error (`!= 200` turned `>= 400`)
- a non-string Connect message dropped to ""
- empty KEYCARD_AGENT_DIR, XDG_RUNTIME_DIR, XDG_STATE_HOME, KEYCARD_HOME,
  socket= and HOME treated as unset
- ResourceAuth copying its scopes, and asking with [] when given none

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@benburkert

Copy link
Copy Markdown
Author

Warning

Posted by Claude via /od-review


/od-review #435

Recommendation: Approve. The wire protocol and socket resolution match the CLI server on every Unix branch. This review fixed 15 findings in 11 commits pushed to this branch, including the two that should have blocked: F1, the is_* predicates missed the SDK's own cause= wrapping, and F2, row 5 passed without its check. With the fixes, the oauth suite passes (745 tests; agent.py at 100%), and so do localdev integration rows 1-8 against a real keycard agent daemon. What's left is five design questions, none of them blocking. On the naming question: keep ResourceAuth (F18).

ID Label Location Claim
F13 suggestion agent.py:388, 418 The token check rejects C0 and DEL but still accepts non-ASCII and spaces. Visible ASCII (0x21-0x7e, RFC 6750 b64token) would be stricter than the spec, so the SDKs should agree on it before any one of them adopts it
F16 question agent.py:74-87, 443 AgentError puts the peer's code and message into str(exc) as received, with no length cap. Should it fold control characters and cap the text?
F17 question types/models.py (not in this diff) TokenResponse's dataclass repr prints access_token. Use field(repr=False) in a follow-up?
F18 question agent.py:489 ResourceAuth or ResourceTransport? Recommend keeping ResourceAuth
F19 suggestion agent.py:229-232, cross-repo XDG says a relative XDG_* value must be ignored, but the CLI's xdgDir (config.go:586) accepts it. Fix the CLI first, then mirror it here

Not verified:

  • Conformance: no closing issue. The local reviewer checked the spec's MUSTs and test rows directly instead.
  • Blind-reader: it is Go-only.
  • Undead: the diff only adds code.
  • Python 3.10: only 3.11 was run locally.
  • ty: run with a newer version than the lockfile pins. It found nothing in agent.py, and 7 errors in the untouched types/models.py.
  • Localdev run: the CLI binary was built from a dirty main (e0b7dc6), and svc-sts was also dirty.
Fixed by this review (15 findings, 11 commits)

For each behavior fix, the test named first was written before the code change and failed against the old code.

Commit Finding Change RED
196d3af F1 · issue _agent_code also follows OAuthError.cause, which OAuthError(msg, cause=…) sets without setting __cause__. It still skips __context__, so raising inside except AgentError isn't counted as a refusal. Tests cover the cycle guard and the __context__ rule test_predicates_follow_oauth_error_cause: assert False where False = is_declined(OAuthError('token exchange failed'))
7c10996 F2 · issue Row 5 fails if socket resolution runs, so deleting the empty-resource check fails it. Verified by deleting that check n/a (test-only)
aec475f F3 AsyncHTTPTransport(uds=…, verify=False). httpx 0.28.1 loads the CA bundle in the constructor: 9.09 ms vs 0.08 ms, once per request through ResourceAuth n/a (performance only)
459607c F4 The JSON decode error is raised outside the except, so __context__ is None. from None only suppressed it, and its .doc held the whole body, token included test_row_32_unusable_success[malformed-json-with-token]: __context__ was a JSONDecodeError
b7a2c26 F5 A malformed scopes leaves scope=None instead of discarding the token. Spec line 68, and its error table at 360-362 test_malformed_scopes_is_treated_as_absent[a b]: raised AgentResponseError
74062f3 F12 re.ASCII on _RFC3339. The comment above it now says that nine-digit fractions exceed datetime on every Python version test_unparseable_expiry…[٢٠٣٠-01-01T00:00:00Z]: parsed
d1c5036 F11 A 200 body over 1 MiB raises AgentResponseError. A streamed endless body covers the early break on both paths test_success_body_is_bounded: returned a token
8558a10 F14 A C0 or DEL character in org or zone raises ConfigError before the socket is resolved. Before, it surfaced mid-send as a retryable NetworkError test_tenant_header_with_a_control_character…['a\r\nX-Injected: 1'-org]: no ConfigError
68502ad F6, F7, F20 · nitpicks The Windows error names the named pipe (config_windows.go:37). The docs name asyncio.wait_for alongside asyncio.timeout (3.11+). Unused README import removed. The example test asserts iscoroutinefunction n/a (docs)
c416595 F9, F10 short_tmp uses /tmp: a 120-character TMPDIR had failed 11 tests and now passes. A shared serve_on_uds surfaces a server that dies before serving, where the resource server's copy spun forever. AsyncExitStack stops every fake agent n/a (test-only)
8816ea7 F8, F15 Tests for the surviving mutants: fraction and padding, a +05:30 offset, scopes sent as given, a non-200 2xx or 3xx, a non-string message, empty socket variables, ResourceAuth scopes. Re-applying the fraction, padding, status and empty-HOME mutants now fails tests n/a (test-only)

Not fixed from F15:

  • unix_only and RESOURCE are still duplicated across the two test files, since importing from conftest.py is a pytest anti-pattern.
  • The timeout=None contract has no test, because one would need a deliberately slow run.
  • Row 38's "caller's request unchanged" clause and row 34's AttributeError check are as they were.

Checks after the fixes:

  • pytest tests/ (oauth): 745 passed.
  • agent.py coverage: 100% (220 statements).
  • ruff check: clean.
  • e2e-sdk-localdev bin/run python at 8816ea7: rows 1-8 PASS. That includes row 2's signature check against the zone's keys, row 3 with 0 svc-sts token requests, and row 6's keycard_declared_app_id.
Open findings F13, F16-F19 in full

F13 · suggestion: the token character set.

  • _has_control_character blocks every byte that can split a header.
  • It still accepts non-ASCII characters, C1 controls and spaces. A space produces a malformed Bearer value.
  • RFC 6750's b64token is visible ASCII only. Adopting it here would make Python stricter than the spec and the other SDKs, so change the spec first.

F16 · question: untrusted agent text.

  • The real agent sends fixed denial strings (run/issuetoken.go:60-130). A few CLI paths still pass an error's own text through (run/server.go:365, 766, 777, 862).
  • The realistic attacker is a rogue process on the socket, since its owner is not checked.
  • The CLI's own rule is to fold non-printing characters and cap at 500 characters, at the point where the untrusted value enters. That would go in _refusal, keeping the raw value on an attribute.
  • Counterpoint: a library that rewrites server text surprises callers who log it themselves.

F17 · question:

  • TokenResponse is a plain @dataclass, so repr, pytest's assertion diffs, and Sentry's capture of frame locals all print the token.
  • The model is shared, so this belongs in a follow-up PR.

F18 · question: naming.

  • In httpx, and in this SDK (http/transport.py's AsyncHTTPTransport protocol), "transport" means the layer that sends one request. Auth hooks are named *Auth.
  • The spec's divergence table (around line 452) already records "an httpx.Auth in Python".
  • The docstring's "The spec's resource transport" cross-reference is enough. Don't add an alias.

F19 · suggestion, cross-repo:

  • The XDG Base Directory spec says a relative path in these variables must be considered invalid and ignored.
  • If the SDK alone ignored relative values, it would miss the socket in the one case where the CLI still finds it.

Checked and found sound:

  • Request fields and the Keycard-Org and Keycard-Zone headers match services/agent.proto and services/client.go:25-26.
  • The Connect error codes match what run/issuetoken.go returns.
  • _resolve_socket matches config_unix.go:104-117 on every Unix branch.
  • The _RFC3339 regex is anchored with no nested repetition, so it cannot backtrack badly (ReDoS).
  • The sync-client refusal works.
  • Redirects: httpx runs async_auth_flow once per send and strips Authorization on a cross-origin redirect (_client.py:1645-1715), so a redirect never re-attaches the token.
  • The test dependencies are confined to the test extra.

@benburkert
benburkert marked this pull request as ready for review November 18, 2026 21:10

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Comment on lines +350 to +367
try:
async with (
httpx.AsyncClient(transport=transport, timeout=None) as client,
client.stream(
"POST", _ISSUE_TOKEN_URL, json=fields, headers=headers
) as response,
):
if response.status_code != 200:
raise _refusal(
response.status_code,
await _read_prefix(response, _ERROR_BODY_LIMIT),
)
content = await _read_prefix(response, _RESPONSE_BODY_LIMIT + 1)
if len(content) > _RESPONSE_BODY_LIMIT:
raise AgentResponseError("response is too large")
except httpx.TransportError as err:
raise NetworkError(err, operation=socket.describe()) from err

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) Callers can get a raw httpx.DecodingError instead of an OAuthError when the agent's 200 body has a bad Content-Encoding. The except httpx.TransportError at agent.py:366 misses it, because DecodingError subclasses RequestError, not TransportError. So except OAuthError handlers and the is_* predicates miss this failure. Fix: also catch httpx.DecodingError, or catch httpx.RequestError broadly, around the stream read. Map it to AgentResponseError (or NetworkError) so every httpx failure comes out under the documented hierarchy.

Why this was flagged

The agent, or any peer on the socket (the module comment at agent.py:47 says the owner is not checked), answers 200 with Content-Encoding: gzip and a truncated or corrupt body. Then response.aiter_bytes() in _read_prefix (agent.py:426) raises httpx.DecodingError. That class derives from httpx.RequestError, not httpx.TransportError, so the handler at agent.py:366-367 does not catch it. It escapes resource_token and ResourceAuth.async_auth_flow unwrapped. The docstring at agent.py:303-313 says only ConfigError, NetworkError, AgentError, OAuthHttpError or AgentResponseError are raised. Callers following it (except OAuthError, or the example's except (ConfigError, NetworkError) / except AgentError) crash with a traceback instead of handling the failure. This is new code, so there is no base behaviour. No test covers an encoding failure.

Verification: _read_prefix (agent.py:423-429) reads response.aiter_bytes(), which raises httpx.DecodingError on a corrupt gzip/deflate stream. DecodingError subclasses RequestError directly. The only handler is except httpx.TransportError at agent.py:365-366, so it does not catch DecodingError. The exception therefore leaves resource_token unwrapped.

Comment on lines +429 to +431
return bytes(prefix[:limit])


Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) A non-ASCII org or zone gets past the new header guard and fails as a raw UnicodeEncodeError instead of the documented ConfigError. _has_control_character (agent.py:429-431) rejects only C0 controls and DEL. httpx encodes header values as ASCII, so any non-ASCII character raises inside client.stream, outside every handler. Fix: also reject non-ASCII characters (or anything outside visible ASCII) in org/zone with ConfigError. Apply the same check to the token (agent.py:386) so ResourceAuth cannot fail the same way on a bad agent response.

Why this was flagged

Trigger: an AgentTokenSource(org=..., zone=...) value with a non-ASCII character. Example: a copy-pasted id with a non-breaking space or smart quote, read from KEYCARD_ORG/KEYCARD_ZONE as in examples/agent_token_source/main.py. The guard at agent.py:315-317 calls _has_control_character, which only checks c < " " or c == "\x7f", so the value passes. It is put into the Keycard-Org/Keycard-Zone headers at agent.py:334-337. httpx encodes header string values as ASCII by default, so building the request at agent.py:348-352 raises UnicodeEncodeError. That is not an httpx.TransportError or an OAuthError, so it escapes resource_token. The docstring promises ConfigError for bad org/zone. Likewise, a 200 token with a non-ASCII character passes the agent.py:386 check, and ResourceAuth.async_auth_flow (agent.py:521) then raises UnicodeEncodeError when it sets the Authorization header. That breaks the promise that errors from the source come out as OAuthError subclasses.

Verification: nit. The trigger is an org or zone value that contains a non-ASCII character. _has_control_character (agent.py:418-420) returns any(c < " " or c == "\x7f" for c in value). httpx encodes header values as ASCII and raises UnicodeEncodeError, which the only handler, except httpx.TransportError at agent.py:365, does not catch.

Comment on lines +360 to +367
await _read_prefix(response, _ERROR_BODY_LIMIT),
)
content = await _read_prefix(response, _RESPONSE_BODY_LIMIT + 1)
if len(content) > _RESPONSE_BODY_LIMIT:
raise AgentResponseError("response is too large")
except httpx.TransportError as err:
raise NetworkError(err, operation=socket.describe()) from err

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) A peer on the socket can still make the SDK allocate tens of MB or more per read, despite the 1 MiB cap claimed to stop decompression-amplified bodies. _read_prefix checks the length only after httpx decodes each raw network chunk in full. A single compressed chunk can expand far past _RESPONSE_BODY_LIMIT before the check runs. Fix: send Accept-Encoding: identity and read with aiter_raw(), rejecting any response that carries a Content-Encoding. Alternatively, cap the decoded size incrementally; either way covers both the success and the _ERROR_BODY_LIMIT error paths.

Why this was flagged

The trigger is a misbehaving or hostile process listening on the socket (agent.py:47-49 says the owner is not checked). httpx advertises gzip/deflate, plus br/zstd when those packages are installed, and decodes in aiter_bytes(). Its decoders call decompress(data) with no max_length, so one ~64 KiB raw chunk of gzip zeros expands to roughly 64 MB in a single yield. A brotli or zstd chunk can expand much further. _read_prefix (agent.py:360-367) sees that chunk only after it is fully materialized, then slices it. The cap at agent.py:347-349 bounds the bytes kept, not the memory allocated. A deeper check of the httpx decoder internals was not possible from this checkout.

Verification: The trigger is a hostile process on the resolved socket that answers 200 with a highly compressed body. _read_prefix (agent.py:423-429) only checks the length after each item that response.aiter_bytes() yields. So one raw chunk of gzip or deflate zeros is fully inflated (roughly 64 MB) before the 1 MiB check runs. The base branch had no agent code, so the change introduces this.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant