# Auth.md — Agent Authentication & Authorization Standard

Canonical URL: `https://www.it-tremmel.de/.well-known/auth.md`
Platform: IT-Tremmel GmbH (ITT SaaS / ERP & MiniApps)
Status: Stable · Version 1.2.0 · Last updated 2026-09-05

This document is the authoritative specification for how AI agents authenticate
to, and act on, the ITT platform. It is machine- and human-readable: an agent
fetches it once to learn the real endpoints, token format, scopes, and audit
rules below, then operates strictly within them.

Two distinct credential systems exist on this platform. **Agents use the
AgentAuth system described here** — not the human login (JWT) or the tenant
API-key system, which are summarised under "Related credential systems" only so
agents do not confuse them.

---

## 1. Identity & secure agent login

An agent is identified by a stable `agent_id` (an opaque string chosen when the
token is issued, e.g. `agent-procurement-bot`). An agent never holds a human
password and never performs an interactive login. It presents a scoped bearer
token on every request.

There are **two ways to obtain that token**, and both end in the same
credential:

1. **Admin-issued (out of band).** A tenant administrator, authenticated by the
   platform's normal JWT session, mints a token and hands it to the agent.
   Described in §4.
2. **Bought by the agent itself (self-service).** An agent that starts with
   nothing but this document orders paid API access, pays, and redeems its own
   token — no human in the loop. Described in **§5**. This is the path to take
   if you are an agent reading this to get started.

Common to both:

- The token is bound to one tenant and one `agent_id`.
- The plaintext token is shown **exactly once**, at issue time. It is stored
  only as a bcrypt hash; it cannot be recovered, only revoked and re-issued.
- Scopes are fixed at issue time; a token never widens its own authority.

---

## 2. Credential format & handling

Agent tokens are opaque bearer tokens, **not** JWTs:

```
itt_agt_<8 hex>.<48 hex>
example: itt_agt_3f9a1c20.6b1d…(48 hex chars)
```

- The left half (`itt_agt_<8 hex>`) is a **lookup id**, stored in plaintext so a
  presented token can be located in O(1).
- The right half (after the `.`) is the **secret**, never persisted in
  plaintext. The full token is bcrypt-hashed at rest (cost 10) and verified in
  constant time.
- Splitting lookup id from secret means a leaked lookup id alone (e.g. from a
  log line) cannot be replayed.

Presentation: send the token as a standard bearer credential.

```
Authorization: Bearer itt_agt_3f9a1c20.<secret>
```

Handling rules for agents:

- Treat the token as a secret: never log it, never embed it in URLs, never
  share it across agents. One token = one agent identity.
- On suspected exposure, call revoke (§4) and request a fresh token.
- Tokens are transport-protected: production endpoints are HTTPS-only.

---

## 3. Authorization scopes (least privilege)

Every token is issued with an explicit, minimal set of scopes. There is **no
wildcard and no implicit grant** — an action proceeds only if the token carries
the exact scope it requires. The complete catalogue:

| Scope         | Grants                                                        |
|---------------|---------------------------------------------------------------|
| `search:read` | Read the discovery surface (`/.well-known/*`, catalog, llms)  |
| `erp:read`    | Read ERP module data — lists, detail views, exports           |
| `erp:write`   | Create/update ERP records (CRUD writes)                       |
| `reports:run` | Execute reporting / analytics jobs                            |
| `audit:read`  | Read this agent's audit log                                   |
| `commerce:order` | Complete ACP checkout sessions into orders / booking offers (see `/.well-known/payments.json`) |

Request the narrowest set that covers the task. A read-only research agent
should hold only `search:read` (+ `erp:read`); it must never be granted
`erp:write`. Unknown scopes are rejected at issue time.

---

## 4. Token lifecycle (issue / introspect / revoke / expiry)

Base path: `/api/agent-auth`. JSON request/response; standard ITT error
envelope `{ "success": false, "error": <code>, "message": <text> }`.

### Issue — `POST /api/agent-auth/tokens` (JWT + CSRF)

