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,231 @@
require "test_helper"
class OidcDeviceFlowControllerTest < ActionDispatch::IntegrationTest
DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code".freeze
def setup
@group = Group.create!(name: "device-flow-testers", description: "test")
@user = User.create!(email_address: "device_flow@example.com", password: "password123")
@user.groups << @group
@cli = Application.create!(
name: "Device Flow CLI",
slug: "device-flow-cli",
app_type: "oidc",
is_public_client: true,
active: true
)
@cli.allowed_groups << @group
@resource_secret = "resource-server-secret-value-1234567890"
@resource = Application.create!(
name: "Device Flow Resource Server",
slug: "device-flow-rs",
app_type: "oidc",
client_secret: @resource_secret,
active: true
)
end
def teardown
Current.session = nil
[@cli, @resource].each do |app|
OidcRefreshToken.where(application: app).delete_all
OidcAccessToken.where(application: app).delete_all
OidcDeviceCode.where(application: app).delete_all
OidcUserConsent.where(application: app).delete_all
end
end
# --- Discovery -------------------------------------------------------------
test "discovery advertises the device grant and new endpoints" do
get "/.well-known/openid-configuration"
assert_response :success
config = JSON.parse(@response.body)
assert_includes config["grant_types_supported"], DEVICE_GRANT
assert config["device_authorization_endpoint"].end_with?("/oauth/device_authorization")
assert config["introspection_endpoint"].end_with?("/oauth/introspect")
end
# --- Device authorization endpoint -----------------------------------------
test "device_authorization issues a device_code and user_code" do
post "/oauth/device_authorization", params: {client_id: @cli.client_id, scope: "openid groups"}
assert_response :success
body = JSON.parse(@response.body)
assert body["device_code"].present?
assert_match(/\A[A-HJ-NP-Z2-9]{8}\z/, body["user_code"])
assert body["verification_uri"].end_with?("/device")
assert body["verification_uri_complete"].include?("user_code=#{body["user_code"]}")
assert_equal 5, body["interval"]
assert body["expires_in"].positive?
end
test "device_authorization rejects an unknown client" do
post "/oauth/device_authorization", params: {client_id: "does-not-exist"}
assert_response :unauthorized
assert_equal "invalid_client", JSON.parse(@response.body)["error"]
end
# --- Token endpoint device_code grant --------------------------------------
test "token endpoint returns authorization_pending while pending" do
dc = OidcDeviceCode.create!(application: @cli, scope: "openid")
poll(dc)
assert_response :bad_request
assert_equal "authorization_pending", JSON.parse(@response.body)["error"]
end
test "token endpoint returns slow_down when polled faster than the interval" do
dc = OidcDeviceCode.create!(application: @cli, scope: "openid")
poll(dc) # first poll records last_polled_at
poll(dc) # immediate second poll is too fast
assert_response :bad_request
assert_equal "slow_down", JSON.parse(@response.body)["error"]
end
test "token endpoint returns expired_token for an expired code" do
dc = OidcDeviceCode.create!(application: @cli, scope: "openid", expires_at: 1.minute.ago)
poll(dc)
assert_response :bad_request
assert_equal "expired_token", JSON.parse(@response.body)["error"]
end
test "token endpoint returns access_denied when the user denied" do
dc = OidcDeviceCode.create!(application: @cli, scope: "openid")
dc.deny!
poll(dc)
assert_response :bad_request
assert_equal "access_denied", JSON.parse(@response.body)["error"]
end
test "token endpoint issues tokens once approved, then the code is single-use" do
OidcUserConsent.create!(user: @user, application: @cli, scopes_granted: "openid groups", granted_at: Time.current)
dc = OidcDeviceCode.create!(application: @cli, scope: "openid groups")
dc.approve!(user: @user, acr: "1", auth_time: Time.current.to_i)
poll(dc)
assert_response :success
body = JSON.parse(@response.body)
assert body["access_token"].present?
assert body["refresh_token"].present?
assert body["id_token"].present?
assert_equal "Bearer", body["token_type"]
assert_equal "openid groups", body["scope"]
# Replaying the (now consumed) device_code fails.
poll(dc)
assert_response :bad_request
assert_equal "invalid_grant", JSON.parse(@response.body)["error"]
end
# --- Verification page -----------------------------------------------------
test "verification page shows the approval prompt for a signed-in allowed user" do
sign_in_as(@user)
dc = OidcDeviceCode.create!(application: @cli, scope: "openid groups")
get "/device", params: {user_code: dc.user_code}
assert_response :success
assert_match(/Approve/, @response.body)
assert_match(dc.user_code, @response.body)
end
test "approving records consent and approves the device code" do
sign_in_as(@user)
dc = OidcDeviceCode.create!(application: @cli, scope: "openid groups")
post "/device", params: {user_code: dc.user_code}
assert_response :success
assert_match(/approved/i, @response.body)
dc.reload
assert dc.approved?
assert_equal @user, dc.user
assert OidcUserConsent.exists?(user: @user, application: @cli)
end
test "denying marks the device code denied" do
sign_in_as(@user)
dc = OidcDeviceCode.create!(application: @cli, scope: "openid")
post "/device", params: {user_code: dc.user_code, deny: "1"}
assert_response :success
dc.reload
assert dc.denied?
end
test "a user without access cannot approve" do
outsider = User.create!(email_address: "outsider@example.com", password: "password123")
sign_in_as(outsider)
dc = OidcDeviceCode.create!(application: @cli, scope: "openid")
post "/device", params: {user_code: dc.user_code}
assert_response :success
assert_match(/not allowed/i, @response.body)
dc.reload
assert dc.pending?, "device code must stay pending when approval is refused"
end
test "verification page requires authentication" do
dc = OidcDeviceCode.create!(application: @cli, scope: "openid")
get "/device", params: {user_code: dc.user_code}
assert_redirected_to signin_path
end
# --- Introspection ---------------------------------------------------------
test "introspection reports an active token with groups" do
token = OidcAccessToken.create!(application: @cli, user: @user, scope: "openid groups")
post "/oauth/introspect", params: {
token: token.plaintext_token,
client_id: @resource.client_id,
client_secret: @resource_secret
}
assert_response :success
body = JSON.parse(@response.body)
assert_equal true, body["active"]
assert_equal @cli.client_id, body["client_id"]
assert_includes body["groups"], @group.name
assert body["sub"].present?
end
test "introspection reports inactive for a revoked token" do
token = OidcAccessToken.create!(application: @cli, user: @user, scope: "openid")
token.revoke!
post "/oauth/introspect", params: {
token: token.plaintext_token,
client_id: @resource.client_id,
client_secret: @resource_secret
}
assert_response :success
assert_equal false, JSON.parse(@response.body)["active"]
end
test "introspection requires valid caller credentials" do
token = OidcAccessToken.create!(application: @cli, user: @user, scope: "openid")
post "/oauth/introspect", params: {
token: token.plaintext_token,
client_id: @resource.client_id,
client_secret: "wrong-secret"
}
assert_response :unauthorized
end
private
def poll(device_code)
post "/oauth/token", params: {
grant_type: DEVICE_GRANT,
device_code: device_code.plaintext_device_code,
client_id: @cli.client_id
}
end
end
@@ -0,0 +1,137 @@
require "test_helper"
class OidcRegistrationControllerTest < ActionDispatch::IntegrationTest
JSON_HEADERS = {"Content-Type" => "application/json"}.freeze
def teardown
Setting.where(key: Application::DCR_SETTING_KEY).delete_all
Application.where("slug LIKE ?", "%-%").where(metadata: nil).delete_all
Application.where("metadata LIKE ?", "%dynamically_registered%").destroy_all
end
def enable_dcr
Setting.set(Application::DCR_SETTING_KEY, true)
end
def register(body)
post "/oauth/register", params: body.to_json, headers: JSON_HEADERS
end
test "registration is disabled by default" do
register(redirect_uris: ["https://client.example.com/cb"], token_endpoint_auth_method: "none")
assert_response :forbidden
assert_equal "access_denied", JSON.parse(@response.body)["error"]
end
test "registers a public client and returns no secret" do
enable_dcr
register(
redirect_uris: ["https://client.example.com/cb"],
token_endpoint_auth_method: "none",
grant_types: ["authorization_code", "refresh_token"],
client_name: "My MCP Connector"
)
assert_response :created
body = JSON.parse(@response.body)
assert body["client_id"].present?
assert_not body.key?("client_secret")
assert_equal ["https://client.example.com/cb"], body["redirect_uris"]
assert_equal "none", body["token_endpoint_auth_method"]
app = Application.find_by(client_id: body["client_id"])
assert app.public_client?
assert app.require_pkce?
assert_empty app.allowed_groups, "a freshly registered client must be default-deny"
end
test "registers a confidential client and returns a secret once" do
enable_dcr
register(
redirect_uris: ["https://client.example.com/cb"],
token_endpoint_auth_method: "client_secret_basic"
)
assert_response :created
body = JSON.parse(@response.body)
assert body["client_secret"].present?
assert_equal 0, body["client_secret_expires_at"]
app = Application.find_by(client_id: body["client_id"])
assert app.confidential_client?
assert app.authenticate_client_secret(body["client_secret"])
end
test "requires at least one redirect_uri" do
enable_dcr
register(token_endpoint_auth_method: "none")
assert_response :bad_request
assert_equal "invalid_redirect_uri", JSON.parse(@response.body)["error"]
end
test "rejects non-loopback http redirect_uris" do
enable_dcr
register(redirect_uris: ["http://evil.example.com/cb"], token_endpoint_auth_method: "none")
assert_response :bad_request
assert_equal "invalid_redirect_uri", JSON.parse(@response.body)["error"]
end
test "allows http redirect_uris for loopback" do
enable_dcr
register(redirect_uris: ["http://localhost:8123/cb"], token_endpoint_auth_method: "none")
assert_response :created
end
test "rejects unsupported grant types" do
enable_dcr
register(redirect_uris: ["https://client.example.com/cb"], grant_types: ["client_credentials"])
assert_response :bad_request
assert_equal "invalid_client_metadata", JSON.parse(@response.body)["error"]
end
test "rejects a non-JSON body" do
enable_dcr
post "/oauth/register", params: "not json", headers: JSON_HEADERS
assert_response :bad_request
assert_equal "invalid_client_metadata", JSON.parse(@response.body)["error"]
end
# --- Discovery advertisement ----------------------------------------------
test "discovery advertises registration_endpoint only when enabled" do
get "/.well-known/openid-configuration"
assert_not JSON.parse(@response.body).key?("registration_endpoint")
enable_dcr
get "/.well-known/openid-configuration"
assert JSON.parse(@response.body)["registration_endpoint"].end_with?("/oauth/register")
end
test "RFC 8414 metadata alias mirrors OIDC discovery" do
get "/.well-known/oauth-authorization-server"
assert_response :success
config = JSON.parse(@response.body)
assert config["token_endpoint"].end_with?("/oauth/token")
assert config["authorization_endpoint"].end_with?("/oauth/authorize")
end
# --- Admin runtime toggle --------------------------------------------------
test "admin can toggle the registration window at runtime" do
sign_in_as(users(:alice)) # alice is in the admin group
patch "/admin/dynamic_client_registration", params: {enabled: "true"}
assert_redirected_to admin_applications_path
assert Application.dynamic_registration_enabled?
patch "/admin/dynamic_client_registration", params: {enabled: "false"}
assert_not Application.dynamic_registration_enabled?
end
test "non-admins cannot toggle registration" do
sign_in_as(users(:one)) # not an admin
patch "/admin/dynamic_client_registration", params: {enabled: "true"}
assert_redirected_to root_path
assert_not Application.dynamic_registration_enabled?
end
end
+84
View File
@@ -0,0 +1,84 @@
require "test_helper"
class OidcDeviceCodeTest < ActiveSupport::TestCase
def setup
@application = Application.create!(
name: "Device Code Model Test",
slug: "device-code-model-test",
app_type: "oidc",
is_public_client: true,
active: true
)
@user = User.create!(email_address: "device_model@example.com", password: "password123")
end
test "generates an opaque device_code stored as HMAC and looked up by plaintext" do
dc = OidcDeviceCode.create!(application: @application)
assert dc.plaintext_device_code.present?
assert dc.device_code_hmac.present?
assert_not_equal dc.plaintext_device_code, dc.device_code_hmac
assert_equal dc, OidcDeviceCode.find_by_plaintext_device_code(dc.plaintext_device_code)
assert_nil OidcDeviceCode.find_by_plaintext_device_code("wrong")
end
test "generates a short user_code from the unambiguous alphabet" do
dc = OidcDeviceCode.create!(application: @application)
assert_equal 8, dc.user_code.length
# No visually ambiguous characters (0/O, 1/I) and only the allowed alphabet.
assert_match(/\A[A-HJ-NP-Z2-9]{8}\z/, dc.user_code)
end
test "find_by_user_code normalizes case, hyphens, and whitespace" do
dc = OidcDeviceCode.create!(application: @application)
formatted = "#{dc.user_code[0, 4]}-#{dc.user_code[4, 4]}".downcase
assert_equal dc, OidcDeviceCode.find_by_user_code(formatted)
assert_equal dc, OidcDeviceCode.find_by_user_code(" #{dc.user_code} ")
assert_nil OidcDeviceCode.find_by_user_code("nope")
end
test "user_code is unique" do
dc = OidcDeviceCode.create!(application: @application)
dup = OidcDeviceCode.new(application: @application, user_code: dc.user_code)
assert_not dup.valid?
assert_includes dup.errors[:user_code], "has already been taken"
end
test "starts pending and approve! attaches the user and auth context" do
dc = OidcDeviceCode.create!(application: @application)
assert dc.pending?
dc.approve!(user: @user, acr: "1", auth_time: 1_700_000_000)
assert dc.approved?
assert_equal @user, dc.user
assert_equal "1", dc.acr
assert_equal 1_700_000_000, dc.auth_time
end
test "deny! marks the code denied" do
dc = OidcDeviceCode.create!(application: @application)
dc.deny!
assert dc.denied?
end
test "expired? reflects expires_at" do
assert OidcDeviceCode.create!(application: @application, expires_at: 1.minute.ago).expired?
assert_not OidcDeviceCode.create!(application: @application).expired?
end
test "uses_pkce? and rejects malformed code_challenge" do
assert_not OidcDeviceCode.create!(application: @application).uses_pkce?
valid_challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
dc = OidcDeviceCode.create!(application: @application, code_challenge: valid_challenge, code_challenge_method: "S256")
assert dc.uses_pkce?
bad = OidcDeviceCode.new(application: @application, code_challenge: "too-short")
assert_not bad.valid?
assert_includes bad.errors[:code_challenge], "must be 43-128 characters of base64url encoding"
end
end