Skip to content

feat(keycardai-oauth): add a resource token source backed by the local Keycard agent - #382

Closed
benburkert wants to merge 3 commits into
mainfrom
feat/agent-token-source
Closed

benburkert wants to merge 3 commits into
mainfrom
feat/agent-token-source

Conversation

@benburkert

Copy link
Copy Markdown

The gap

A Python application that needs to call a third-party resource has no way to get a credential for it from keycardai-oauth. Every flow here either authenticates the client to the authorization server or exchanges an inbound user token. Nothing answers "give me a token for resource X", which is what an application running beside the Keycard CLI needs, and why it otherwise still carries a client secret.

# before: the app holds a client secret and runs its own exchange
# after:
source = AgentTokenSource(workload="my-app")
async with httpx.AsyncClient(auth=ResourceAuth(source, "https://api.example.com")) as client:
    await client.get("https://api.example.com/things")

What this adds

The Python port of keycardai/go-sdk#51.

ResourceTokenSource protocol: async resource_token(resource, *scopes) -> TokenResponse
AgentTokenSource mints over KEYCARD_SOCKET via the agent's IssueToken procedure; socket, workload, app_id, org, zone
ResourceAuth httpx.Auth that attaches a resource token to every request of an httpx.AsyncClient
AgentError, AgentCode, is_declined, is_rate_limited, is_prompter_unavailable, is_authorization_required, is_application_not_found, is_unavailable the Connect code, read as the outcomes a caller should branch on

Plus two examples: packages/oauth/examples/agent_token_source (a plain script) and packages/fastmcp/examples/agent_resource_access (a FastMCP server whose tools reach a resource through the agent and never put the token in tool output, which reaches the model).

No new dependencies; the Unix socket is reached with httpx.AsyncHTTPTransport(uds=...).

CLI compatibility

  • Requires a CLI with keycardlabs/cli#1246, which named the procedure /keycard.agent.v1.AgentService/IssueToken. Connect addresses a procedure by URL path, so a CLI predating it answers 404.
  • app_id relies on keycardlabs/cli#1255–#1257, all merged. It is sent as appId only when set. A CLI without those PRs drops the unknown field. With them, the server labels the id self-asserted in the approval prompt and audit log, resolves it to the application's name in the session's zone, and forwards it to the authorization server.
  • The keycard_declared_app_id token claim waits on keycardlabs/svc-sts#739, still open. Until it deploys, a mint that declares an id succeeds with no claim. The agent_resource_access example prints both keycard_declared_app_id and keycard_app_id so the difference is visible.

Decisions rather than details

