Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 76 additions & 1 deletion packages/oauth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,75 @@ If the server's metadata has no `userinfo_endpoint`, `userinfo()` raises
`ConfigError` without making a request. An expired or revoked token raises
`InvalidTokenError`.

### Resource Tokens from the Local Keycard Agent

An application running beside the Keycard CLI can get an access token for a
third-party resource without holding an application credential.
`AgentTokenSource` asks the local Keycard agent over its Unix socket, and the
agent mints the token with the developer's zone session once a human approves
the request.

```python
import httpx
from keycardai.oauth import AgentTokenSource, ResourceAuth

source = AgentTokenSource(workload="my-agent")

token = await source.resource_token("https://api.example.com", ["read"])

# Or attach a token to every request an httpx.AsyncClient sends:
auth = ResourceAuth(source, "https://api.example.com", ["read"])
async with httpx.AsyncClient(auth=auth) as client:
response = await client.get("https://api.example.com/items")
```

The socket is the first of:

1. `socket=`, when passed.
2. `KEYCARD_SOCKET`, which `keycard run` sets for the process it starts.
3. The `keycard agent` daemon's default socket, located the way the CLI
locates it from `KEYCARD_AGENT_DIR`, `XDG_RUNTIME_DIR`, `XDG_STATE_HOME`,
`KEYCARD_HOME` and `HOME` (on macOS, `~/.local/state/keycard/run/agent.sock`).
The daemon serves several zones, so pass `org=` and `zone=`.

Variables are read from `env=` (default `os.environ`) on every call, never
from `keycard.toml`. Construction does no I/O.

The first request for a resource and scope set blocks until someone answers
the approval prompt, so no timeout is applied; bound the call with
`asyncio.wait_for`, or `asyncio.timeout` on Python 3.11+. The SDK does not cache tokens: each call is one request to
the agent, which caches them itself.

Options, all keyword-only:

| Option | Purpose |
|--------|---------|
| `socket` | Socket path; see above |
| `env` | Where the socket variables are read from |
| `workload` | Name shown in the approval prompt; self-declared |
| `app_id` | Identifier of the Keycard application the caller says it acts for, as set on the application; self-declared and matched exactly |
| `org`, `zone` | The tenant, for the multi-zone daemon; `keycard run` ignores them |
| `clock` | Wall-clock source for `expires_in` |

`TokenResponse.expires_in` is `None` when the agent reports no expiry, and
`scope` is the granted scopes the agent reports, or `None` when it reports
none; it is never filled in from the request.

A refusal raises `AgentError`, whose `code` is the agent's Connect error code
(`AgentCode`). Branch on the predicates rather than the message:

| Predicate | Code | What to do |
|-----------|------|------------|
| `is_declined` | `permission_denied` | Don't retry automatically: declined, prompt expired or failed, the authorization server refused, or no session for `org`/`zone` |
| `is_rate_limited` | `resource_exhausted` | Back off |
| `is_prompter_unavailable` | `failed_precondition` | No prompt on this host; use another credential |
| `is_authorization_required` | `unauthenticated` | Sign in or authorize the resource; the message names the command |
| `is_application_not_found` | `not_found` | The declared `app_id` names no application in the zone |
| `is_unavailable` | `unavailable` | Transient; retry with backoff |

An unreachable socket raises `NetworkError` naming the socket and how it was
chosen, and a 200 response the SDK cannot use raises `AgentResponseError`.

## Error Handling

