Repository navigation
feat(keycardai-oauth): get resource tokens from the local Keycard agent - #435
benburkert wants to merge 12 commits into
Conversation
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>
Release previewkeycardai-oauth 0.36.0 → 0.37.0 (minor)
No other package releases. This comment was automatically generated by the release preview workflow. |
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>
|
Warning Posted by Claude via /od-review
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
Not verified:
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.
Not fixed from F15:
Checks after the fixes:
Open findings F13, F16-F19 in fullF13 · suggestion: the token character set.
F16 · question: untrusted agent text.
F17 · question:
F18 · question: naming.
F19 · suggestion, cross-repo:
Checked and found sound:
|
| 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 | ||
|
|
There was a problem hiding this comment.
🟡 (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.
| return bytes(prefix[:limit]) | ||
|
|
||
|
|
There was a problem hiding this comment.
🟡 (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.
| 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 | ||
|
|
There was a problem hiding this comment.
🟡 (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.
Summary
Implements Local Agent Token Source (keycard-sdk-spec
specs/delegated-access/local-agent-token-source.mdat21b11f0) inkeycardai-oauth.AgentTokenSource.resource_token(resource, scopes)calls the agent's ConnectIssueTokenprocedure (JSON over HTTP/1.1) on a Unix socket. No default timeout is applied; cancellation bounds the call.socket=, thenKEYCARD_SOCKET, then thekeycard agentdaemon's default socket, resolved from the environment as the CLI resolves it. It readsenv(defaultos.environ) on every call, neverkeycard.toml, and touches nothing on disk.AgentError(Connectcode/message, read-onlyretryable) andAgentResponseError(an unusable 200) areOAuthErrorsubclasses;ConfigError,NetworkErrorandOAuthHttpErrorare reused. The network error names the socket and the rule that chose it, and suggestskeycard agent start/keycard runfor the default socket. Messages never include the token.AgentCodeplus the predicatesis_declined,is_rate_limited,is_prompter_unavailable,is_authorization_required,is_application_not_foundandis_unavailable, which follow the cause chain (__cause__andOAuthError.cause, not__context__).ResourceAuthis the resource transport: anhttpx.Authforhttpx.AsyncClientthat setsAuthorization: Bearer, replacing any existing value. It refuses a synchttpx.Clientrather than send the request unauthenticated.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_SOCKETunset, raisedConfigErrorinstead 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 forResourceTransport, 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:OAuthError.cause.scopesin a 200 leavesscopeabsent and keeps the token.AgentResponseError.org/zoneis aConfigError.expiresAtaccepts ASCII digits only.__context__.Test plan
pytest tests/: 745 passed at8816ea7;agent.pyat 100% (715 before the review fixes)test_row_NN_*intests/keycardai/oauth/test_agent.pytest_agent_integration.py, against a fake agent (Starlette + uvicorn on a real Unix socket); nokeycardbinary, no networkjust check(ruff) at8816ea7just typecheck(ty),cz check, and Python 3.10/3.12: passed at81a84ef, not yet re-run after the review fixes (only 3.11 was run locally)keycard agentdaemon and zone at8816ea7(keycardlabs/e2e-sdk-localdevresults/python; the report at that SHA is not yet committed there)🤖 Generated with Claude Code