These follow go-sdk#51; see its description for the longer reasoning.

  • Connect's unary JSON encoding is spoken by hand. The CLI's generated stubs are published nowhere, and the encoding needs only httpx.
  • The resource indicator is sent exactly as the caller wrote it, and ResourceAuth binds to one resource rather than deriving one from each request URL. Normalizing here would be a second opinion about what was requested.
  • Tokens are cached per (resource, scopes) until 30s before expiry, and concurrent first requests for the same key share one mint behind a per-key asyncio.Lock. A credential with no expiry (a static API key, keycardlabs/cli#1198) is cached indefinitely. The agent remembers the human's approval, not the token, so without a client-side cache every request costs an authorization server round trip.
  • No timeout on the mint. The first request may block for as long as a human takes to answer the prompt; callers bound it with asyncio.timeout.
  • A token carrying a control character is refused, since it may be an opaque third-party secret headed for an Authorization header.
  • ResourceAuth.sync_auth_flow raises rather than inheriting httpx's default, which would pass the request through unauthenticated.
  • expiresAt is parsed by hand: protojson emits up to nine fractional digits, which datetime.fromisoformat rejects before Python 3.11.

Verified end to end

Beyond the unit tests (test_agent.py, which drive the source through a mock transport), the FastMCP example was driven against a live Keycard daemon and a live authorization server on 2026-10-14: k3d localdev, a CLI built from keycardlabs/cli#1256, ITL_PROMPT=native. A separate driver reached the server only through MCP tool calls over stdio, and a resource server verified the bearer against the zone's JWKS rather than decoding it.

Scenario Result
Mint, cached repeat compact JWS, iss is the zone issuer, aud includes the resource; the first call writes exactly one token_issue audit record and the repeat writes none
Spend at the resource 200, signature verified against the zone JWKS
Unknown app id not_found, with no prompt
Human declines with a new scope (so a new approval key), permission_denied

That CLI build predates #1257, so the run covers the local app-id lookup but not the forwarding, and the keycard_declared_app_id claim has not been seen on a real token.

Open for review

  • TokenResponse.scope echoes what was requested, not what was granted, the same open question as go-sdk#51. IssueToken returns only a token and an expiry; ask for no scopes and the field is None while the token carries the session's full set.
  • is_application_not_found's docstring lags go-sdk. go-sdk updated its equivalent to say that not_found also covers an id the authorization server refuses at the mint (keycardlabs/cli#1257). The code is the same here; only the docstring is out of date.

Draft

Draft for review of the API shape, and until svc-sts#739 merges so the app_id claim isn't documented ahead of the server that stamps it. Locally: ruff check, cz check, ty check, and the oauth (603 passed, 89% coverage) and fastmcp (94 passed, 85%) suites pass.

🤖 Generated with Claude Code

benburkert and others added 3 commits October 29, 2026 11:57
…l Keycard agent

AgentTokenSource asks the Keycard CLI over KEYCARD_SOCKET for an access
token for a named third-party resource, so an application running beside
the CLI needs no client secret of its own. The CLI mints the token once a
human approves the request, and remembers the approval rather than the
token, so tokens are cached per source until 30 seconds before they
expire, and concurrent first requests share one mint.

It ports keycardai/go-sdk#51: the Connect unary JSON call to
AgentService/IssueToken, the optional app_id the CLI resolves to an
application name, AgentError with predicates for each refusal code, and
ResourceAuth to attach the token to an httpx.AsyncClient's requests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…e through the local Keycard agent

agent_resource_access is the shape for a FastMCP server running on a
developer's machine beside the Keycard CLI: it holds no client secret and
has no inbound user token to exchange, so its tools ask the CLI for a
resource token through keycardai-oauth's AgentTokenSource, and a human
approves each new resource. The resource and the URL the token is sent to
are configuration rather than tool arguments, and the token itself never
appears in tool output, which reaches the model.

The smoke test skips when the installed keycardai-oauth predates
AgentTokenSource, which is what the sibling-floors job installs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…ion ids in the agent_resource_access example

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

Copy link
Copy Markdown

Caution

Review the following alerts detected in dependencies.

According to your organization's Security Policy, you must resolve all "Block" alerts before proceeding. Learn more about Socket for GitHub.

Priority Alert  (click "▶" to expand/collapse) Action
Critical priority
Critical CVE: pypi certifi bundles emSign root CAs with compromised intermediate CA keys

CVE: GHSA-6q48-6c7w-9gw2 certifi bundles emSign root CAs with compromised intermediate CA keys (CRITICAL)

Affected versions: >= 2019.03.09 < 2026.10.18

Patched version: 2026.10.18

From: packages/oauth/examples/agent_token_source/uv.lock → pypi/httpx@0.28.1 → pypi/certifi@2026.7.22

ℹ Read more on: This package | This alert | What is a critical CVE?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: Remove or replace dependencies that include known critical CVEs. Consumers can use dependency overrides or npm audit fix --force to remove vulnerable dependencies.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore pypi/certifi@2026.7.22. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Block

View full report

@github-actions

Copy link
Copy Markdown
Contributor

Release preview

keycardai-oauth 0.33.2 → 0.34.0 (minor)

  • feat(keycardai-oauth): add a resource token source backed by the local Keycard agent
  • AgentTokenSource asks the Keycard CLI over KEYCARD_SOCKET for an access
    token for a named third-party resource, so an application running beside
    the CLI needs no client secret of its own. The CLI mints the token once a
    human approves the request, and remembers the approval rather than the
    token, so tokens are cached per source until 30 seconds before they
    expire, and concurrent first requests share one mint.
  • It ports feat(oauth): add a resource token source backed by the local Keycard agent go-sdk#51: the Connect unary JSON call to
    AgentService/IssueToken, the optional app_id the CLI resolves to an
    application name, AgentError with predicates for each refusal code, and
    ResourceAuth to attach the token to an httpx.AsyncClient's requests.

No other package releases.


This comment was automatically generated by the release preview workflow.

@benburkert

Copy link
Copy Markdown
Author

Superseded by #435, generated from the merged Local Agent Token Source spec (keycard-sdk-spec 21b11f0). Unlike this draft it resolves the daemon's default socket (integration rows 7 and 8) and leaves caching to the agent.

@benburkert benburkert closed this Nov 17, 2026
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