discourse/app/services/user_api_key/expiry.rb
Sam 5458a5f150
FEATURE: User API key device authorization flow (#40189)
Adds an OAuth-style device authorization flow for user API keys so
applications that can't open a browser (CLIs, headless tools, IoT
clients) can request a key by displaying a short user-facing code.

The client POSTs to `/user-api-key/device` to obtain a device code,
a user code, and a verification URL. The user visits the URL,
authenticates, confirms the application and scopes, and either
approves or denies the request. Meanwhile the client polls
`/user-api-key/device/poll` until it receives the encrypted key
payload, a denial, or expiry.

The flow is implemented as a `UserApiKey::DeviceAuth` namespace of
service objects (`CreateRequest`, `Authorize`, `Deny`, `Poll`,
`Store`, `Crypto`, `ApprovalTokenStore`, `GrantPresenter`). Pending
grants live in Redis with a short TTL and are rate limited per IP
and per user code. Encrypted payload generation is shared with the
existing redirect-based flow.

Also adds first-class expiration for user API keys:

- New `expires_at` column on `user_api_keys`.
- New `max_user_api_key_expiry_days` site setting (default 365).
- Clients can request a key lifetime via `expires_in_seconds`, which
  is surfaced to the user on the authorization screen and serialized
  back to the client.
- A `user_api_key` rake task for listing, inspecting, expiring, and
  revoking keys from the console.

---------

Co-authored-by: Penar Musaraj <pmusaraj@gmail.com>
2026-06-10 16:09:44 -04:00

29 lines
850 B
Ruby
Vendored

# frozen_string_literal: true
class UserApiKey::Expiry
MAX_EXPIRES_IN_SECONDS_DIGITS = 10
def self.parse_seconds!(value)
return if value.blank?
value = value.to_s
if value.bytesize > MAX_EXPIRES_IN_SECONDS_DIGITS || !value.match?(/\A\d+\z/)
raise Discourse::InvalidParameters.new(:expires_in_seconds)
end
seconds = Integer(value, 10)
max_seconds = SiteSetting.max_user_api_key_expiry_days.to_i.days.to_i
if seconds <= 0 || max_seconds <= 0 || seconds > max_seconds
raise Discourse::InvalidParameters.new(:expires_in_seconds)
end
seconds
rescue ArgumentError, TypeError
raise Discourse::InvalidParameters.new(:expires_in_seconds)
end
def self.requested_expires_at(expires_in_seconds)
expires_in_seconds.present? ? Time.zone.now + expires_in_seconds.to_i.seconds : nil
end
end