> ## Documentation Index
> Fetch the complete documentation index at: https://docs.algovoi.co.uk/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent Session Authentication

> Exchange an ATB ZKP certificate or a federation token for a short lived HMAC session JWT with an embedded spend cap, used across all payment routes.

Agent session authentication lets agentic payment workflows authenticate once and operate within a declared spend cap for the duration of a session. Two credential paths are supported:

* **ATB ZKP certificate** — the agent presents a Falcon-1024 signed [ATB Pass Certificate](/atb-reputation-credential) (Phase 2, Bulletproofs range proof). Open to all tenants.
* **Federation token** — the agent presents a pre-composed cross-issuer federation token. Available under the [AlgoVoi Commercial License](mailto:hello@algovoi.co.uk).

## Why it exists

Standard API key authentication is stateless: every request to `/x402`, `/mpp`, `/ap2`, or `/a2a` presents the full API key. For high-frequency agentic workflows — where an agent may make dozens of payment decisions per session — this has two problems:

1. **Repeated key exposure** — the API key travels on every request.
2. **No session-level spend governance** — there is no in-gateway mechanism to cap total spend for a single agentic run, independent of the tenant-level volume caps.

Agent session tokens solve both. The agent presents its API key and ATB ZKP cert once, receives a short-lived signed token, and uses that token for the remainder of the session. The token embeds a spend cap enforced in-process on every payment route.

## Prerequisites

