Metadata-Version: 2.5
Name: brutor-agent-auth
Version: 0.2.0
Summary: Workload identity for agents calling Brutor Agent Control: a short-lived token from the platform the agent runs on, bound to a key (DPoP) or presented over mutual TLS
Project-URL: Documentation, https://docs.brutor.ai/build-an-agent/identity/sdk-python/
Project-URL: Source, https://github.com/brutor-ai/brutor-agent-control/tree/main/sdk/python/brutor-agent-auth
Author: Brutor AI Ltd.
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: agents,dpop,mtls,oauth,spiffe,token exchange,workload identity
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.11
Provides-Extra: aws
Requires-Dist: botocore<2,>=1.34; extra == 'aws'
Provides-Extra: pop
Requires-Dist: cryptography<51,>=42; extra == 'pop'
Provides-Extra: spiffe
Requires-Dist: spiffe<0.5,>=0.4; extra == 'spiffe'
Description-Content-Type: text/markdown

# Brutor Agent Control — Agent Auth for Python

Workload identity for agents that call Brutor Agent Control. The agent proves
who it is with the credential of the platform it runs on, so no API key is
stored in it. It can also prove that it holds a private key on every request:
a token bound to a key pair (DPoP, RFC 9449), or its SPIFFE X.509-SVID
presented over mutual TLS.

**Edition:** Community (works with both editions of Brutor Agent Control)

## What it is

`brutor-agent-auth` is the Python workload-identity helper for Brutor Agent Control (the
`brutor.auth` namespace package). Documentation: https://docs.brutor.ai

## Requirements

Python 3.11 or later (CI runs 3.11 to 3.15). The package itself has no dependency: HTTP is the
standard library's. The adapters for httpx and requests use the library you already have; neither
is a dependency. The extras below add `py-spiffe`, `botocore` and `cryptography`.

## Install

```bash
pip install brutor-agent-auth            # file and GitHub Actions; GCP and Entra
pip install 'brutor-agent-auth[spiffe]'  # adds the SPIFFE Workload API (py-spiffe), and mutual TLS
pip install 'brutor-agent-auth[aws]'     # adds AWS IAM (botocore)
pip install 'brutor-agent-auth[pop]'     # adds DPoP proof of possession (cryptography)
```

## Usage

```python
from brutor.auth import WorkloadAuth, WorkloadTokenError

auth = WorkloadAuth(audience="brutor")  # the issuer's workload audience

response = httpx.post(
    "https://gateway.example.com/v1/proxy/llm/chat/completions",
    headers=auth.headers(),  # Authorization, X-Tenant-ID, X-Resource-Group
    json={...},
    timeout=60,  # your own call's timeout: always set one
)
if response.status_code == 401:
    auth.invalidate()  # the next call fetches a new token
```

`auth.token()` returns a token valid now and refreshes it as needed;
`auth.expires_at` is its expiry in epoch seconds. For a one-liner,
`workload_token(**kwargs)` keeps one `WorkloadAuth` per distinct set of
arguments for the whole process.

## Sources

| `source` | Where the token comes from |
|---|---|
| `spiffe` | a JWT-SVID from the SPIFFE Workload API (`SPIFFE_ENDPOINT_SOCKET`) |
| `file` | a projected token file, read again on every refresh (`BRUTOR_WORKLOAD_TOKEN_FILE`) |
| `github_actions` | the job's OIDC token (`permissions: id-token: write`) |
| `gcp` | the metadata server's identity token |
| `entra` | the managed identity's access token (App Service and Functions, else the instance metadata service), for `entra_resource` |
| `aws` | a signed `sts:GetCallerIdentity` request from botocore's default credential chain, for the issuer named by `aws_server_id` |

With no `source`, the SDK reads `BRUTOR_WORKLOAD_SOURCE`, then detects, from
the environment only, SPIFFE, then a token file, then GitHub Actions. It never
probes a metadata server: `gcp`, `entra` and `aws` are always chosen
explicitly.

## The token exchange