```jsonc
// request
{ "agent_id": "agent-procurement-bot",
  "name": "Procurement bot (read-only)",
  "scopes": ["search:read", "erp:read"],
  "expires_at": "2026-12-31T23:59:59+00:00" }  // ISO-8601 or YYYY-MM-DD; optional

// 201 response
{ "agent_token": { "id": 42, "agent_id": "agent-procurement-bot",
                   "token_id": "itt_agt_3f9a1c20", "scopes": ["search:read","erp:read"],
                   "is_active": 1, "expires_at": "2026-12-31 23:59:59" },
  "token": "itt_agt_3f9a1c20.<secret>",      // shown ONCE
  "token_type": "Bearer",
  "warning": "Store this token securely. It will not be shown again." }
```

Validation errors return `400` with `agent_id_required`, `scope_required`,
`invalid_scope`, or `invalid_expires_at`.

### Introspect / validate — `POST /api/agent-auth/introspect` (public)

RFC 7662-inspired. The agent (or a downstream service) confirms a token is
active and, optionally, that it carries a given scope. Token may be supplied via
the `Authorization` header or a `token` body field.

```jsonc
// request: { "token": "itt_agt_…", "scope": "erp:read" }   // scope optional
// 200 active
{ "active": true, "agent_id": "agent-procurement-bot", "tenant_id": "…",
  "scopes": ["search:read","erp:read"], "expires_at": "2026-12-31 23:59:59",
  "token_type": "Bearer" }
// inactive: { "active": false, "outcome": "expired|revoked|missing_scope|not_found|bad_secret|invalid_format" }
```

### Revoke — `DELETE /api/agent-auth/tokens/{id}` (JWT + CSRF)

Immediately deactivates a token (`is_active = 0`, `revoked_at` set). A revoked
token fails every subsequent validation. `404` if not found, `422` if already
revoked.

### List — `GET /api/agent-auth/tokens` (JWT)

Lists the tenant's tokens with metadata and `last_used_at`. Hashes are never
returned.

### Expiry & session control

- A token with `expires_at` in the past is rejected (`expired`) on every call —
  there is no grace window and no silent refresh.
- **There is no refresh endpoint by design.** Rotation is explicit: revoke the
  old token and issue a new one. This keeps every credential change auditable
  and prevents a long-lived token from being silently extended.
- Each successful validation updates `last_used_at`, giving operators a clear
  signal for dormant-token clean-up.

### OAuth 2.0 client credentials (RFC 6749 §4.4, RFC 8414, RFC 9728, RFC 7009)

OAuth clients use the same agent token; there is no second credential store.

- Metadata: `GET /.well-known/oauth-authorization-server` (issuer = this
  origin) and `GET /.well-known/oauth-protected-resource`.
- Token: `POST /api/oauth/token` with `grant_type=client_credentials`;
  `client_id` = the lookup half `itt_agt_<lookup>`, `client_secret` = the full
  token, via HTTP Basic (`client_secret_basic`) or form body
  (`client_secret_post`), never both. The response
  `{ "access_token", "token_type": "Bearer", "expires_in", "scope" }` returns
  the agent token itself with its real expiry and scopes. `scope` may only
  narrow (subset check), never widen; least privilege is chosen at issue time.
  Errors follow RFC 6749 §5.2 (`invalid_client` 401, `invalid_grant` for an
  expired access period, `unsupported_grant_type` / `invalid_scope` 400).
- Revocation: `POST /api/oauth/revoke` with `token=<agent token>`, client
  authenticated like the token request; always `200`, revokes only the
  caller's own token.
- Tenant binding: a token is only accepted by the authorization server of its
  own tenant's host.
- `401` answers of agent routes (e.g. `POST /api/mcp`) carry
  `WWW-Authenticate: Bearer resource_metadata="<origin>/.well-known/oauth-protected-resource"`
  (MCP authorization, revision `2025-06-18`).

---

## 5. Buying access yourself (self-service — no human in the loop)

