Add OAuth device flow, token introspection, and dynamic client registration

Adds three OAuth surfaces to the OIDC provider so CLIs, terminal agents, and
MCP connectors can authenticate as real users instead of using static API keys.

Device Authorization Grant (RFC 8628):
- OidcDeviceCode model (HMAC device_code, short plaintext user_code, nullable
  user until approval, slow_down polling state), mirroring OidcAuthorizationCode
- POST /oauth/device_authorization issues the code pair + verification URIs
- device_code grant on /oauth/token returns authorization_pending / slow_down /
  access_denied / expired_token, then the standard token triple; single-use
- Authenticated /device approval page, gated by Application#user_allowed?

Token Introspection (RFC 7662):
- POST /oauth/introspect: confidential-caller-authenticated; returns active,
  scope, and the user's groups so resource servers can authorize on membership

Dynamic Client Registration (RFC 7591):
- POST /oauth/register creates public/confidential clients (PKCE required)
- Runtime toggle via a new Setting store + admin switch on the Applications page;
  off by default, env var CLINCH_DCR_ENABLED as bootstrap fallback
- New clients are default-deny (no allowed_groups) until an admin grants access
- RFC 8414 metadata alias at /.well-known/oauth-authorization-server;
  registration_endpoint advertised only while the window is open