`entra` and `aws` credentials are accepted only by the gateway's token
exchange (`POST /v1/auth/token`), so for those sources the SDK always trades
them for a short-lived Brutor token. For the other sources, `exchange=True`
does the same. The exchange needs `gateway_url` (`BRUTOR_GATEWAY_URL`); a
refusal raises `WorkloadTokenError` with the gateway's `brutor_code`.

## Proof of possession: DPoP

A bearer token works for whoever holds it. With `dpop=True` the token is bound
to a key pair the SDK generates in memory, and every request carries a proof
signed with that key, so a copied token is useless without the key.

```python
auth = WorkloadAuth(audience="brutor", dpop=True, gateway_url="https://gateway.example.com")

with httpx.Client(auth=auth.httpx_auth()) as client:  # or AsyncClient
    client.post("https://gateway.example.com/v1/proxy/llm/chat/completions", json={...})

session = requests.Session()
session.auth = auth.requests_auth()
session.get("https://gateway.example.com/v1/proxy/llm/models")
```

What happens:

- `dpop=True` always uses the token exchange (`exchange=False` with `dpop=True`
  raises `ValueError`). The exchange request carries a DPoP proof, and the
  gateway issues a token bound to the key (`token_type` `DPoP`, `cnf.jkt` the
  key's RFC 7638 thumbprint). The SDK checks both and refuses an unbound token.
- Every request then sends `Authorization: DPoP <token>` and a `DPoP` header: a
  proof (`typ` `dpop+jwt`, ES256, the public key as `jwk`) for this request's
  method and URL, with a new `jti`, the current time as `iat`, `ath` (the hash
  of the token) and the gateway's latest nonce.
- **One key pair per `WorkloadAuth`**, ES256 (P-256). It lives in memory only: it
  is never written to disk, never logged, and the object cannot be pickled or
  copied. `invalidate()` drops the token **and** the key pair; the next request
  exchanges again with a new key. `auth.dpop_jkt` is the key's thumbprint.

### The URL in each proof (`htu`)

Each proof names the URL it is for: the gateway's **public URL** followed by
the request's path, without query or fragment, normalised as RFC 3986 does
(scheme and host in lower case, the default port removed, percent-escapes of
unreserved characters decoded). The public URL is `public_url`
(`BRUTOR_GATEWAY_PUBLIC_URL`), by default `gateway_url`. Set it when the agent
reaches the gateway at another address than the one the gateway calls its own:
for example, `gateway_url="http://core:8100"` inside a Compose network while
the gateway's public URL is `https://gateway.example.com`. On the gateway's
mutual-TLS listener, use that listener's public URL.

When `gateway_url` has a path (a gateway behind a reverse proxy at
`https://proxy.example.com/brutor`), the path of each request below it is what
follows the public URL.

The SDK signs requests to the gateway only: a URL on another origin, or outside
the gateway's path, raises `ValueError` before anything is sent, so the token
never leaves for another host. The token exchange (`/v1/auth/token`) is the
SDK's own request and is never sent through the adapters.

### Server nonces

The gateway requires a nonce of its own in every proof. It sends the current
one in a `DPoP-Nonce` header on every answer, and the SDK keeps the latest per
gateway origin and per audience (the token exchange and the governed routes
have separate nonces). The first request has none yet, so the gateway answers
`use_dpop_nonce` (400 at the token exchange, 401 with
`WWW-Authenticate: DPoP error="use_dpop_nonce"` elsewhere) with a nonce. The
SDK then sends the request **once more**, with that nonce and a new proof; the
caller never sees the first answer. Nonces change every few minutes, so this
round trip happens again now and then.

That one retry is the only one: a second `use_dpop_nonce` in a row raises
`WorkloadTokenError` (`error` `use_dpop_nonce`, `brutor_code` the gateway's
reason). No other answer is retried; every other refusal is returned to the
caller as it is.

**Request bodies that are streams.** A body that is a generator, an iterator
or (with httpx) a multipart upload is read as it is sent and cannot be sent
twice. When such a request gets `use_dpop_nonce`, the adapter raises
`WorkloadTokenError` instead of re-sending a consumed stream; the nonce of that
answer is kept, so sending the request again succeeds at once. Bodies in
memory (bytes, text, JSON, forms) are re-sent; with requests, a seekable file is
rewound to where it started.

**Redirects.** The requests adapter strips `Authorization` and `DPoP` from a
redirected request: credentials never follow a redirect. httpx does not follow
redirects unless asked (`follow_redirects`); a proof is valid for one URL only,
so leave it off for requests to the gateway.

### Sending requests yourself

With another HTTP client, build the headers per request and pass every answer
back with `observe`, which keeps the nonce and says whether to send once more:

```python
for attempt in range(2):
    headers = auth.headers("POST", url)  # Authorization: DPoP …, DPoP: <proof>, X-Tenant-ID …
    response = client.post(url, headers=headers, json=body)
    if not auth.observe(url, response.status_code, response.headers, response.content):
        break
```

`auth.dpop_proof(method, url)` returns a proof on its own. With `dpop=True`,
`headers()` needs the method and the URL.

## Mutual TLS with the X.509-SVID

With `mtls=True` the agent presents its SPIFFE X.509-SVID on every connection,
from the SPIFFE Workload API (`spiffe_socket`, `SPIFFE_ENDPOINT_SOCKET`; the
`spiffe` extra). The certificate is the credential: without the token exchange
and without DPoP, `headers()` sends no `Authorization` header at all.

```python
auth = WorkloadAuth(mtls=True, gateway_spiffe_id="spiffe://example.org/brutor/core")

with httpx.Client(verify=auth.ssl_context(), auth=auth.httpx_auth()) as client:
    client.get("https://gateway.example.com:8443/v1/proxy/llm/models")

session = requests.Session()
session.mount("https://", auth.requests_adapter())
session.auth = auth.requests_auth()
```

- `auth.ssl_context()` is one `ssl.SSLContext` for the life of the object:
  TLS 1.3 at least, the server always verified, the host name always checked.
  When the SVID or the trust bundles rotate, the SDK builds new TLS material,
  and the next connection made with the same context presents the new SVID and
  trusts the new bundles; an authority removed from the bundles is no longer
  trusted. Connections already open keep their handshake. The context's trust
  and certificate cannot be changed or weakened: loading other CAs or turning
  verification off raises.
- The SVID and its key are written to a private directory (mode 0700, files
  0600) because Python's `ssl` loads a client certificate only from files. The
  key on disk is encrypted under a random password that exists only in memory.
  The files are replaced atomically on rotation and removed by `close()`, when
  the object is garbage collected, and at interpreter exit. `WorkloadAuth` is a
  context manager.
- **Verifying the gateway.** With `gateway_ca_file` (`BRUTOR_GATEWAY_CA_FILE`),
  the gateway's certificate must chain to that file. Without it, it must chain
  to the trust bundles of the Workload API: the agent's own trust domain and
  every federated one, kept current as they change. A gateway whose server
  certificate is itself a SPIRE X.509-SVID then rotates with nothing to copy to
  agents. Either way the host name of the URL is checked.
- `gateway_spiffe_id` (`BRUTOR_GATEWAY_SPIFFE_ID`) adds an exact check: the
  gateway's certificate must carry that SPIFFE ID as its one URI SAN. The check
  runs as the handshake completes, before any byte of the request is sent, and
  a mismatch closes the connection with `ssl.SSLCertVerificationError`. It
  applies to every client that uses the context, synchronous or asyncio.
- With the token exchange as well, the exchange runs over the same mutual-TLS
  connection; `gateway_url` must then be the gateway's https mTLS listener.

DPoP and mutual TLS combine: `WorkloadAuth(dpop=True, mtls=True, ...)` proves
the key on every request over a connection that presents the SVID.

## Configuration

Every argument falls back to an environment variable; an explicit empty string
means "none".

| Argument | Variable |
|---|---|
| `source` | `BRUTOR_WORKLOAD_SOURCE` |
| `gateway_url` | `BRUTOR_GATEWAY_URL` |
| `tenant_id` | `BRUTOR_TENANT_ID` (sent as `X-Tenant-ID`) |
| `resource_group` | `BRUTOR_RESOURCE_GROUP` (sent as `X-Resource-Group`) |
| `token_file` | `BRUTOR_WORKLOAD_TOKEN_FILE` |
| `spiffe_socket` | `SPIFFE_ENDPOINT_SOCKET` |
| `entra_resource` | `BRUTOR_ENTRA_RESOURCE` |
| `aws_server_id` | `BRUTOR_AWS_SERVER_ID` (sent signed as `X-Brutor-Server-Id`) |
| `aws_region` | `AWS_REGION` (unset: the global STS endpoint) |
| `aws_sts_fips` | `BRUTOR_AWS_STS_FIPS_ENABLED` (`true` or `false`; unset: false) |
| `public_url` | `BRUTOR_GATEWAY_PUBLIC_URL` (read with `dpop=True` only; unset: `gateway_url`) |
| `gateway_ca_file` | `BRUTOR_GATEWAY_CA_FILE` (read with `mtls=True` only; unset: the Workload API's trust bundles) |
| `gateway_spiffe_id` | `BRUTOR_GATEWAY_SPIFFE_ID` (read with `mtls=True` only) |
| `timeout` | `BRUTOR_WORKLOAD_TIMEOUT_SECS` (seconds; unset: 10) |

`dpop` and `mtls` (default `False`) are arguments only. `public_url` without
`dpop`, or `gateway_ca_file` or `gateway_spiffe_id` without `mtls`, raises
`ValueError`.

`timeout` is a deadline for each request the SDK makes (the platform's token endpoint, the
token exchange): the connection, the answer and its body together, so a server that answers
slowly or a byte at a time cannot hold a call longer; it bounds the Workload API's first answer
too. A request that runs out of time raises
`WorkloadTokenError` ("did not answer within ..."). Anything but a positive, finite number of
seconds is refused when `WorkloadAuth` is made. Your own calls to the gateway are yours: give
each a timeout too, as in the example above.

The `aws` request is signed for the region's STS endpoint: `sts.<region>.amazonaws.com`,
`sts.<region>.amazonaws.com.cn` in China, `sts.amazonaws.com` with no region. With
`aws_sts_fips`, it is signed for the region's FIPS endpoint instead:
`sts-fips.<region>.amazonaws.com` in the US regions, and the regional endpoint in
GovCloud, which is FIPS already. AWS has no FIPS STS endpoint in any other region, in
China or without a region: there `WorkloadAuth` refuses the setting when it is made.
A gateway set to accept FIPS endpoints only (`BRUTOR_AWS_STS_FIPS_ENABLED` of the Core
Gateway) refuses a request signed for any other.

## Refresh and failure

A token is reused until half its lifetime has passed or 60 seconds remain,
whichever comes first. One refresh runs at a time per `WorkloadAuth`. If a
refresh fails while the current token still has 30 seconds or more, the
current token is returned and the next call tries again; otherwise
`WorkloadTokenError` is raised. An expired token is never returned.

The SDK reads the `exp` of each JWT it handles but verifies no signature: the
gateway does that.

## Errors

`WorkloadTokenError` carries `error` (the gateway's code, for example
`invalid_dpop_proof` or `use_dpop_nonce`), `brutor_code` (its reason, for
example `dpop_htu` or `dpop_nonce_stale`) and `status` (the HTTP status) when
the gateway refused. Arguments that cannot go together raise `ValueError`.

## What is never written anywhere

No token, DPoP proof, private key, signed request or AWS credential appears in
a log record, a `repr` or an error message. `repr(auth)` shows the source, the
subject when known, the expiry and whether DPoP and mutual TLS are on.

## Development

From `sdk/python/brutor-agent-auth` in the Brutor Agent Control repository (the tools are pinned in
`requirements-dev.txt`; the `sdk-python.yml` workflow runs these gates):

```bash
python -m pip install -r requirements-dev.txt -e '.[spiffe,aws,pop]'
ruff check . && ruff format --check .
mypy --strict src scripts
python scripts/env_registry.py --check   # env_registry.json equals the SDK's registry
python -m pytest                          # fails below 95% coverage
```

The release build (`scripts/build_release.py`) is reproducible: CI builds the sdist and the wheel
twice and compares them byte for byte.

## Documentation

https://docs.brutor.ai/build-an-agent/identity/sdk-python/

## Security

See SECURITY.md at the repository root.

## License

Apache License, Version 2.0. See `LICENSE` and `NOTICE`.
