Skip to content

A platform for community discussion. Free, open, simple.

FIX: Prevent read-only keys being created without scopes (#42280)

Mark VanLandingham7c82423416d3
diff --git a/app/controllers/admin/api_controller.rb b/app/controllers/admin/api_controller.rb
index b4c36533676..2648e85d8d8 100644
--- a/app/controllers/admin/api_controller.rb
+++ b/app/controllers/admin/api_controller.rb
@@ -72,7 +72,10 @@ class Admin::ApiController < Admin::AdminController
end
def create
- api_key = ApiKey.new(update_params)
+ api_key_params = update_params
+ validate_read_only_scopes!
+
+ api_key = ApiKey.new(api_key_params)
ApiKey.transaction do
api_key.created_by = current_user
api_key.api_key_scopes = build_scopes
@@ -111,6 +114,12 @@ class Admin::ApiController < Admin::AdminController
private
+ def validate_read_only_scopes!
+ return if params.dig(:key, :scope_mode) != "read_only"
+
+ raise Discourse::InvalidParameters if params.dig(:key, :scopes).blank?
+ end
+
def build_scopes
params.require(:key)[:scopes].to_a.map do |scope_params|
resource, action = scope_params[:scope_id].split(":")
diff --git a/app/models/api_key.rb b/app/models/api_key.rb
index 325f87f92cc..a285d618b91 100644
--- a/app/models/api_key.rb
+++ b/app/models/api_key.rb
@@ -13,7 +13,7 @@ class ApiKey < ActiveRecord::Base
scope :with_key, ->(key) { where(key_hash: ApiKey.hash_key(key)) }
validates :description, length: { maximum: 255 }
- validate :at_least_one_granular_scope
+ validate :valid_scope_mode_scopes
enum :scope_mode, %i[global read_only granular].freeze
@@ -117,14 +117,21 @@ class ApiKey < ActiveRecord::Base
private
- def at_least_one_granular_scope
- if scope_mode == "granular" && api_key_scopes.empty?
+ def valid_scope_mode_scopes
+ if granular? && api_key_scopes.empty?
errors.add(
:api_key_scopes,
I18n.t("activerecord.errors.models.api_key.base.at_least_one_granular_scope"),
)
+ elsif read_only? && !valid_read_only_scope?
+ errors.add(:api_key_scopes, I18n.t("activerecord.errors.models.api_key.base.read_only_scope"))
end
end
+
+ def valid_read_only_scope?
+ api_key_scopes.size == 1 && api_key_scopes.first.resource == "global" &&
+ api_key_scopes.first.action == "read"
+ end
end
# == Schema Information
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index f73dfb99110..ad4f3421a63 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -875,6 +875,7 @@ en:
api_key:
base:
at_least_one_granular_scope: "at least one must be selected"
+ read_only_scope: "must be the global read scope"
uncategorized_category_name: "Uncategorized"
diff --git a/db/migrate/20260629210246_revoke_invalid_read_only_api_keys.rb b/db/migrate/20260629210246_revoke_invalid_read_only_api_keys.rb
new file mode 100644
index 00000000000..c3fad533f4c
--- /dev/null
+++ b/db/migrate/20260629210246_revoke_invalid_read_only_api_keys.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+class RevokeInvalidReadOnlyApiKeys < ActiveRecord::Migration[8.0]
+ def up
+ execute <<~SQL
+ UPDATE api_keys
+ SET revoked_at = CURRENT_TIMESTAMP,
+ updated_at = CURRENT_TIMESTAMP
+ WHERE scope_mode = 1
+ AND revoked_at IS NULL
+ AND NOT (
+ (
+ SELECT COUNT(*)
+ FROM api_key_scopes
+ WHERE api_key_scopes.api_key_id = api_keys.id
+ ) = 1
+ AND EXISTS (
+ SELECT 1
+ FROM api_key_scopes
+ WHERE api_key_scopes.api_key_id = api_keys.id
+ AND api_key_scopes.resource = 'global'
+ AND api_key_scopes.action = 'read'
+ )
+ )
+ SQL
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/db/structure.sql b/db/structure.sql
index e9c0d44918a..a3ca89b1716 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -23121,6 +23121,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260701013606'),
('20260630034050'),
('20260629233141'),
+('20260629210246'),
('20260629081606'),
('20260629022603'),
('20260626055145'),
diff --git a/spec/models/api_key_spec.rb b/spec/models/api_key_spec.rb
index e768b282d39..a58d8f4f697 100644
--- a/spec/models/api_key_spec.rb
+++ b/spec/models/api_key_spec.rb
@@ -18,6 +18,18 @@ RSpec.describe ApiKey do
expect(api_key.errors).to contain_exactly("Api key scopes at least one must be selected")
end
+ it "validates read-only mode uses the global read scope" do
+ api_key = ApiKey.new(scope_mode: "read_only")
+
+ expect(api_key).not_to be_valid
+
+ api_key.api_key_scopes = [ApiKeyScope.new(resource: "topics", action: "write")]
+ expect(api_key).not_to be_valid
+
+ api_key.api_key_scopes = [ApiKeyScope.new(resource: "global", action: "read")]
+ expect(api_key).to be_valid
+ end
+
it "generates a key when saving" do
api_key = ApiKey.new
api_key.save!
diff --git a/spec/requests/admin/api_controller_spec.rb b/spec/requests/admin/api_controller_spec.rb
index 04c74581214..22fa4dde570 100644
--- a/spec/requests/admin/api_controller_spec.rb
+++ b/spec/requests/admin/api_controller_spec.rb
@@ -245,6 +245,21 @@ RSpec.describe Admin::ApiController do
expect(UserHistory.last.subject).to eq(key.truncated_key)
end
+ it "rejects read-only keys without scopes" do
+ expect {
+ post "/admin/api/keys.json",
+ params: {
+ key: {
+ description: "read-only key description",
+ scope_mode: "read_only",
+ },
+ }
+ }.not_to change(ApiKey, :count)
+
+ expect(response.status).to eq(400)
+ expect(response.parsed_body["error_type"]).to eq("invalid_parameters")
+ end
+
it "can create a user-specific key" do
user = Fabricate(:user)
post "/admin/api/keys.json",