* An active AlgoVoi API key (`X-Tenant-Id` + `Authorization: Bearer <api_key>`)
* One of:
  * A valid ATB ZKP certificate — issued by [`agent-trust-bench.algovoi.co.uk`](https://agent-trust-bench.algovoi.co.uk) with `passed=true` and a Bulletproofs range proof. See [ATB Pass Certificate](/atb-reputation-credential) for issuance.
  * A federation token — issued by the AlgoVoi federation validator. [Commercial License](mailto:hello@algovoi.co.uk) required.

## Authentication flow

```
1.  Agent → POST /auth/token
        Headers: X-Tenant-Id, Authorization: Bearer <api_key>
        Body:    { atb_zk_credential OR federation_token, spend_cap_usd?, ttl_secs? }

2.  Gateway verifies (path A — ATB ZKP cert):
        - API key valid and tenant active
        - ATB ZKP cert: Falcon-1024 signature + Bulletproofs range proof
        - Score ≥ ATB_ZKP_THRESHOLD (default 0.700)

    Gateway verifies (path B — federation token):
        - API key valid and tenant active
        - Federation token: HMAC-SHA256 signature + expiry
        - Issued by a trusted federation validator

3.  Gateway issues:
        - HMAC-signed session JWT (typ=agent_session)
        - Spend cap initialised in-process (in USD, converted to micro-USD)

4.  Agent → any payment route
        Headers: Authorization: Bearer <session_token>
        (X-Tenant-Id not required — tenant_id is in JWT claims)

5.  Gateway checks spend cap before each payment.
        Exceeded cap → 402 with detail "agent_spend_cap_exceeded"
```

## POST /auth/token

Exchange an ATB ZKP certificate for a session token.

### Request

```http theme={null}
POST /auth/token
X-Tenant-Id: <your-tenant-id>
Authorization: Bearer <api_key>
Content-Type: application/json
```

```json theme={null}
{
  "atb_zk_credential": "<base64url-encoded ZKP cert envelope>",
  "spend_cap_usd": 50.0,
  "ttl_secs": 3600
}
```

<Warning>
  **Commercial License required for `federation_token`.** The `federation_token` path requires the `algovoi-federation-validator` service, which is available under the **AlgoVoi Commercial License v1.0**. Evaluation use (non-production testing) is free. Production or commercial deployment requires a written licence agreement. Contact [hello@algovoi.co.uk](mailto:hello@algovoi.co.uk) to enquire. The `atb_zk_credential` path has no additional licensing requirement beyond your standard AlgoVoi account.
</Warning>

Or, with a federation token (Commercial License):

```json theme={null}
{
  "federation_token": "<base64url-encoded federation token>",
  "spend_cap_usd": 50.0,
  "ttl_secs": 3600
}
```

| Field               | Type    | Required | Description                                                                                                           |
| ------------------- | ------- | -------- | --------------------------------------------------------------------------------------------------------------------- |
| `atb_zk_credential` | string  | One of   | Base64url-encoded ATB ZKP Phase 2 cert (`X-ATB-ZK-Credential` value from bench).                                      |
| `federation_token`  | string  | One of   | Base64url-encoded cross-issuer federation token. [Commercial License](mailto:hello@algovoi.co.uk) required.           |
| `spend_cap_usd`     | float   | No       | Per-session spend ceiling in USD. Default: `100.0`. Range: `0–10000`. Set to `0` for a dry-run session (no payments). |
| `ttl_secs`          | integer | No       | Session lifetime in seconds. Default: `3600` (1 hour). Max: `86400` (24 h).                                           |

### Response

```json theme={null}
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6ImFnZW50X3Nlc3Npb24ifQ...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "spend_cap_usd": 50.0,
  "jti": "a3f8c2d1e4b5..."
}
```

| Field           | Description                                                                        |
| --------------- | ---------------------------------------------------------------------------------- |
| `token`         | HMAC-signed session JWT. Use as `Authorization: Bearer <token>` on payment routes. |
| `token_type`    | Always `"Bearer"`.                                                                 |
| `expires_in`    | Session lifetime in seconds from issuance.                                         |
| `spend_cap_usd` | Confirmed spend cap in USD.                                                        |
| `jti`           | JWT ID — unique session identifier for audit and status queries.                   |

### Error responses

| Status | Detail                                           | Meaning                                                                                     |
| ------ | ------------------------------------------------ | ------------------------------------------------------------------------------------------- |
| `401`  | Unauthorized                                     | API key missing, invalid, or tenant inactive                                                |
| `403`  | `atb_verification_failed`                        | ZKP cert rejected — cert expired, sig invalid, range proof failed, or score below threshold |
| `403`  | `federation_token_invalid`                       | Federation token rejected — HMAC invalid or expired                                         |
| `422`  | `Provide atb_zk_credential or federation_token`  | Neither credential field was present in the request body                                    |
| `503`  | `ATB ZKP credential verification is not enabled` | Gateway not configured for ZKP (contact support)                                            |
| `503`  | `Federation token auth is not enabled`           | Gateway not configured for federation (Commercial License)                                  |

## GET /auth/token/status

Check current spend vs cap for a live session.

### Request

```http theme={null}
GET /auth/token/status
Authorization: Bearer <session_token>
```

No `X-Tenant-Id` required — the tenant is resolved from the JWT claims.

### Response

```json theme={null}
{
  "jti": "a3f8c2d1e4b5...",
  "spend_cap_usd": 50.0,
  "spent_usd": 12.40,
  "remaining_usd": 37.60,
  "active": true
}
```

## Spend cap mechanics

The spend cap is enforced in-process on every payment route (`/x402/verify`, `/mpp/{resource_id}`, `/a2a` task completion). After each confirmed settlement, the gateway records the amount against the session's `jti`.

* **Exceeded cap** → `402 Payment Required` with `detail: "agent_spend_cap_exceeded"`. The payment is blocked before it reaches the facilitator.
* **Tenant volume caps** (database-level) remain the hard enforcement floor regardless of session cap. Session caps are an additional advisory layer.
* **Single-instance note** — the in-process spend store resets on gateway restart. For multi-instance deployments, the spend counter should be moved to Redis. On the current single-instance production deployment this is not a concern.

## ATB discount

When a valid ATB ZKP cert is presented and `ATB_DISCOUNT_ENABLED=true` on the gateway, the effective payment amount is reduced by the discount factor (default 20%) at the resource price resolution step. The session token carries this discount forward automatically — no additional header is required on payment routes.

## Using the session token

Once issued, the session token replaces the API key on all payment routes:

```http theme={null}
POST /x402/verify
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6ImFnZW50X3Nlc3Npb24ifQ...
Content-Type: application/json

{
  "tx_id": "ABC123...",
  "network": "algorand_mainnet",
  "resource_id": "premium-content"
}
```

`X-Tenant-Id` is not required — it is resolved from the JWT `sub` claim.

## Quick start

### Python

```python theme={null}
import httpx

BASE = "https://api.algovoi.co.uk"
TENANT_ID = "<your-tenant-id>"
API_KEY = "<your-api-key>"
ZKP_CERT = "<base64url-encoded cert from ATB>"

# 1. Exchange cert for session token
r = httpx.post(
    f"{BASE}/auth/token",
    headers={"X-Tenant-Id": TENANT_ID, "Authorization": f"Bearer {API_KEY}"},
    json={"atb_zk_credential": ZKP_CERT, "spend_cap_usd": 50.0, "ttl_secs": 3600},
)
r.raise_for_status()
session = r.json()
token = session["token"]
print(f"Session issued. Cap: ${session['spend_cap_usd']} / JTI: {session['jti']}")

# 2. Use session token on payment routes (no X-Tenant-Id needed)
verify = httpx.post(
    f"{BASE}/x402/verify",
    headers={"Authorization": f"Bearer {token}"},
    json={"tx_id": "ABC123", "network": "algorand_mainnet", "resource_id": "premium"},
)
print(verify.json())

# 3. Check remaining budget
status = httpx.get(
    f"{BASE}/auth/token/status",
    headers={"Authorization": f"Bearer {token}"},
)
print(status.json())
```

### TypeScript

```typescript theme={null}
const BASE = "https://api.algovoi.co.uk";

// 1. Exchange cert for session token
const tokenRes = await fetch(`${BASE}/auth/token`, {
  method: "POST",
  headers: {
    "X-Tenant-Id": TENANT_ID,
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    atb_zk_credential: ZKP_CERT,
    spend_cap_usd: 50.0,
    ttl_secs: 3600,
  }),
});
const { token, spend_cap_usd, jti } = await tokenRes.json();
console.log(`Session issued. Cap: $${spend_cap_usd} / JTI: ${jti}`);

// 2. Use session token on payment routes
const verifyRes = await fetch(`${BASE}/x402/verify`, {
  method: "POST",
  headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
  body: JSON.stringify({ tx_id: "ABC123", network: "algorand_mainnet", resource_id: "premium" }),
});
console.log(await verifyRes.json());

// 3. Check remaining budget
const statusRes = await fetch(`${BASE}/auth/token/status`, {
  headers: { Authorization: `Bearer ${token}` },
});
console.log(await statusRes.json());
```

## Backwards compatibility

Existing API key authentication is fully unaffected. The gateway's `GatewayAuth` dependency accepts both API keys and agent session tokens (union). No changes to existing integrations are required.

## On-premise deployment

The full AlgoVoi payment stack is available as a self-hosted Docker Compose deployment. See the [On-Premise](/on-premise) guide for setup instructions.

Agent session authentication — both the ATB ZKP cert path and the federation token path — is supported in the on-premise stack. The local gateway validates a Falcon-1024 signed licence token issued by the AlgoVoi main gateway on startup; no API calls back to AlgoVoi during normal operation.

[Contact us](mailto:hello@algovoi.co.uk) for enterprise deployment and commercial licensing enquiries.

## See also

* [ATB Pass Certificate](/atb-reputation-credential) — how to earn and obtain a ZKP cert
* [Agent Trust Bench](/agent-trust-bench) — the adversarial test harness
* [ATB Hub Conformance](/atb-hub-conformance) — federation discovery
* [Composite Trust Query](/composite-trust-query) — composing session evidence into audit chains
