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:
co-authored by
Claude Opus 4.8
parent
c85d25c4b9
commit
7149b98b7b
@@ -103,6 +103,22 @@ class Application < ApplicationRecord
|
||||
app_type == "forward_auth"
|
||||
end
|
||||
|
||||
DCR_SETTING_KEY = "dynamic_client_registration".freeze
|
||||
|
||||
# OAuth 2.0 Dynamic Client Registration (RFC 7591) is opt-in: it lets anyone
|
||||
# anonymously create an OIDC client, so it is disabled by default. An admin
|
||||
# toggles it at runtime (open the window, let a client self-register, attach it
|
||||
# to a group, close the window again). Newly registered clients are still
|
||||
# default-deny (no allowed_groups) until an admin grants access.
|
||||
#
|
||||
# The persisted Setting is authoritative once set; until then we fall back to
|
||||
# the CLINCH_DCR_ENABLED env var (bootstrap/headless default, off if unset).
|
||||
def self.dynamic_registration_enabled?
|
||||
stored = Setting.boolean(DCR_SETTING_KEY)
|
||||
return stored unless stored.nil?
|
||||
ActiveModel::Type::Boolean.new.cast(ENV["CLINCH_DCR_ENABLED"])
|
||||
end
|
||||
|
||||
# Client type checks (for OIDC)
|
||||
def public_client?
|
||||
client_secret_digest.blank?
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# OAuth 2.0 Device Authorization Grant code (RFC 8628).
|
||||
#
|
||||
# Mirrors OidcAuthorizationCode: the long device_code is opaque and stored as an
|
||||
# HMAC, while the short user_code is stored in plaintext because the user types it
|
||||
# back on the verification page. A record is created "pending" by the device
|
||||
# authorization endpoint, moved to "approved" (with a user) or "denied" on the
|
||||
# verification page, and consumed by the token endpoint once approved.
|
||||
class OidcDeviceCode < ApplicationRecord
|
||||
belongs_to :application
|
||||
belongs_to :user, optional: true # nil until the request is approved
|
||||
|
||||
# Alphabet for the user_code: uppercase letters + digits, minus visually
|
||||
# ambiguous characters (0/O, 1/I, etc.) so it is easy to read and type.
|
||||
USER_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789".chars.freeze
|
||||
USER_CODE_GROUP_SIZE = 4
|
||||
USER_CODE_GROUPS = 2 # e.g. "WDJB-MJHT"
|
||||
|
||||
STATUSES = %w[pending approved denied].freeze
|
||||
|
||||
attr_accessor :plaintext_device_code
|
||||
|
||||
before_validation :generate_device_code, on: :create
|
||||
before_validation :generate_user_code, on: :create
|
||||
before_validation :set_expiry, on: :create
|
||||
|
||||
validates :device_code_hmac, presence: true, uniqueness: true
|
||||
validates :user_code, presence: true, uniqueness: true
|
||||
validates :status, inclusion: {in: STATUSES}
|
||||
validates :code_challenge_method, inclusion: {in: %w[S256], allow_nil: true}
|
||||
validate :validate_code_challenge_format, if: -> { code_challenge.present? }
|
||||
|
||||
scope :valid, -> { where(status: "pending").where("expires_at > ?", Time.current) }
|
||||
scope :expired, -> { where("expires_at <= ?", Time.current) }
|
||||
|
||||
# Find a device code by its plaintext device_code using HMAC verification.
|
||||
def self.find_by_plaintext_device_code(plaintext_device_code)
|
||||
return nil if plaintext_device_code.blank?
|
||||
|
||||
find_by(device_code_hmac: compute_device_code_hmac(plaintext_device_code))
|
||||
end
|
||||
|
||||
# Look up a device code by the human-typed user_code. Normalizes case and
|
||||
# strips separators/whitespace so "wdjb-mjht" and "WDJB MJHT" both match.
|
||||
def self.find_by_user_code(user_code)
|
||||
return nil if user_code.blank?
|
||||
|
||||
find_by(user_code: normalize_user_code(user_code))
|
||||
end
|
||||
|
||||
def self.normalize_user_code(user_code)
|
||||
user_code.to_s.upcase.gsub(/[^A-Z0-9]/, "")
|
||||
end
|
||||
|
||||
def self.compute_device_code_hmac(plaintext_device_code)
|
||||
OpenSSL::HMAC.hexdigest("SHA256", TokenHmac::KEY, plaintext_device_code)
|
||||
end
|
||||
|
||||
def expired?
|
||||
expires_at <= Time.current
|
||||
end
|
||||
|
||||
def pending?
|
||||
status == "pending"
|
||||
end
|
||||
|
||||
def approved?
|
||||
status == "approved"
|
||||
end
|
||||
|
||||
def denied?
|
||||
status == "denied"
|
||||
end
|
||||
|
||||
def uses_pkce?
|
||||
code_challenge.present?
|
||||
end
|
||||
|
||||
# Grant the request: attach the approving user and capture their auth context.
|
||||
def approve!(user:, acr:, auth_time:)
|
||||
update!(status: "approved", user: user, acr: acr, auth_time: auth_time)
|
||||
end
|
||||
|
||||
def deny!
|
||||
update!(status: "denied")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def generate_device_code
|
||||
self.plaintext_device_code ||= SecureRandom.urlsafe_base64(48)
|
||||
self.device_code_hmac ||= self.class.compute_device_code_hmac(plaintext_device_code)
|
||||
end
|
||||
|
||||
def generate_user_code
|
||||
self.user_code ||= USER_CODE_GROUPS.times.map do
|
||||
USER_CODE_GROUP_SIZE.times.map { USER_CODE_ALPHABET.sample }.join
|
||||
end.join
|
||||
end
|
||||
|
||||
def set_expiry
|
||||
self.expires_at ||= 10.minutes.from_now
|
||||
end
|
||||
|
||||
def validate_code_challenge_format
|
||||
# PKCE code challenge should be base64url-encoded, 43-128 characters.
|
||||
unless code_challenge.match?(/\A[A-Za-z0-9\-_]{43,128}\z/)
|
||||
errors.add(:code_challenge, "must be 43-128 characters of base64url encoding")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,25 @@
|
||||
# Small persisted key/value store for runtime-togglable configuration that an
|
||||
# admin can flip from the UI without a redeploy (e.g. the dynamic client
|
||||
# registration window). Values are stored as strings; use the typed helpers.
|
||||
class Setting < ApplicationRecord
|
||||
validates :key, presence: true, uniqueness: true
|
||||
|
||||
def self.get(key)
|
||||
find_by(key: key.to_s)&.value
|
||||
end
|
||||
|
||||
def self.set(key, value)
|
||||
record = find_or_initialize_by(key: key.to_s)
|
||||
record.value = value.to_s
|
||||
record.save!
|
||||
value
|
||||
end
|
||||
|
||||
# Returns nil if the key has never been set, so callers can distinguish
|
||||
# "unset" (fall back to a default) from an explicit false.
|
||||
def self.boolean(key)
|
||||
raw = get(key)
|
||||
return nil if raw.nil?
|
||||
ActiveModel::Type::Boolean.new.cast(raw)
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user