A platform for community discussion. Free, open, simple.
SECURITY: Enforce API key path restrictions (#43875)
Sam8a02a2cc9d62
diff --git a/app/controllers/admin/api_controller.rb b/app/controllers/admin/api_controller.rbindex 2648e85d8d8..6aa0f752f0e 100644--- a/app/controllers/admin/api_controller.rb+++ b/app/controllers/admin/api_controller.rb@@ -43,7 +43,7 @@ class Admin::ApiController < Admin::AdminControllerscope_id: "#{resource}:#{k}",key: k,name: k.to_s.gsub("_", " "),- params: v[:params],+ params: ApiKeyScope.restrictable_parameters(v),urls: v[:urls],}end@@ -130,7 +130,8 @@ class Admin::ApiController < Admin::AdminControllerApiKeyScope.new(resource: resource,action: action,- allowed_parameters: build_params(scope_params, mapping[:params]),+ allowed_parameters:+ build_params(scope_params, ApiKeyScope.restrictable_parameters(mapping)),)endenddiff --git a/app/models/api_key_scope.rb b/app/models/api_key_scope.rbindex cc65b12cacf..46fa6875fcd 100644--- a/app/models/api_key_scope.rb+++ b/app/models/api_key_scope.rb@@ -29,17 +29,23 @@ class ApiKeyScope < ActiveRecord::Base},update: {actions: %w[topics#update topics#status],- params: %i[topic_id category_id],+ params: %i[category_id],+ path_params: %i[topic_id],},delete: {actions: %w[topics#destroy],+ path_params: %i[topic_id],+ aliases: {+ topic_id: :id,+ },},recover: {actions: %w[topics#recover],+ path_params: %i[topic_id],},read: {actions: %w[topics#show topics#feed topics#posts topics#show_by_external_id],- params: %i[topic_id external_id],+ path_params: %i[topic_id external_id],aliases: {topic_id: :id,},@@ -53,23 +59,26 @@ class ApiKeyScope < ActiveRecord::Base},status: {actions: %w[topics#status],- params: %i[topic_id category_id status enabled],+ params: %i[category_id status enabled],+ path_params: %i[topic_id],},change_owner: {actions: %w[topics#change_post_owners],- params: %i[topic_id],+ path_params: %i[topic_id],},},posts: {edit: {actions: %w[posts#update],- params: %i[id],+ path_params: %i[id],},delete: {actions: %w[posts#destroy],+ path_params: %i[id],},recover: {actions: %w[posts#recover],+ path_params: %i[post_id],},list: {actions: %w[posts#latest],@@ -78,15 +87,15 @@ class ApiKeyScope < ActiveRecord::Baserevisions: {read: {actions: %w[posts#latest_revision posts#revisions],- params: %i[post_id],+ path_params: %i[post_id],},modify: {actions: %w[posts#hide_revision posts#show_revision posts#revert],- params: %i[post_id],+ path_params: %i[post_id],},permanently_delete: {actions: %w[posts#permanently_delete_revisions],- params: %i[post_id],+ path_params: %i[post_id],},},tags: {@@ -100,14 +109,14 @@ class ApiKeyScope < ActiveRecord::Base},show: {actions: %w[tag_groups#show],- params: %i[id],+ path_params: %i[id],},create: {actions: %w[tag_groups#create],},update: {actions: %w[tag_groups#update],- params: %i[id],+ path_params: %i[id],},},categories: {@@ -116,7 +125,7 @@ class ApiKeyScope < ActiveRecord::Base},show: {actions: %w[categories#show],- params: %i[id],+ path_params: %i[id],},},uploads: {@@ -135,7 +144,7 @@ class ApiKeyScope < ActiveRecord::Baseusers: {bookmarks: {actions: %w[users#bookmarks],- params: %i[username],+ path_params: %i[username],},sync_sso: {actions: %w[admin/users#sync_sso],@@ -143,11 +152,11 @@ class ApiKeyScope < ActiveRecord::Base},show: {actions: %w[users#show],- params: %i[username external_id external_provider],+ path_params: %i[username external_id external_provider],},check_emails: {actions: %w[users#check_emails],- params: %i[username],+ path_params: %i[username],},create: {actions: %w[users#create],@@ -161,19 +170,23 @@ class ApiKeyScope < ActiveRecord::Baseusers#feature_topicusers#clear_featured_topic],- params: %i[username],+ path_params: %i[username],},log_out: {actions: %w[admin/users#log_out],+ path_params: %i[user_id],},anonymize: {actions: %w[admin/users#anonymize],+ path_params: %i[user_id],},suspend: {actions: %w[admin/users#suspend],+ path_params: %i[user_id],},delete: {actions: %w[admin/users#destroy],+ path_params: %i[id],},list: {actions: %w[admin/users#index],@@ -206,16 +219,19 @@ class ApiKeyScope < ActiveRecord::Base},show: {actions: %w[badges#show],+ path_params: %i[id],},update: {actions: %w[admin/badges#update],+ path_params: %i[id],},delete: {actions: %w[admin/badges#destroy],+ path_params: %i[id],},list_user_badges: {actions: %w[user_badges#username],- params: %i[username],+ path_params: %i[username],},assign_badge_to_user: {actions: %w[user_badges#create],@@ -223,12 +239,13 @@ class ApiKeyScope < ActiveRecord::Base},revoke_badge_from_user: {actions: %w[user_badges#destroy],+ path_params: %i[id],},},groups: {manage_groups: {actions: %w[groups#members groups#add_members groups#remove_member],- params: %i[id],+ path_params: %i[id name],},administer_groups: {actions: %w[@@ -238,6 +255,7 @@ class ApiKeyScope < ActiveRecord::Basegroups#updategroups#index],+ path_params: %i[id name],},},search: {@@ -275,6 +293,12 @@ class ApiKeyScope < ActiveRecord::Base@default_mappings = mappingsend+ def restrictable_parameters(mapping)+ (+ Array(mapping&.dig(:params)).map(&:to_sym) | Array(mapping&.dig(:path_params)).map(&:to_sym)+ ).presence+ end+def scope_mappingsplugin_mappings = DiscoursePluginRegistry.api_key_scope_mappingsreturn default_mappings if plugin_mappings.empty?diff --git a/app/serializers/api_key_scope_serializer.rb b/app/serializers/api_key_scope_serializer.rbindex a677ab71125..c27388bf693 100644--- a/app/serializers/api_key_scope_serializer.rb+++ b/app/serializers/api_key_scope_serializer.rb@@ -4,7 +4,8 @@ class ApiKeyScopeSerializer < ApplicationSerializerattributes :resource, :action, :parameters, :urls, :allowed_parameters, :keydef parameters- ApiKeyScope.scope_mappings.dig(object.resource.to_sym, object.action.to_sym)&.dig(:params).to_a+ mapping = ApiKeyScope.scope_mappings.dig(object.resource.to_sym, object.action.to_sym)+ ApiKeyScope.restrictable_parameters(mapping).to_aenddef urlsdiff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rbindex 86e4bd50898..170168fd4e1 100644--- a/lib/plugin/instance.rb+++ b/lib/plugin/instance.rb@@ -1063,10 +1063,18 @@ class Plugin::Instance# Register a new API key scope.## Example:- # add_api_key_scope(:groups, { delete: { actions: %w[groups#add_members], params: %i[id] } })+ # add_api_key_scope(+ # :groups,+ # { delete: { actions: %w[groups#remove_member], path_params: %i[id] } },+ # )+ #+ # Use path_params for resource identifiers selected by the Rails route, and params for intentional+ # query or body restrictions. Query and body values cannot satisfy path_params. Aliases are only+ # for route parameters containing the same literal identifier. All configured restrictions in one+ # scope row must match; use separate rows for alternate identifier systems.#- # This scope lets you add members to a group. Additionally, you can specify which group ids are allowed.- # The delete action is added to the groups resource.+ # This scope lets you remove members from a group. Additionally, you can specify which group ids+ # are allowed. Registering an existing resource and action replaces conflicting mapping arrays.def add_api_key_scope(resource, action)DiscoursePluginRegistry.register_api_key_scope_mapping({ resource => action }, self)enddiff --git a/lib/route_matcher.rb b/lib/route_matcher.rbindex a97e2fe6dc7..a39e0035e44 100644--- a/lib/route_matcher.rb+++ b/lib/route_matcher.rb@@ -3,11 +3,12 @@class RouteMatcherPATH_PARAMETERS = "_DISCOURSE_REQUEST_PATH_PARAMETERS"- attr_reader :actions, :params, :methods, :aliases, :formats, :allowed_param_values+ attr_reader :actions, :params, :path_params, :methods, :aliases, :formats, :allowed_param_valuesdef initialize(actions: nil,params: nil,+ path_params: nil,methods: nil,formats: nil,aliases: nil,@@ -15,6 +16,7 @@ class RouteMatcher)@actions = Array(actions) if actions@params = Array(params) if params+ @path_params = Array(path_params) if path_params@methods = Array(methods) if methods@formats = Array(formats) if formats@aliases = aliases@@ -26,6 +28,7 @@ class RouteMatcherRouteMatcher.new(actions: actions,params: params,+ path_params: path_params,methods: methods,formats: formats,aliases: aliases,@@ -51,17 +54,24 @@ class RouteMatcher# logster is not a rails route, special handlingreturn true if actions.include?(Logster::Web) && request.fullpath =~ %r{\A/logs/.*\.json\z}- path_params = path_params_from_request(request)- actions.include? "#{path_params[:controller]}##{path_params[:action]}"+ recognized_params = path_params_from_request(request)+ actions.include? "#{recognized_params[:controller]}##{recognized_params[:action]}"enddef params_allowed?(request)- return true if params.nil? || allowed_param_values.blank? # params are unrestricted+ return true if allowed_param_values.blank?++ ordinary_params = Array(params).map(&:to_sym) - Array(path_params).map(&:to_sym)+ ordinary_params_allowed?(request, ordinary_params) && path_params_allowed?(request)+ end++ def ordinary_params_allowed?(request, ordinary_params)+ return true if ordinary_params.empty?requested_params = request.parameters- params.all? do |param|- param_alias = aliases&.[](param)+ ordinary_params.all? do |param|+ param_alias = param_alias_for(param)allowed_values = [allowed_param_values.fetch(param.to_s, [])].flattenvalue = requested_params[param.to_s]@@ -76,9 +86,56 @@ class RouteMatcherendend+ def path_params_allowed?(request)+ return true if path_params.nil?++ requested_params = path_params_from_request(request)++ path_params.all? do |param|+ allowed_values = [allowed_param_values.fetch(param.to_s, [])].flatten+ next true if allowed_values.blank?++ param_alias = param_alias_for(param)+ value_present, value = path_parameter(requested_params, param)+ alias_present, alias_value = path_parameter(requested_params, param_alias)++ next false if value_present && alias_present+ next false unless value_present || alias_present++ requested_value = value_present ? value : alias_value+ scalar_path_value?(requested_value) && allowed_values.include?(requested_value)+ end+ end++ def param_alias_for(param)+ aliases&.[](param) || aliases&.[](param.to_s) || aliases&.[](param.to_sym)+ end++ def path_parameter(requested_params, param)+ return false, nil if param.nil?++ string_key = param.to_s+ if requested_params.key?(string_key)+ value = requested_params[string_key]+ return true, value unless value.nil?+ end++ symbol_key = param.to_sym+ if requested_params.key?(symbol_key)+ value = requested_params[symbol_key]+ return true, value unless value.nil?+ end+ [false, nil]+ end++ def scalar_path_value?(value)+ value.is_a?(String) || value.is_a?(Symbol) || value.is_a?(Numeric) || value == true ||+ value == false+ end+def extract_category_id(category_slug_with_id)- parts = category_slug_with_id.split("/")- !parts.empty? && parts.last =~ /\A\d+\Z/ ? parts.pop : nil+ parts = category_slug_with_id&.split("/")+ parts.present? && parts.last.match?(/\A\d+\Z/) ? parts.pop : nilenddef method_allowed?(request)@@ -94,18 +151,12 @@ class RouteMatcherenddef path_params_from_request(request)- if request.env[ActionDispatch::Http::Parameters::PARAMETERS_KEY].nil?- # We need to manually recognize the path when Rails hasn't done that yet. That can happen when- # the matcher gets called in a Middleware before the controller did its work.- # We store the result of `recognize_path` in a custom env key, so that we don't change- # some Rails behavior by accident.- request.env[PATH_PARAMETERS] ||= begin- Rails.application.routes.recognize_path(request.path_info, method: request.request_method)- rescue ActionController::RoutingError- {}- end- end+ return request.path_parameters if request.path_parameters.present?- request.path_parameters.presence || request.env[PATH_PARAMETERS] || {}+ request.env[PATH_PARAMETERS] ||= begin+ Rails.application.routes.recognize_path(request.path_info, method: request.request_method)+ rescue ActionController::RoutingError+ {}+ endendenddiff --git a/plugins/automation/plugin.rb b/plugins/automation/plugin.rbindex 64db25469e4..6883320a7db 100644--- a/plugins/automation/plugin.rb+++ b/plugins/automation/plugin.rb@@ -120,6 +120,7 @@ after_initialize dotrigger_automation: {actions: %w[discourse_automation/automations#trigger],params: %i[context],+ path_params: %i[id],formats: :json,},},diff --git a/plugins/automation/spec/requests/discourse_automation_automations_spec.rb b/plugins/automation/spec/requests/discourse_automation_automations_spec.rbindex 208d28b0a84..0c8863a3607 100644--- a/plugins/automation/spec/requests/discourse_automation_automations_spec.rb+++ b/plugins/automation/spec/requests/discourse_automation_automations_spec.rb@@ -55,6 +55,18 @@ describe DiscourseAutomation::AdminAutomationsController dolet(:admin) { Fabricate(:admin) }let(:api_key) { Fabricate(:api_key, user: admin) }+ let(:restricted_api_key) do+ Fabricate(:api_key, user: admin).tap do |key|+ ApiKeyScope.create!(+ api_key_id: key.id,+ resource: "automation",+ action: "trigger_automation",+ allowed_parameters: {+ "id" => [automation.id.to_s],+ },+ )+ end+ endit "enqueues the automation trigger with an admin API key" dopost "/automations/#{automation.id}/trigger.json",@@ -70,6 +82,33 @@ describe DiscourseAutomation::AdminAutomationsController doexpect(response.status).to eq(200)expect(Jobs::DiscourseAutomation::Trigger.jobs.size).to eq(1)end++ it "enforces the automation ID from the path" do+ other_automation = Fabricate(:automation)++ post "/automations/#{automation.id}/trigger.json",+ params: {+ context: {+ foo: :bar,+ },+ },+ headers: {+ HTTP_API_KEY: restricted_api_key.key,+ }+ expect(response.status).to eq(200)++ post "/automations/#{other_automation.id}/trigger.json",+ params: {+ id: automation.id,+ context: {+ foo: :bar,+ },+ },+ headers: {+ HTTP_API_KEY: restricted_api_key.key,+ }+ expect(response.status).to eq(404)+ endendenddiff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rbindex 5c70dec0ae0..b9c2ef6a088 100644--- a/plugins/chat/plugin.rb+++ b/plugins/chat/plugin.rb@@ -587,7 +587,7 @@ after_initialize do{create_message: {actions: %w[chat/api/channel_messages#create],- params: %i[chat_channel_id],+ path_params: %i[chat_channel_id],},},)diff --git a/plugins/chat/spec/integration/custom_api_key_scopes_spec.rb b/plugins/chat/spec/integration/custom_api_key_scopes_spec.rbindex 56487dfbd4e..bcff01fe796 100644--- a/plugins/chat/spec/integration/custom_api_key_scopes_spec.rb+++ b/plugins/chat/spec/integration/custom_api_key_scopes_spec.rb@@ -65,6 +65,7 @@ describe "API keys scoped to chat#create_message" do"Api-Username" => admin.username,},params: {+ chat_channel_id: chat_channel_2.id,message: "asdfasdf asdfasdf",}}.not_to change { Chat::Message.where(chat_channel: chat_channel).count }diff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rbindex 3120df2f31b..364d1629c3e 100644--- a/plugins/discourse-ai/plugin.rb+++ b/plugins/discourse-ai/plugin.rb@@ -227,7 +227,10 @@ after_initialize doDiscourseAi::PostImageCaptions.remove_existing_caption_metadata(doc)end- add_api_key_scope(:ai, { update_agents: { actions: %w[discourse_ai/admin/ai_agents#update] } })+ add_api_key_scope(+ :ai,+ { update_agents: { actions: %w[discourse_ai/admin/ai_agents#update], path_params: %i[id] } },+ )add_api_key_scope(:ai,@@ -240,6 +243,7 @@ after_initialize dodiscourse_ai/admin/ai_artifacts#updatediscourse_ai/admin/ai_artifacts#destroy],+ path_params: %i[id],},},)diff --git a/plugins/discourse-ai/spec/integration/custom_api_key_scopes_spec.rb b/plugins/discourse-ai/spec/integration/custom_api_key_scopes_spec.rbindex a205ecb22bc..d5a5422f2ac 100644--- a/plugins/discourse-ai/spec/integration/custom_api_key_scopes_spec.rb+++ b/plugins/discourse-ai/spec/integration/custom_api_key_scopes_spec.rb@@ -6,6 +6,7 @@ describe "API keys scoped to ai#manage_artifacts" dofab!(:admin)fab!(:topic_post, :post)fab!(:ai_artifact)+ fab!(:other_ai_artifact, :ai_artifact)let(:api_key) dokey = ApiKey.create!@@ -13,7 +14,23 @@ describe "API keys scoped to ai#manage_artifacts" dokeyend+ let(:restricted_api_key) do+ key = ApiKey.create!+ ApiKeyScope.create!(+ resource: "ai",+ action: "manage_artifacts",+ api_key_id: key.id,+ allowed_parameters: {+ "id" => [ai_artifact.id.to_s],+ },+ )+ key+ end+let(:headers) { { "Api-Key" => api_key.key, "Api-Username" => admin.username } }+ let(:restricted_headers) do+ { "Api-Key" => restricted_api_key.key, "Api-Username" => admin.username }+ endit "can list artifacts" doget "/admin/plugins/discourse-ai/ai-artifacts.json", headers: headers@@ -55,6 +72,22 @@ describe "API keys scoped to ai#manage_artifacts" doexpect(response.status).to eq(204)end+ it "enforces artifact IDs from the path and denies collection routes when restricted" do+ get "/admin/plugins/discourse-ai/ai-artifacts/#{ai_artifact.id}.json",+ headers: restricted_headers+ expect(response.status).to eq(200)++ get "/admin/plugins/discourse-ai/ai-artifacts/#{other_ai_artifact.id}.json",+ headers: restricted_headers,+ params: {+ id: ai_artifact.id,+ }+ expect(response.status).to eq(404)++ get "/admin/plugins/discourse-ai/ai-artifacts.json", headers: restricted_headers+ expect(response.status).to eq(404)+ end+it "cannot access unrelated endpoints" doget "/latest.json", headers: headersexpect(response.status).to eq(403)diff --git a/plugins/discourse-data-explorer/plugin.rb b/plugins/discourse-data-explorer/plugin.rbindex ad9c1159e7a..8a7f7fdeac1 100644--- a/plugins/discourse-data-explorer/plugin.rb+++ b/plugins/discourse-data-explorer/plugin.rb@@ -82,7 +82,7 @@ after_initialize do{run_queries: {actions: %w[discourse_data_explorer/query#run discourse_data_explorer/query#public_run],- params: %i[id],+ path_params: %i[id],},},)diff --git a/plugins/discourse-data-explorer/spec/integration/custom_api_key_scopes_spec.rb b/plugins/discourse-data-explorer/spec/integration/custom_api_key_scopes_spec.rbindex 4883cd9e6bc..90c9372c017 100644--- a/plugins/discourse-data-explorer/spec/integration/custom_api_key_scopes_spec.rb+++ b/plugins/discourse-data-explorer/spec/integration/custom_api_key_scopes_spec.rb@@ -77,6 +77,9 @@ describe "API keys scoped to query#run" doheaders: {"Api-Key" => single_query_api_key.key,"Api-Username" => admin.username,+ },+ params: {+ id: query1.id,}}.not_to change { query2.reload.last_run_at }expect(response.status).to eq(403)diff --git a/spec/lib/plugin/instance_spec.rb b/spec/lib/plugin/instance_spec.rbindex a96e0762516..e89a33a72d3 100644--- a/spec/lib/plugin/instance_spec.rb+++ b/spec/lib/plugin/instance_spec.rb@@ -845,6 +845,21 @@ TEXT*actions,)end++ it "retains path parameters and replaces conflicting mapping arrays" do+ plugin_instance.add_api_key_scope(+ :topics,+ read: {+ actions: %w[topics#show],+ path_params: %i[topic_id],+ },+ )++ mapping = ApiKeyScope.scope_mappings.dig(:topics, :read)++ expect(mapping[:actions]).to eq(%w[topics#show])+ expect(mapping[:path_params]).to eq(%i[topic_id])+ endenddescribe "#add_directory_column" dodiff --git a/spec/lib/route_matcher_spec.rb b/spec/lib/route_matcher_spec.rbnew file mode 100644index 00000000000..5b0b8b7c2ff--- /dev/null+++ b/spec/lib/route_matcher_spec.rb@@ -0,0 +1,244 @@+# frozen_string_literal: true++RSpec.describe RouteMatcher do+ def request_env(path_parameters:, query_parameters: {}, request_method: "GET")+ ActionDispatch::TestRequest+ .create+ .tap do |request|+ request.path_parameters = path_parameters+ request.set_header(+ "action_dispatch.request.query_parameters",+ query_parameters.stringify_keys,+ )+ request.request_method = request_method+ end+ .env+ end++ describe "#match?" do+ it "preserves merged request semantics for ordinary parameters" do+ matcher =+ described_class.new(params: %i[status], allowed_param_values: { "status" => ["open"] })+ env = request_env(path_parameters: {}, query_parameters: { status: "open" })++ expect(matcher.match?(env: env)).to eq(true)+ end++ it "matches only recognized values for path parameters" do+ matcher =+ described_class.new(+ path_params: %i[topic_id],+ allowed_param_values: {+ "topic_id" => %w[3 4],+ },+ )++ expect(matcher.match?(env: request_env(path_parameters: { topic_id: "3" }))).to eq(true)+ expect(matcher.match?(env: request_env(path_parameters: { topic_id: "5" }))).to eq(false)+ expect(+ matcher.match?(env: request_env(path_parameters: {}, query_parameters: { topic_id: "3" })),+ ).to eq(false)+ end++ it "does not let query parameters override a recognized path value" do+ matcher =+ described_class.new(+ path_params: %i[topic_id],+ allowed_param_values: {+ "topic_id" => ["3"],+ },+ )+ env = request_env(path_parameters: { topic_id: "4" }, query_parameters: { topic_id: "3" })++ expect(matcher.match?(env: env)).to eq(false)+ end++ it "uses aliases only when they are recognized path parameters" do+ matcher =+ described_class.new(+ path_params: %i[topic_id],+ aliases: {+ topic_id: :id,+ },+ allowed_param_values: {+ "topic_id" => ["3"],+ },+ )++ expect(matcher.match?(env: request_env(path_parameters: { id: "3" }))).to eq(true)+ expect(+ matcher.match?(env: request_env(path_parameters: {}, query_parameters: { id: "3" })),+ ).to eq(false)+ end++ it "treats nil canonical values as absent when an alias is recognized" do+ matcher =+ described_class.new(+ path_params: %w[topic_id],+ aliases: {+ "topic_id" => :id,+ },+ allowed_param_values: {+ "topic_id" => ["3"],+ },+ )+ env = request_env(path_parameters: { "topic_id" => nil, :id => "3" })++ expect(matcher.match?(env: env)).to eq(true)+ end++ it "rejects ambiguous recognized aliases" do+ matcher =+ described_class.new(+ path_params: %i[topic_id],+ aliases: {+ topic_id: :id,+ },+ allowed_param_values: {+ "topic_id" => ["3"],+ },+ )+ env = request_env(path_parameters: { topic_id: "3", id: "3" })++ expect(matcher.match?(env: env)).to eq(false)+ end++ it "requires every configured path restriction" do+ matcher =+ described_class.new(+ path_params: %i[topic_id external_id],+ allowed_param_values: {+ "topic_id" => ["3"],+ "external_id" => ["external-3"],+ },+ )++ expect(matcher.match?(env: request_env(path_parameters: { topic_id: "3" }))).to eq(false)+ end++ it "keeps blank path allowlists unrestricted" do+ matcher =+ described_class.new(+ path_params: %i[topic_id external_id],+ allowed_param_values: {+ "topic_id" => ["3"],+ "external_id" => [],+ },+ )++ expect(matcher.match?(env: request_env(path_parameters: { topic_id: "3" }))).to eq(true)+ end++ it "requires ordinary and path restrictions together" do+ matcher =+ described_class.new(+ params: %i[status],+ path_params: %i[topic_id],+ allowed_param_values: {+ "status" => ["open"],+ "topic_id" => ["3"],+ },+ )++ expect(+ matcher.match?(+ env:+ request_env(path_parameters: { topic_id: "3" }, query_parameters: { status: "closed" }),+ ),+ ).to eq(false)+ end++ it "gives path semantics precedence for overlapping declarations" do+ matcher =+ described_class.new(+ params: %w[topic_id],+ path_params: %i[topic_id],+ allowed_param_values: {+ "topic_id" => ["3"],+ },+ )+ env = request_env(path_parameters: { topic_id: "4" }, query_parameters: { topic_id: "3" })++ expect(matcher.match?(env: env)).to eq(false)+ end++ it "matches exact scalar types and rejects structured path values" do+ matcher = described_class.new(path_params: %i[id], allowed_param_values: { "id" => [3, "4"] })++ expect(matcher.match?(env: request_env(path_parameters: { id: 3 }))).to eq(true)+ expect(matcher.match?(env: request_env(path_parameters: { id: "3" }))).to eq(false)+ expect(matcher.match?(env: request_env(path_parameters: { id: [3] }))).to eq(false)+ expect(matcher.match?(env: request_env(path_parameters: { id: { value: 3 } }))).to eq(false)+ end++ it "preserves path parameters when allowed values are replaced" do+ matcher = described_class.new(path_params: %i[id])++ replacement = matcher.with_allowed_param_values("id" => ["3"])++ expect(replacement.path_params).to eq([:id])+ expect(replacement.match?(env: request_env(path_parameters: { id: "3" }))).to eq(true)+ end++ it "recognizes and caches routes before controller dispatch" do+ request = ActionDispatch::TestRequest.create+ request.set_header("PATH_INFO", "/t/3.json")+ request.request_method = "GET"+ matcher =+ described_class.new(+ actions: %w[topics#show],+ path_params: %i[topic_id],+ aliases: {+ topic_id: :id,+ },+ allowed_param_values: {+ "topic_id" => ["3"],+ },+ )++ expect(matcher.match?(env: request.env)).to eq(true)+ expect(request.env[described_class::PATH_PARAMETERS]).to include(+ controller: "topics",+ action: "show",+ id: "3",+ )+ end++ it "recognizes routes after ordinary parameters are loaded when actions are unrestricted" do+ request = ActionDispatch::TestRequest.create+ request.set_header("PATH_INFO", "/t/3.json")+ request.set_header("action_dispatch.request.query_parameters", { "status" => "open" })+ request.request_method = "GET"+ matcher =+ described_class.new(+ params: %i[status],+ path_params: %i[topic_id],+ aliases: {+ topic_id: :id,+ },+ allowed_param_values: {+ "status" => ["open"],+ "topic_id" => ["3"],+ },+ )++ expect(matcher.match?(env: request.env)).to eq(true)+ expect(request.env[described_class::PATH_PARAMETERS]).to include(id: "3")+ end++ it "handles a missing ordinary category alias value" do+ matcher =+ described_class.new(+ params: %i[category_id],+ aliases: {+ category_id: :category_slug_path_with_id,+ },+ allowed_param_values: {+ "category_id" => ["3"],+ },+ )++ expect(matcher.match?(env: request_env(path_parameters: {}))).to eq(false)+ end+ end+enddiff --git a/spec/models/api_key_scope_spec.rb b/spec/models/api_key_scope_spec.rbindex 81f81026c18..7c8568d410d 100644--- a/spec/models/api_key_scope_spec.rb+++ b/spec/models/api_key_scope_spec.rb@@ -16,6 +16,21 @@ RSpec.describe ApiKeyScope doendend+ describe ".restrictable_parameters" do+ it "returns ordinary parameters followed by deduplicated path parameters" do+ mapping = { params: %w[status topic_id], path_params: %i[topic_id external_id] }++ expect(described_class.restrictable_parameters(mapping)).to eq(+ %i[status topic_id external_id],+ )+ end++ it "returns nil when a mapping has no restrictable parameters" do+ expect(described_class.restrictable_parameters({ actions: %w[topics#show] })).to be_nil+ expect(described_class.restrictable_parameters(nil)).to be_nil+ end+ end+describe ".scope_mappings" doit "does not define a granular scope for about requests" doexpect(described_class.scope_mappings).not_to have_key(:about)diff --git a/spec/models/api_key_spec.rb b/spec/models/api_key_spec.rbindex a58d8f4f697..bd7b517de42 100644--- a/spec/models/api_key_spec.rb+++ b/spec/models/api_key_spec.rb@@ -178,6 +178,39 @@ RSpec.describe ApiKey doexpect(key.request_allowed?(env)).to eq(true)end+ it "rejects query parameters that try to satisfy a path restriction" do+ request.path_parameters = { controller: "topics", action: "show", topic_id: "4" }+ request.set_header("action_dispatch.request.query_parameters", { "topic_id" => "3" })++ expect(key.request_allowed?(env)).to eq(false)+ end++ it "allows separate scope rows to match alternate route selectors" do+ key.api_key_scopes = [+ scope,+ ApiKeyScope.new(+ resource: "topics",+ action: "read",+ allowed_parameters: {+ external_id: "external-3",+ },+ ),+ ]+ request.path_parameters = {+ controller: "topics",+ action: "show_by_external_id",+ external_id: "external-3",+ }++ expect(key.request_allowed?(env)).to eq(true)+ end++ it "rejects a row when a configured path selector is missing" do+ scope.allowed_parameters = { topic_id: "3", external_id: "external-3" }++ expect(key.request_allowed?(env)).to eq(false)+ end+it "allow the request when the scope has an alias" dorequest.path_parameters = { controller: "topics", action: "show", id: "3" }expect(key.request_allowed?(env)).to eq(true)diff --git a/spec/requests/admin/api_controller_spec.rb b/spec/requests/admin/api_controller_spec.rbindex 7f73832924a..2a96799466d 100644--- a/spec/requests/admin/api_controller_spec.rb+++ b/spec/requests/admin/api_controller_spec.rb@@ -305,6 +305,23 @@ RSpec.describe Admin::ApiController doexpect(scope.allowed_parameters["topic_id"]).to contain_exactly("55")end+ it "creates a scope with allowed path parameters" do+ post "/admin/api/keys.json",+ params: {+ key: {+ description: "path restricted key",+ scopes: [{ scope_id: "topics:delete", topic_id: "55" }],+ },+ }++ expect(response.status).to eq(200)+ scope = ApiKeyScope.find_by(api_key_id: response.parsed_body.dig("key", "id"))+ serialized_scope = response.parsed_body.dig("key", "api_key_scopes", 0)++ expect(scope.allowed_parameters).to eq("topic_id" => ["55"])+ expect(serialized_scope["parameters"]).to eq(["topic_id"])+ end+it "creates an scope for /logs" dopost "/admin/api/keys.json",params: {@@ -320,6 +337,7 @@ RSpec.describe Admin::ApiController doexpect(scope.resource).to eq("logs")expect(scope.action).to eq("messages")+ expect(data.dig("key", "api_key_scopes", 0, "parameters")).to eq([])api_key = data.dig("key", "key")post "/logs/messages.json", headers: { "Api-Key": api_key, "Api-Username": "system" }@@ -480,6 +498,17 @@ RSpec.describe Admin::ApiController do"logs",)+ topic_delete_scope = scopes["topics"].find { it["key"] == "delete" }+ topic_update_scope = scopes["topics"].find { it["key"] == "update" }+ topic_write_scope = scopes["topics"].find { it["key"] == "write" }+ global_read_scope = scopes["global"].find { it["key"] == "read" }++ expect(topic_delete_scope).to include("params" => ["topic_id"])+ expect(topic_update_scope).to include("params" => %w[category_id topic_id])+ expect(topic_write_scope).to include("params" => ["topic_id"])+ expect(global_read_scope).to include("params" => nil)+ expect(topic_delete_scope).not_to have_key("path_params")+topic_routes = ["/t/:id (GET)","/t/external_id/:external_id (GET)",diff --git a/spec/requests/api_key_path_scopes_spec.rb b/spec/requests/api_key_path_scopes_spec.rbnew file mode 100644index 00000000000..74682a04c4e--- /dev/null+++ b/spec/requests/api_key_path_scopes_spec.rb@@ -0,0 +1,56 @@+# frozen_string_literal: true++RSpec.describe "Path-restricted API key scopes" do+ fab!(:admin)+ fab!(:topic)+ fab!(:other_topic, :topic)++ def headers_for(api_key)+ { "Api-Key" => api_key.key, "Api-Username" => admin.username }+ end++ def topic_read_key(allowed_parameters)+ Fabricate(:api_key, user: admin).tap do |api_key|+ ApiKeyScope.create!(+ api_key_id: api_key.id,+ resource: "topics",+ action: "read",+ allowed_parameters: allowed_parameters,+ )+ end+ end++ it "uses the recognized topic path instead of an injected selector" do+ api_key = topic_read_key("topic_id" => [topic.id.to_s])++ get "/t/#{other_topic.id}/posts.json",+ headers: headers_for(api_key),+ params: {+ topic_id: topic.id,+ }++ expect(response.status).to eq(403)+ expect(response.body).not_to include(other_topic.title)+ end++ it "does not satisfy an external ID restriction on a numeric topic route" do+ api_key = topic_read_key("external_id" => ["allowed-external-id"])++ get "/t/#{topic.id}/posts.json",+ headers: headers_for(api_key),+ params: {+ external_id: "allowed-external-id",+ }++ expect(response.status).to eq(403)+ expect(response.body).not_to include(topic.title)+ end++ it "allows a matching recognized topic path" do+ api_key = topic_read_key("topic_id" => [topic.id.to_s])++ get "/t/#{topic.id}/posts.json", headers: headers_for(api_key)++ expect(response.status).to eq(200)+ end+end