The SDK provides a structured exception hierarchy with retry guidance.
Expand All @@ -536,7 +605,9 @@ OAuthError (base)
│ └── TokenExchangeError # RFC 8693 specific errors
├── NetworkError # Connection/transport failures
├── ConfigError # Client misconfiguration
└── AuthenticationError # Authentication failures
├── AuthenticationError # Authentication failures
├── AgentError # Refusals from the local Keycard agent
└── AgentResponseError # Unusable responses from the local Keycard agent
```

### Retryable vs Non-Retryable Errors
Expand All @@ -553,6 +624,9 @@ operation unchanged could succeed.
| `NetworkError` | Yes | Always: transport faults are transient, permanent failures surface as protocol or HTTP errors |
| `ConfigError` | No | Invalid configuration (requires code fix) |
| `AuthenticationError` | No | Invalid credentials |
| `AgentError` | Yes | Code `resource_exhausted` or `unavailable` |
| `AgentError` | No | Any other code |
| `AgentResponseError` | No | Always |

If you use the older `retriable` attribute: it is a legacy constructor flag,
while `retryable` is the classification derived from the failure (the OAuth
Expand Down Expand Up @@ -656,6 +730,7 @@ Working examples are available in the `examples/` directory:

- **[discover_server_metadata](examples/discover_server_metadata/)** - RFC 8414 server metadata discovery
- **[dynamic_client_registration](examples/dynamic_client_registration/)** - RFC 7591 client registration
- **[agent_token_source](examples/agent_token_source/)** - Resource tokens from the local Keycard agent

Run examples:

Expand Down
1 change: 1 addition & 0 deletions packages/oauth/examples/agent_token_source/.python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.12
51 changes: 51 additions & 0 deletions packages/oauth/examples/agent_token_source/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Agent Token Source Example

Gets an access token for a third-party resource from the local Keycard agent,
holding no application credential, then optionally calls the resource with it.

## What it does

1. Asks the agent for a token for `RESOURCE` with `AgentTokenSource`. The
first request for a resource and scope set opens an approval prompt; the
agent remembers the approval and caches the token.
2. If `CALL_URL` is set, sends a GET to it through `ResourceAuth`, which
attaches `Authorization: Bearer <token>`.

A refusal is reported by the predicate it matches: declined, authorization
required, no prompt available on this host, or an unknown application.

## Usage

The example depends on `keycardai-oauth` from this source tree (a path
dependency on `../../`), so it runs against unreleased code.

Under `keycard run`, which starts a per-session agent and sets
`KEYCARD_SOCKET` for the process:

```bash
uv sync
RESOURCE=https://api.example.com keycard run -- uv run python main.py
```

Against the `keycard agent` daemon, which serves every signed-in zone and so
needs the tenant named. With `KEYCARD_SOCKET` unset the source finds the
daemon's default socket the way the CLI does:

```bash
keycard agent start
export KEYCARD_ORG=<org id> KEYCARD_ZONE=<zone id>
RESOURCE=https://api.example.com uv run python main.py
```

Optional:

- `SCOPES`: comma-separated scopes to request
- `KEYCARD_APP_ID`: identifier of a Keycard application in the zone, as set on
the application; the prompt shows it marked self-asserted
- `CALL_URL`: a URL on the resource to GET with the token attached

## Requirements

- Python 3.10+
- The Keycard CLI, signed in to a zone where `RESOURCE` is registered
- A host that can show the approval prompt
96 changes: 96 additions & 0 deletions packages/oauth/examples/agent_token_source/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""Get a resource token from the local Keycard agent and call the resource with it.

Keycard setup this example needs:

1. The Keycard CLI, signed in to a zone (`keycard auth signin`), where the
resource named by RESOURCE is registered and the developer may obtain
tokens for it. A third-party provider's resource may first need a one-time
interactive authorization; the agent's error message names the command.
2. A running agent, either:
- `keycard run -- uv run python main.py`, which starts a per-session agent
for this process and sets KEYCARD_SOCKET, or
- `keycard agent start`, the long-running multi-zone daemon. With
KEYCARD_SOCKET unset the example finds the daemon's default socket, and
KEYCARD_ORG and KEYCARD_ZONE must name the org and zone ids to mint in.
3. A host that can show the approval prompt. The first request for a
resource and scope set waits until a human approves or declines it.
4. Optionally, a Keycard application in the zone whose identifier (as set on
the application, not its public id) is given as KEYCARD_APP_ID. The prompt
shows it marked self-asserted.

Environment:
RESOURCE the resource indicator to request a token for (required)
SCOPES comma-separated scopes to request
KEYCARD_ORG org id, for the multi-zone daemon
KEYCARD_ZONE zone id, for the multi-zone daemon
KEYCARD_APP_ID the application this example says it acts for
CALL_URL a URL on the resource to GET with the token attached
"""

import asyncio
import os
import sys

import httpx

from keycardai.oauth import (
AgentError,
AgentTokenSource,
ConfigError,
NetworkError,
ResourceAuth,
is_application_not_found,
is_authorization_required,
is_declined,
is_prompter_unavailable,
)


async def main() -> int:
resource = os.environ.get("RESOURCE")
if not resource:
print("set RESOURCE to the resource indicator to request a token for")
return 2
scopes = [s for s in os.environ.get("SCOPES", "").split(",") if s]

source = AgentTokenSource(
workload="agent-token-source-example",
app_id=os.environ.get("KEYCARD_APP_ID", ""),
org=os.environ.get("KEYCARD_ORG", ""),
zone=os.environ.get("KEYCARD_ZONE", ""),
)

try:
token = await source.resource_token(resource, scopes)
except (ConfigError, NetworkError) as err:
print(err)
return 1
except AgentError as err:
if is_declined(err):
print(f"declined: {err.message}")
elif is_authorization_required(err):
print(f"authorization required: {err.message}")
elif is_prompter_unavailable(err):
print("this host cannot show an approval prompt")
elif is_application_not_found(err):
print("KEYCARD_APP_ID names no application in this zone")
else:
print(err)
return 1

expiry = "no expiry" if token.expires_in is None else f"expires in {token.expires_in}s"
print(f"token for {resource}, {expiry}, granted scopes {token.scope or 'unknown'}")

if call := os.environ.get("CALL_URL"):
# The agent caches the token, so this second request is answered
# without another prompt. The client's timeout bounds the GET, not
# the wait for the token.
auth = ResourceAuth(source, resource, scopes)
async with httpx.AsyncClient(auth=auth) as client:
response = await client.get(call)
print(f"GET {call} -> {response.status_code}")
return 0


if __name__ == "__main__":
sys.exit(asyncio.run(main()))
13 changes: 13 additions & 0 deletions packages/oauth/examples/agent_token_source/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[project]
name = "agent-token-source"
version = "0.1.0"
description = "Resource tokens from the local Keycard agent"
readme = "README.md"
requires-python = ">=3.10"
dependencies = [
"keycardai-oauth",
"httpx>=0.28.1",
]

[tool.uv.sources]
keycardai-oauth = { path = "../../", editable = true }
Loading
Loading