DEV: Require at least one scope for API key granular mode (#31253)

Currently, if creating an API key in "granular" mode, and not selecting any scopes, a globally scoped API key is created. This can be surprising and is not ideal. Having a key with no scopes isn't useful in the first place, so this PR adds client- and server side validations to check that at least one scope is selected if using "granular" mode.
This commit is contained in:
Ted Johansson
2025-02-10 13:22:08 +08:00
committed by GitHub
parent 7be88bbe8a
commit 3d11e3ca10
7 changed files with 55 additions and 2 deletions

View File

@ -4,6 +4,8 @@ class ApiKey < ActiveRecord::Base
class KeyAccessError < StandardError
end
attr_accessor :scope_mode
has_many :api_key_scopes
belongs_to :user
belongs_to :created_by, class_name: "User"
@ -18,6 +20,7 @@ class ApiKey < ActiveRecord::Base
end
validates :description, length: { maximum: 255 }
validate :at_least_one_granular_scope
after_initialize :generate_key
@ -114,6 +117,17 @@ class ApiKey < ActiveRecord::Base
# using update_column to avoid the AR transaction
update_column(:last_used_at, now)
end
private
def at_least_one_granular_scope
if scope_mode == "granular" && api_key_scopes.empty?
errors.add(
:api_key_scopes,
I18n.t("activerecord.errors.models.api_key.base.at_least_one_granular_scope"),
)
end
end
end
# == Schema Information