An agent can acquire its own paid API access using only this document and the
public contract at `GET /api/docs/openapi.json`. Nothing here needs a tenant
admin, a browser or a human decision.

**Never hard-code the price or the period.** They are configuration and are
published live:

```
GET /api/agents/catalog          # price, currency, access period, usage profiles
GET /api/docs/pricing            # the same numbers, per metered capability
```

### 5.1 Order

```
POST /api/agent-auth/self-service/orders
Idempotency-Key: <your key>
{ "tenant_id": "...", "agent_id": "...", "scopes": ["erp:read"],
  "usage_profile": "agent" }
```

`201` returns `order_id`, `amount_minor_units`, `currency`,
`access_period_days`, `usage_profile`, `request_budget`, `auto_renew` (always
`false`), `status: "payment_pending"`, `status_url`, and a **`claim_token`
shown exactly once**. The claim token is what proves later that *you* placed
this order; store it before doing anything else. Replaying the same
`Idempotency-Key` answers `409 agent_order_replayed` rather than ordering twice.

`usage_profile` is a named configuration, not a different product: `agent` and
`app` cost the same and last the same; `app` carries the larger request budget
because an application calls far more often than a single agent. An unknown
profile is refused with `422 invalid_usage_profile` — it is never silently
downgraded.

### 5.2 Pay

Settle a tenant-bound payment for exactly `amount_minor_units` in `currency`.
Note its `payment_transaction_id`.

### 5.3 Watch the order

```
GET /api/agent-auth/self-service/orders/{order_id}
X-Agent-Order-Claim: <claim_token>
```

Returns `status` (`payment_pending` → `issued`) and a `next_step` telling you
exactly which call to make next. The claim travels in the header, never in a
query string. A wrong claim, or an order belonging to another tenant, answers
`404` — never `200`, and never a hint that the order exists.

### 5.4 Redeem

```
POST /api/agent-auth/self-service/orders/{order_id}/issue
{ "claim_token": "...", "payment_transaction_id": "..." }
```

Returns the agent token. Typed refusals: `422 payment_not_received` (no settled
payment found), `422 payment_amount_mismatch` (amount or currency differs from
the order), `409 payment_already_consumed` (that payment already bought a
token).

### 5.5 Budget, and what a `429` means

Every successful request against a catalogue route consumes one unit of the
request budget of your access period.

```
GET /api/agent-auth/self-service/usage      # budget, used, remaining, profile
```

When the budget is gone, every further call answers **`429`** with
`Retry-After` and the headers `X-Agent-Quota-Used`, `X-Agent-Quota-Budget` and
`X-Agent-Error: agent_quota_exhausted`; the body carries
`error: "rate_limit_exceeded"`. A refused request is **not** counted against
you. Through the action layer (§6) the same refusal arrives as the typed
result code `rate_limited` with `inner_code: "rate_limit_exceeded"`, and the
same headers on the response.

### 5.6 Expiry — access never renews itself

```
GET /api/agent-auth/self-service/access-status
```

Access lasts exactly `access_period_days` from issue and **never auto-renews**;
`auto_renew` is `false` and there is no refresh endpoint by design. After it
expires the credential does not die silently: **reads keep working**, while
writes answer `agent_access_expired_read_only`. To continue, order again (§5.1)
— the flow is identical.

---

## 6. The typed action layer — one envelope over every module

`POST /api/agents/actions` is the recommended way for an agent to work. Instead
of learning one REST shape per module, you send a uniform, typed operation and
the platform dispatches it internally through the very same pipeline as the
REST route — so auth, tenant scoping, expiry, quota and audit are re-enforced
**per operation**, not once at the envelope.

```
POST /api/agents/actions
Idempotency-Key: <required for create/update/delete>
{ "action": "create", "resource": "erp.document-types",
  "input": { "code": "INV", "name": "Invoice" } }
```