Discovery advertises all three grants/endpoints. Seeds add a clinch-cli public
client and a c2a2-introspection confidential client. ADRs in docs/decisions
record the opaque-vs-JWT, device-flow, and DCR-security decisions.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F7cwhwDJp3MJJDoNPVE6zq
This commit is contained in:
Dan Milne
2026-07-19 12:30:02 +10:00
co-authored by Claude Opus 4.8
parent c85d25c4b9
commit 7149b98b7b
22 changed files with 1551 additions and 9 deletions
@@ -0,0 +1,39 @@
# 0001 — Opaque access tokens (not JWT); introspection for resource servers
**Status:** Accepted · **Date:** 2026-07-19
## Decision
Clinch issues **opaque** access and refresh tokens — random strings stored server-side
as SHA-256 HMACs (`OidcAccessToken` / `OidcRefreshToken`), not self-contained JWTs. The
**ID token stays a JWT** (RS256), because it is meant to be read by the client. Resource
servers that need to validate an access token call the **RFC 7662 introspection endpoint**
(`POST /oauth/introspect`), which also returns the user's `groups` for authorization.
## Context
There is no universal winner between opaque and JWT access tokens; it is an architecture
call:
| | Opaque (reference) | JWT (self-contained) |
|---|---|---|
| Validation | Resource server calls back (introspect/userinfo) | Offline signature check against JWKS |
| **Revocation** | **Instant** — the AS holds the state | Valid until expiry unless a blocklist is added (which re-adds state) |
| Best when | One central IdP, few resource servers, revocation matters | Many resource servers, high throughput, offline verification needed |
| Token contents | Nothing leaks (just a handle) | Claims readable by any holder |
Clinch is a single self-hosted IdP with a handful of relying parties. It already has
instant revocation, including refresh-token **family revocation** on reuse. That
revocation guarantee is a real security property for an IdP, and the introspection
callback cost is negligible at this scale (and cacheable by the resource server).
## Consequences
- Resource servers (e.g. c2a2) cannot verify tokens offline; they must call
`/oauth/introspect` (authenticated as a confidential client) and should briefly cache
positive results.
- Tokens can be revoked immediately (logout, admin action, reuse detection) and stop
working at the next introspection — a property JWT access tokens can't offer without
reintroducing server state.
- If we ever need many resource servers with zero-latency offline verification, revisit
with RFC 9068 (JWT access token profile) — accepting the loss of instant revocation.
@@ -0,0 +1,50 @@
# 0002 — CLI/agent auth via the Device Authorization Grant (RFC 8628)
**Status:** Accepted · **Date:** 2026-07-19
## Decision
CLIs and terminal agents (e.g. Claude) authenticate to Clinch-protected services as a
real user via the **OAuth 2.0 Device Authorization Grant (RFC 8628)** instead of static
API keys. The tool prints a short code and a URL; the user approves at `/device` with
their passkey; the tool polls the token endpoint and receives the standard
access + refresh + ID token triple.
## Context
We wanted CLIs — and especially headless agents — to authenticate as a real user rather
than carry a long-lived API key. The two mainstream options:
- **Device flow (RFC 8628):** tool prints a code, human approves on any device, tool
polls. Needs only "print text" + "poll HTTP".
- **Auth code + PKCE with a loopback (`127.0.0.1`) redirect (RFC 8252):** tool opens a
browser and catches a local redirect.
Agents are often sandboxed or run on a remote box where opening a browser and receiving a
loopback redirect is unreliable. Device flow needs neither, which is exactly why it fits
CLIs and agents. The human approves wherever their passkey lives.
## Implementation notes
- `OidcDeviceCode` mirrors `OidcAuthorizationCode`: opaque `device_code` stored as an
HMAC, short plaintext `user_code`, nullable `user` until approval, `status`
(pending/approved/denied), PKCE columns, and `interval`/`last_polled_at` for
`slow_down` enforcement.
- Endpoints: `POST /oauth/device_authorization`, the
`urn:ietf:params:oauth:grant-type:device_code` branch of `POST /oauth/token`, and the
authenticated verification page `GET/POST /device`.
- Token issuance reuses the authorization-code path (`OidcAccessToken` +
`OidcRefreshToken` + `OidcJwtService`). Access control reuses
`Application#user_allowed?`, so approval is gated by group membership.
- PKCE is **optional** for device flow (RFC 8628 §5.5): enforced only when the device
authorization request supplied a `code_challenge`. The `device_code` itself is a
high-entropy secret delivered directly to the client over TLS.
- A well-known public client `clinch-cli` (no secret, PKCE) is seeded for tools to use.
## Consequences
- No static API keys for user-context CLI/agent access; tokens are revocable and expire.
- Resource servers validate the resulting opaque access tokens via introspection — see
[0001](0001-opaque-vs-jwt-access-tokens.md).
- Same foundation (public clients + PKCE + introspection) supports future MCP connector
support, whose main additional piece would be Dynamic Client Registration (RFC 7591).
@@ -0,0 +1,55 @@
# 0003 — Dynamic Client Registration (RFC 7591), runtime-gated
**Status:** Accepted · **Date:** 2026-07-19
## Decision
Clinch supports **OAuth 2.0 Dynamic Client Registration (RFC 7591)** at
`POST /oauth/register`, so clients (notably MCP connectors like Claude) can register
themselves instead of being hand-created. It is **off by default** and toggled at runtime
by an admin from the Applications page. A newly registered client is **default-deny**: it
has no `allowed_groups` until an admin attaches one.
We also serve the **RFC 8414** metadata alias at
`/.well-known/oauth-authorization-server` (the OIDC discovery document is a superset), and
advertise `registration_endpoint` only while registration is enabled.
## Context
MCP connectors expect to self-register via anonymous DCR rather than being pre-provisioned.
But open registration is a real risk: anyone could register a legitimate-looking client and
attempt **consent phishing** — luring a user to approve it, then holding a token that acts
as that user against any resource server that trusts clinch tokens (via introspection, see
[0001](0001-opaque-vs-jwt-access-tokens.md)).
Two controls make this safe:
1. **Runtime window, not always-on.** DCR is a toggle (persisted `Setting`, admin UI), so
the operator opens it briefly, lets the client register, attaches a group, and closes it
again. The `CLINCH_DCR_ENABLED` env var is only a bootstrap default when the setting is
unset. Default is off.
2. **Default-deny for new clients.** Clinch's authorize flow already gates on
`Application#user_allowed?` (group membership), evaluated *before* the consent screen
renders. A group-less registered client therefore can't show any user an approve button —
the consent-phishing path dead-ends until an admin explicitly grants a group. ForwardAuth
services are gated by the user's session cookie, not client tokens, so DCR doesn't widen
that surface at all.
## Implementation notes
- `OidcRegistrationController#create`: validates `token_endpoint_auth_method`
(none/client_secret_basic/client_secret_post), `grant_types`
(authorization_code/refresh_token), `response_types` (code), and `redirect_uris`
(https anywhere; http only for loopback). Creates a public or confidential `Application`
with `require_pkce: true`, returns the RFC 7591 response (client_secret once, for
confidential clients).
- `Setting` is a small key/value store; `Application.dynamic_registration_enabled?` reads it
with the env var as fallback. Admin toggle: `Admin::DynamicClientRegistrationController`.
## Consequences
- MCP connectors can self-register when the window is open, then operate normally once an
admin grants a group.
- No always-on anonymous registration surface; the risky window is short and operator-driven.
- Remaining MCP pieces (resource indicators RFC 8707, protected-resource metadata RFC 9728 on
the resource server) are separate, smaller follow-ups.
+12
View File
@@ -0,0 +1,12 @@
# Architecture Decision Records
Short, dated records of non-obvious technical decisions in Clinch. They live in the
repo (rather than a wiki) so they version with the code and travel with a checkout.
Each file is one decision. Newest decisions get the next number.
| # | Decision |
|---|----------|
| [0001](0001-opaque-vs-jwt-access-tokens.md) | Access tokens are opaque (not JWT); resource servers use introspection |
| [0002](0002-device-authorization-grant.md) | CLI/agent auth uses the OAuth 2.0 Device Authorization Grant (RFC 8628) |
| [0003](0003-dynamic-client-registration.md) | Dynamic Client Registration (RFC 7591), runtime-gated + default-deny |