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
+247 -8
View File
@@ -3,12 +3,12 @@ class OidcController < ApplicationController
# Discovery and JWKS endpoints are public
# authorize is also unauthenticated to handle prompt=none and prompt=login specially
allow_unauthenticated_access only: [:discovery, :jwks, :token, :revoke, :userinfo, :logout, :authorize]
# Machine-to-machine endpoints (token/revoke/userinfo) and pure redirect handlers
# (logout/authorize) legitimately skip CSRF. The consent endpoint is browser-facing
# and state-changing (it grants OAuth scopes), so it MUST keep CSRF protection — the
# consent form already embeds the token via form_with.
skip_before_action :verify_authenticity_token, only: [:token, :revoke, :userinfo, :logout, :authorize]
allow_unauthenticated_access only: [:discovery, :jwks, :token, :revoke, :introspect, :userinfo, :logout, :authorize, :device_authorization]
# Machine-to-machine endpoints (token/revoke/introspect/userinfo/device_authorization)
# and pure redirect handlers (logout/authorize) legitimately skip CSRF. The consent
# endpoint is browser-facing and state-changing (it grants OAuth scopes), so it MUST
# keep CSRF protection — the consent form already embeds the token via form_with.
skip_before_action :verify_authenticity_token, only: [:token, :revoke, :introspect, :userinfo, :logout, :authorize, :device_authorization]
# RFC 6749 §4.1.2.1: client_id and redirect_uri must be validated *before* any
# other error can be reported via redirect. Failures here render a plain page.
@@ -16,7 +16,7 @@ class OidcController < ApplicationController
before_action :validate_redirect_uri, only: :authorize
# Rate limiting to prevent brute force and abuse
rate_limit to: 60, within: 1.minute, only: [:token, :revoke], with: -> {
rate_limit to: 60, within: 1.minute, only: [:token, :revoke, :introspect, :device_authorization], with: -> {
render json: {error: "too_many_requests", error_description: "Rate limit exceeded. Try again later."}, status: :too_many_requests
}
rate_limit to: 30, within: 1.minute, only: [:authorize, :consent], with: -> {
@@ -32,12 +32,14 @@ class OidcController < ApplicationController
authorization_endpoint: "#{base_url}/oauth/authorize",
token_endpoint: "#{base_url}/oauth/token",
revocation_endpoint: "#{base_url}/oauth/revoke",
introspection_endpoint: "#{base_url}/oauth/introspect",
userinfo_endpoint: "#{base_url}/oauth/userinfo",
device_authorization_endpoint: "#{base_url}/oauth/device_authorization",
jwks_uri: "#{base_url}/.well-known/jwks.json",
end_session_endpoint: "#{base_url}/logout",
response_types_supported: ["code"],
response_modes_supported: ["query"],
grant_types_supported: ["authorization_code", "refresh_token"],
grant_types_supported: ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code"],
subject_types_supported: ["pairwise"],
id_token_signing_alg_values_supported: ["RS256"],
scopes_supported: SUPPORTED_SCOPES,
@@ -60,6 +62,11 @@ class OidcController < ApplicationController
claims_parameter_supported: true
}
# Only advertise dynamic client registration when it is enabled (RFC 7591).
if Application.dynamic_registration_enabled?
config[:registration_endpoint] = "#{base_url}/oauth/register"
end
render json: config
end
@@ -68,6 +75,55 @@ class OidcController < ApplicationController
render json: OidcJwtService.jwks
end
# POST /oauth/device_authorization
# RFC 8628 §3.1-3.2 — Device Authorization Request/Response.
# Public (PKCE) client presents its client_id and gets back a device_code the
# client polls with, plus a short user_code the human types on the /device page.
def device_authorization
client_id, _client_secret = extract_client_credentials
application = Application.find_by(client_id: client_id, app_type: "oidc")
unless application&.active?
render json: {error: "invalid_client", error_description: "Unknown or inactive client"}, status: :unauthorized
return
end
# Only accept scopes we support (mirrors the authorize endpoint).
requested_scope = (params[:scope].to_s.split & SUPPORTED_SCOPES).join(" ")
requested_scope = "openid" if requested_scope.blank?
# PKCE is optional but recommended for device flow (RFC 8628 §5.5). If the
# client sends a challenge here it must send the verifier at the token endpoint.
code_challenge = params[:code_challenge].presence
code_challenge_method = params[:code_challenge_method].presence
if code_challenge_method.present? && code_challenge_method != "S256"
render json: {error: "invalid_request", error_description: "Only S256 code_challenge_method is supported"}, status: :bad_request
return
end
device_code = OidcDeviceCode.create!(
application: application,
scope: requested_scope,
nonce: params[:nonce].presence,
code_challenge: code_challenge,
code_challenge_method: code_challenge.present? ? (code_challenge_method || "S256") : nil
)
base_url = OidcJwtService.issuer_url
verification_uri = "#{base_url}/device"
response.headers["Cache-Control"] = "no-store"
render json: {
device_code: device_code.plaintext_device_code,
user_code: device_code.user_code,
verification_uri: verification_uri,
verification_uri_complete: "#{verification_uri}?user_code=#{device_code.user_code}",
expires_in: (device_code.expires_at - Time.current).to_i,
interval: device_code.interval
}
end
# GET /oauth/authorize
def authorize
# @application and a validated redirect_uri are guaranteed by the before_actions.
@@ -453,11 +509,141 @@ class OidcController < ApplicationController
handle_authorization_code_grant
when "refresh_token"
handle_refresh_token_grant
when "urn:ietf:params:oauth:grant-type:device_code"
handle_device_code_grant
else
render json: {error: "unsupported_grant_type"}, status: :bad_request
end
end
# RFC 8628 §3.4-3.5 — the CLI/agent polls here with its device_code until the
# user approves on the /device page, then receives the standard token triple.
def handle_device_code_grant
client_id, client_secret = extract_client_credentials
unless client_id
render json: {error: "invalid_client", error_description: "client_id is required"}, status: :unauthorized
return
end
application = Application.find_by(client_id: client_id)
unless application
render json: {error: "invalid_client", error_description: "Unknown client"}, status: :unauthorized
return
end
# Public clients authenticate with the device_code (+ optional PKCE); a
# confidential client using device flow must still present its secret.
if application.confidential_client?
unless client_secret.present? && application.authenticate_client_secret(client_secret)
render json: {error: "invalid_client", error_description: "Invalid client credentials"}, status: :unauthorized
return
end
end
unless application.active?
render json: {error: "invalid_client", error_description: "Application is not active"}, status: :forbidden
return
end
device_code = OidcDeviceCode.find_by_plaintext_device_code(params[:device_code])
unless device_code && device_code.application_id == application.id
render json: {error: "invalid_grant", error_description: "Invalid device_code"}, status: :bad_request
return
end
OidcDeviceCode.transaction do
# Lock so concurrent polls / a poll racing with approval can't double-issue.
device_code.lock!
if device_code.expired?
render json: {error: "expired_token", error_description: "The device_code has expired"}, status: :bad_request
return
end
if device_code.denied?
render json: {error: "access_denied", error_description: "The authorization request was denied"}, status: :bad_request
return
end
if device_code.pending?
# Enforce the polling interval; too-frequent polls get slow_down, and the
# client is expected to add 5s to its interval (RFC 8628 §3.5).
if device_code.last_polled_at && (Time.current - device_code.last_polled_at) < device_code.interval
device_code.update!(interval: device_code.interval + 5, last_polled_at: Time.current)
render json: {error: "slow_down"}, status: :bad_request
else
device_code.update!(last_polled_at: Time.current)
render json: {error: "authorization_pending"}, status: :bad_request
end
return
end
# Approved: mint tokens via the same path as the authorization code grant.
user = device_code.user
consent = OidcUserConsent.find_by(user: user, application: application)
unless consent
Rails.logger.error "OIDC Security: Device token requested without consent record (user: #{user&.id}, app: #{application.id})"
render json: {error: "invalid_grant", error_description: "Authorization consent not found"}, status: :bad_request
return
end
# PKCE is optional for device flow: only enforced when the device
# authorization request supplied a code_challenge.
if device_code.uses_pkce?
pkce_result = validate_pkce(application, device_code, params[:code_verifier])
unless pkce_result[:valid]
render json: {error: pkce_result[:error], error_description: pkce_result[:error_description]}, status: pkce_result[:status]
return
end
end
granted_scope = device_code.scope
access_token_record = OidcAccessToken.create!(
application: application,
user: user,
scope: granted_scope
)
refresh_token_record = OidcRefreshToken.create!(
application: application,
user: user,
oidc_access_token: access_token_record,
scope: granted_scope,
auth_time: device_code.auth_time,
acr: device_code.acr
)
id_token = OidcJwtService.generate_id_token(
user,
application,
consent: consent,
nonce: device_code.nonce,
access_token: access_token_record.plaintext_token,
auth_time: device_code.auth_time,
acr: device_code.acr,
scopes: granted_scope,
claims_requests: {}
)
# Single-use: destroy the code so an approved device_code can't be replayed.
device_code.destroy!
response.headers["Cache-Control"] = "no-store"
response.headers["Pragma"] = "no-cache"
render json: {
access_token: access_token_record.plaintext_token,
token_type: "Bearer",
expires_in: application.access_token_ttl || 3600,
id_token: id_token,
refresh_token: refresh_token_record.token,
scope: granted_scope
}
end
end
def handle_authorization_code_grant
# Get client credentials from Authorization header or params
client_id, client_secret = extract_client_credentials
@@ -868,6 +1054,59 @@ class OidcController < ApplicationController
render json: claims
end
# POST /oauth/introspect
# RFC 7662 - OAuth 2.0 Token Introspection.
# A resource server (e.g. c2a2) presents an opaque access token and its own
# client credentials; we reply whether the token is active and, as an extension,
# the user's groups so the resource server can authorize on group membership.
def introspect
# RFC 7662 §2.1: the caller (resource server) MUST authenticate. Only a
# registered confidential client may introspect.
caller_id, caller_secret = extract_client_credentials
caller = Application.find_by(client_id: caller_id) if caller_id.present?
unless caller&.confidential_client? && caller.active? &&
caller_secret.present? && caller.authenticate_client_secret(caller_secret)
render json: {error: "invalid_client", error_description: "Caller authentication failed"}, status: :unauthorized
return
end
token_value = params[:token]
if token_value.blank?
render json: {error: "invalid_request", error_description: "token parameter is required"}, status: :bad_request
return
end
response.headers["Cache-Control"] = "no-store"
response.headers["Pragma"] = "no-cache"
access_token = OidcAccessToken.find_by_token(token_value)
# Inactive/unknown/expired/revoked tokens (or those for a disabled app) are
# reported as simply inactive per RFC 7662 §2.2 — never an error.
unless access_token&.active? && access_token.application&.active? && access_token.user
render json: {active: false}
return
end
user = access_token.user
application = access_token.application
consent = OidcUserConsent.find_by(user: user, application: application)
render json: {
active: true,
scope: access_token.scope,
client_id: application.client_id,
token_type: "Bearer",
exp: access_token.expires_at.to_i,
iat: access_token.created_at.to_i,
sub: consent&.sid || user.id.to_s,
aud: application.client_id,
username: user.email_address,
groups: user.groups.pluck(:name)
}
end
# POST /oauth/revoke
# RFC 7009 - Token Revocation
def revoke