`action` is one of `list`, `get`, `search`, `create`, `update`, `delete`. Reads
take `filter`, `fields`, `limit`/`offset`; `search` works across entities.
Which resources exist, and which scope and input schema each action needs, is
derived from the compiled OpenAPI contract — never hand-maintained:

```
GET /api/agents/actions/resources[?prefix=erp.]
```

Rules that make the layer safe to automate against:

- **Idempotent writes.** `create`, `update` and `delete` require an
  `Idempotency-Key`; a repeat of the same request returns the stored response
  with `Idempotent-Replay: true` and has **exactly one** effect. The same key
  with a *different* body is refused with `422 idempotency_key_reused`. A `429`
  never burns the key — retry the identical call once budget returns.
- **Dry run.** `"dry_run": true` performs **no** effect and answers with the
  effect it would have had, including whether the target exists.
- **Bulk.** Send `operations: [...]` with `stop_on_error`. The envelope answers
  `200` and each operation carries its own status; skipped ones report
  `skipped_after_error`. A bulk of N costs N units — the envelope itself is
  never billed on top.
- **Typed errors.** Every failure carries a stable code: `not_found`,
  `forbidden`, `unauthenticated`, `conflict`, `rate_limited`,
  `validation_failed`, plus `inner_code` from the underlying route.
- **Fail closed.** A scope your token lacks is `403`, never `200`. An id
  belonging to another tenant is `404`, never `200`. After the access period
  expires reads still work and writes are refused.

---

## 7. Scope enforcement

Scope checks are enforced server-side by `AgentScopeMiddleware`, not by the
agent. For a protected action the middleware:

1. Reads the `Authorization: Bearer …` header.
2. Locates the token by lookup id, then verifies the secret hash.
3. Rejects if the token is missing/malformed (`400`), or
   not-found / revoked / expired / wrong-secret / **missing the required
   scope** (`403`).
4. On success, attaches the validated agent identity and scopes to the request
   and lets the action run.

Error outcomes map to HTTP status as: malformed → `400`; not-authorized
(including missing scope) → `403`. This matches the platform-wide convention
(`400` validation, `403` authorization, `404` not-found, `422` semantic,
`429` rate-limit).

---

## 8. Audit logging of agent actions

Every agent auth event **and** every scoped action is written to an append-only
audit log (`agent_audit_log`). Each row records: `tenant_id`, `agent_id`,
`token_id`, `action` (e.g. `token.issue`, `token.revoke`, `token.introspect`,
or a business action like `erp.read`), `scope`, `outcome`
(`ok | invalid_format | not_found | revoked | expired | bad_secret | missing_scope`),
optional `detail`, and `created_at`. Both successes and denials are logged, so a
rejected attempt is as visible as a permitted one.

Read it (tenant-scoped, JWT): `GET /api/agent-auth/audit?limit=100&agent_id=…`
(requires the `audit:read` scope when accessed by an agent token).

---

## 9. Accessing approved external services

Agents may reach external services **only** through platform-mediated,
least-privilege, auditable mechanisms:

- The agent authenticates to ITT with its scoped token; ITT performs the
  outbound call to the approved third party using server-held credentials. The
  agent never receives third-party secrets.
- Only services the tenant has explicitly approved are reachable; there is no
  open egress.
- Every mediated call inherits the scope check and writes an audit row, so
  external access is bounded by the same least-privilege envelope as internal
  actions.

---

## 10. MCP gateway (Model Context Protocol)

Agents that speak MCP can use the platform's native MCP endpoint instead of
raw REST — same tokens, same scopes, same audit trail:

```
POST /api/mcp
Authorization: Bearer itt_agt_<lookup>.<secret>
Content-Type: application/json
```

- **Transport:** Streamable HTTP, JSON-RPC 2.0, protocol revision
  `2025-06-18`. Every call is answered with a single JSON response body (no
  SSE stream); the server is stateless (no `Mcp-Session-Id`). JSON-RPC
  batches are not supported.
- **Methods:** `initialize`, `ping`, `tools/list`, `tools/call`;
  `notifications/*` are accepted with `202` and no body.
- **Auth:** agent bearer tokens **only** (any valid scope may connect).
  Human sessions (JWT), personal access tokens and API keys are refused.
  Token failures are HTTP-level (`400` malformed / `403` not authorized —
  same envelope as §7); a request that reaches the gateway without an agent
  identity gets a JSON-RPC auth error (`-32001`, HTTP `401`). Every `401`
  names the OAuth protected resource metadata in `WWW-Authenticate`
  (`resource_metadata`, see §4 "OAuth 2.0 client credentials").
- **Tools = route policy catalogue, scope-filtered.** `tools/list` is built
  from the route policy catalogue plus explicit MCP tool definitions and
  returns the read-only tools your token's scopes allow (e.g. a
  `search:read`-only token sees the search tool + the capability catalog).
  The gateway action itself is never projected as a tool. Calling a tool whose
  scope the token lacks returns a tool result with `isError: true`. **Read-only
  first slice:** no mutating tool exists; `erp:write` grants nothing here.
- **Audit:** every `tools/call` executes internally through the same
  middleware pipeline as the REST routes above, so it lands in the §8 audit
  log under its real action (`erp.read`, `search.read`, …) in addition to
  the `mcp.gateway` entry row.
- **Discovery:** the endpoint is announced in `/.well-known/agents.json`
  (`mcp` key), `/.well-known/agent-card.json` (`x-mcp`) and
  `GET /api/agents/capabilities` (`mcp` key).

---

## 11. UI steering affordances (computer-use browser agents)

The web UI is machine-steerable: on phase-one steering hosts (localhost /
`beta.*` / `*.local` / first-party desktop shells), an authenticated session
exposes the in-app steering command registry — the SAME catalogue the
voice/chat orchestrator dispatches through — in machine-readable form:

- **Per-route manifest:** `window.__ITT_STEERING_MANIFEST__()` (fresh on
  every call) or the DOM JSON island `<script type="application/json"
  id="itt-steering-manifest">` — module ids, command ids, localized titles,
  parameter schemas, and availability for the CURRENT page.
- **DOM attributes:** elements bound to a registered command carry
  `data-steer-command="<moduleId>.<commandId>"` (plus `data-steer-params`
  JSON when the command has fixed parameter defaults). Envelope `click` /
  `fill` actions address elements by `data-testid`.
- **Envelope contract:** steering scripts are lists of
  `{ id, action, args }` envelopes; the allowed action set and step ceiling
  are published in `/.well-known/agents.json` under `steering.envelope`
  (single source: the server-side SteeringScriptValidator).
- **Sessions:** the current browser-steering session pipeline is
  consent-gated in-app (`/api/remote-steering`, commands delivered over SSE at
  `/api/remote-steering/events`); mutating route calls prompt the signed-in
  owner for confirmation.

Full descriptor: `/.well-known/agents.json` (`steering` key) and
`/.well-known/agent-card.json` (`x-steering`). The authenticated
`GET /api/steering/capabilities` endpoint serves the generated steering
capability registry; legacy `/api/steering/*` queue endpoints remain a
separate gateway surface.

---

## 12. Related credential systems (for disambiguation)

Agents should use AgentAuth (above). These others exist but are out of scope for
agents:

- **Human/session auth (JWT):** `/api/auth/*` — interactive login, 2FA, tenant
  switch, session tracking. `JWT_SECRET` must be set per environment; tokens are
  HS256/RS256 and fail closed on misconfiguration.
- **Tenant API keys:** `/api/tenant-api-keys` — `itt_k…` keys for tenant
  integrations, with their own `{resource}:{action}` scope allowlist and rate
  limiting.
- **Public, unauthenticated discovery:** `/.well-known/security.txt`,
  `/.well-known/openid-configuration`, `/api/docs`, `/api/openapi.json`.

---

## 13. Security contact

Report vulnerabilities per `/.well-known/security.txt`
(`mailto:anfrage@it-tremmel.de`, subject `[Security]`). Disclosure is
coordinated and acknowledged confidentially.
