A platform for community discussion. Free, open, simple.
SECURITY: Impose a upper bound on limit params in various controllers
Alan Guo Xiang Tanbfc3132bb22b
diff --git a/app/controllers/admin/api_controller.rb b/app/controllers/admin/api_controller.rbindex 49b8a70414e..6238287c067 100644--- a/app/controllers/admin/api_controller.rb+++ b/app/controllers/admin/api_controller.rb@@ -4,9 +4,11 @@ class Admin::ApiController < Admin::AdminController# Note: in the REST API, ApiKeys are referred to simply as "key"# If we used "api_key", then our user provider would try to use the value for authentication+ INDEX_LIMIT = 50+def indexoffset = (params[:offset] || 0).to_i- limit = (params[:limit] || 50).to_i.clamp(1, 50)+ limit = fetch_limit_from_params(default: INDEX_LIMIT, max: INDEX_LIMIT)keys =ApiKeydiff --git a/app/controllers/admin/reports_controller.rb b/app/controllers/admin/reports_controller.rbindex ffa8463a9c4..ab49a29aa9d 100644--- a/app/controllers/admin/reports_controller.rb+++ b/app/controllers/admin/reports_controller.rb@@ -1,6 +1,8 @@# frozen_string_literal: trueclass Admin::ReportsController < Admin::StaffController+ REPORTS_LIMIT = 50+def indexreports_methods =["page_view_total_reqs"] +@@ -108,10 +110,7 @@ class Admin::ReportsController < Admin::StaffControllerfacets = nilfacets = report_params[:facets].map { |s| s.to_s.to_sym } if Array === report_params[:facets]- limit = nil- if report_params.has_key?(:limit) && report_params[:limit].to_i > 0- limit = report_params[:limit].to_i- end+ limit = fetch_limit_from_params(params: report_params, default: nil, max: REPORTS_LIMIT)filters = nilfilters = report_params[:filters] if report_params.has_key?(:filters)diff --git a/app/controllers/admin/staff_action_logs_controller.rb b/app/controllers/admin/staff_action_logs_controller.rbindex 69687294ca9..f419f47c5bf 100644--- a/app/controllers/admin/staff_action_logs_controller.rb+++ b/app/controllers/admin/staff_action_logs_controller.rb@@ -1,11 +1,13 @@# frozen_string_literal: trueclass Admin::StaffActionLogsController < Admin::StaffController+ INDEX_LIMIT = 200+def indexfilters = params.slice(*UserHistory.staff_filters + %i[page limit])page = (params[:page] || 0).to_i- page_size = (params[:limit] || 200).to_i.clamp(1, 200)+ page_size = fetch_limit_from_params(default: INDEX_LIMIT, max: INDEX_LIMIT)staff_action_logs = UserHistory.staff_action_records(current_user, filters)count = staff_action_logs.countdiff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rbindex c6c07482343..79c652a3fe4 100644--- a/app/controllers/application_controller.rb+++ b/app/controllers/application_controller.rb@@ -1084,4 +1084,22 @@ class ApplicationController < ActionController::Baseendendend++ def fetch_limit_from_params(params: self.params, default:, max:)+ raise "default limit cannot be greater than max limit" if default.present? && default > max++ if params.has_key?(:limit)+ limit =+ begin+ Integer(params[:limit])+ rescue ArgumentError+ raise Discourse::InvalidParameters.new(:limit)+ end++ raise Discourse::InvalidParameters.new(:limit) if limit < 0 || limit > max+ limit+ else+ default+ end+ endenddiff --git a/app/controllers/directory_items_controller.rb b/app/controllers/directory_items_controller.rbindex 2fbfcf12048..7d70b1eeae7 100644--- a/app/controllers/directory_items_controller.rb+++ b/app/controllers/directory_items_controller.rb@@ -81,8 +81,7 @@ class DirectoryItemsController < ApplicationControllerendend- limit = [params[:limit].to_i, PAGE_SIZE].min if params[:limit].to_i > 0- limit ||= PAGE_SIZE+ limit = fetch_limit_from_params(default: PAGE_SIZE, max: PAGE_SIZE)result_count = result.countresult = result.limit(limit).offset(limit * page).to_adiff --git a/app/controllers/drafts_controller.rb b/app/controllers/drafts_controller.rbindex 307104b9b4a..ba767b8a5d8 100644--- a/app/controllers/drafts_controller.rb+++ b/app/controllers/drafts_controller.rb@@ -5,11 +5,17 @@ class DraftsController < ApplicationControllerskip_before_action :check_xhr, :preload_json+ INDEX_LIMIT = 50+def indexparams.permit(:offset)- params.permit(:limit)- stream = Draft.stream(user: current_user, offset: params[:offset], limit: params[:limit])+ stream =+ Draft.stream(+ user: current_user,+ offset: params[:offset],+ limit: fetch_limit_from_params(default: nil, max: INDEX_LIMIT),+ )render json: { drafts: stream ? serialize_data(stream, DraftSerializer) : [] }enddiff --git a/app/controllers/groups_controller.rb b/app/controllers/groups_controller.rbindex f0e47f36c8b..a3a267815f0 100644--- a/app/controllers/groups_controller.rb+++ b/app/controllers/groups_controller.rb@@ -230,15 +230,16 @@ class GroupsController < ApplicationControllerrender "posts/latest", formats: [:rss]end+ MEMBERS_LIMIT = 1_000+def membersgroup = find_group(:group_id)guardian.ensure_can_see_group_members!(group)- limit = (params[:limit] || 50).to_i+ limit = fetch_limit_from_params(default: 50, max: MEMBERS_LIMIT)offset = params[:offset].to_i- raise Discourse::InvalidParameters.new(:limit) if limit < 0 || limit > 1000raise Discourse::InvalidParameters.new(:offset) if offset < 0dir = (params[:asc] && params[:asc].present?) ? "ASC" : "DESC"diff --git a/app/controllers/notifications_controller.rb b/app/controllers/notifications_controller.rbindex d5fadbc4942..75cd9c60b79 100644--- a/app/controllers/notifications_controller.rb+++ b/app/controllers/notifications_controller.rb@@ -5,6 +5,8 @@ class NotificationsController < ApplicationControllerbefore_action :ensure_admin, only: %i[create update destroy]before_action :set_notification, only: %i[update destroy]+ INDEX_LIMIT = 50+def indexuser =if params[:username] && !params[:recent]@@ -25,8 +27,7 @@ class NotificationsController < ApplicationControllerendif params[:recent].present?- limit = (params[:limit] || 15).to_i- limit = 50 if limit > 50+ limit = fetch_limit_from_params(default: 15, max: INDEX_LIMIT)include_reviewables = falsediff --git a/app/controllers/post_action_users_controller.rb b/app/controllers/post_action_users_controller.rbindex 7b39cd2fabb..36e87734809 100644--- a/app/controllers/post_action_users_controller.rb+++ b/app/controllers/post_action_users_controller.rb@@ -1,13 +1,15 @@# frozen_string_literal: trueclass PostActionUsersController < ApplicationController+ INDEX_LIMIT = 200+def indexparams.require(:post_action_type_id)params.require(:id)post_action_type_id = params[:post_action_type_id].to_ipage = params[:page].to_i- page_size = (params[:limit] || 200).to_i+ page_size = fetch_limit_from_params(default: INDEX_LIMIT, max: INDEX_LIMIT)# Find the post, and then determine if they can see the post (if deleted)post = Post.with_deleted.where(id: params[:id].to_i).firstdiff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rbindex 260d08f9dc0..0240cf0791a 100644--- a/app/controllers/posts_controller.rb+++ b/app/controllers/posts_controller.rb@@ -662,13 +662,15 @@ class PostsController < ApplicationControllerrender body: nilend+ DELETED_POSTS_MAX_LIMIT = 100+def deleted_postsparams.permit(:offset, :limit)guardian.ensure_can_see_deleted_posts!user = fetch_user_from_paramsoffset = [params[:offset].to_i, 0].max- limit = [(params[:limit] || 60).to_i, 100].min+ limit = fetch_limit_from_params(default: 60, max: DELETED_POSTS_MAX_LIMIT)posts = user_posts(guardian, user.id, offset: offset, limit: limit).where.not(deleted_at: nil)diff --git a/app/controllers/tag_groups_controller.rb b/app/controllers/tag_groups_controller.rbindex fd6dae701d3..74aa7528af0 100644--- a/app/controllers/tag_groups_controller.rb+++ b/app/controllers/tag_groups_controller.rb@@ -79,7 +79,10 @@ class TagGroupsController < ApplicationControllermatches = matches.where("lower(NAME) in (?)", params[:names].map(&:downcase))end- matches = matches.order("name").limit(params[:limit] || 5)+ matches =+ matches.order("name").limit(+ fetch_limit_from_params(default: 5, max: SiteSetting.max_tag_search_results),+ )render json: {results:diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rbindex f2df3fe9755..dae4b9790ec 100644--- a/app/controllers/tags_controller.rb+++ b/app/controllers/tags_controller.rb@@ -292,13 +292,8 @@ class TagsController < ::ApplicationControllerexclude_has_synonyms: params[:excludeHasSynonyms],}- if params[:limit]- begin- filter_params[:limit] = Integer(params[:limit])- raise Discourse::InvalidParameters.new(:limit) if !filter_params[:limit].positive?- rescue ArgumentError- raise Discourse::InvalidParameters.new(:limit)- end+ if limit = fetch_limit_from_params(default: nil, max: SiteSetting.max_tag_search_results)+ filter_params[:limit] = limitendfilter_params[:category] = Category.find_by_id(params[:categoryId]) if params[:categoryId]diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rbindex 29063caae6b..92ed0207429 100644--- a/app/controllers/users_controller.rb+++ b/app/controllers/users_controller.rb@@ -1182,6 +1182,8 @@ class UsersController < ApplicationControllerendend+ SEARCH_USERS_LIMIT = 50+def search_usersterm = params[:term].to_s.strip@@ -1204,10 +1206,11 @@ class UsersController < ApplicationControllerparams[:include_staged_users],)options[:last_seen_users] = !!ActiveModel::Type::Boolean.new.cast(params[:last_seen_users])- if params[:limit].present?- options[:limit] = params[:limit].to_i- raise Discourse::InvalidParameters.new(:limit) if options[:limit] <= 0++ if limit = fetch_limit_from_params(default: nil, max: SEARCH_USERS_LIMIT)+ options[:limit] = limitend+options[:topic_id] = topic_id if topic_idoptions[:category_id] = category_id if category_id@@ -1733,6 +1736,8 @@ class UsersController < ApplicationControllerrender json: success_jsonend+ BOOKMARKS_LIMIT = 20+def bookmarksuser = fetch_user_from_paramsguardian.ensure_can_edit!(user)@@ -1740,7 +1745,15 @@ class UsersController < ApplicationControllerrespond_to do |format|format.json do- bookmark_list = UserBookmarkList.new(user: user, guardian: guardian, params: params)+ bookmark_list =+ UserBookmarkList.new(+ user: user,+ guardian: guardian,+ search_term: params[:q],+ page: params[:page],+ per_page: fetch_limit_from_params(default: nil, max: BOOKMARKS_LIMIT),+ )+bookmark_list.loadif bookmark_list.bookmarks.empty?@@ -1789,10 +1802,9 @@ class UsersController < ApplicationControllerUserBookmarkList.new(user: current_user,guardian: guardian,- params: {- per_page: USER_MENU_LIST_LIMIT - reminder_notifications.size,- },+ per_page: USER_MENU_LIST_LIMIT - reminder_notifications.size,)+bookmark_list.load do |query|if exclude_bookmark_ids.present?query.where("bookmarks.id NOT IN (?)", exclude_bookmark_ids)diff --git a/app/models/user_bookmark_list.rb b/app/models/user_bookmark_list.rbindex a55a72a8141..a085a5b3ec7 100644--- a/app/models/user_bookmark_list.rb+++ b/app/models/user_bookmark_list.rb@@ -8,26 +8,32 @@ class UserBookmarkListattr_reader :bookmarks, :per_page, :has_moreattr_accessor :more_bookmarks_url, :bookmark_serializer_opts- def initialize(user:, guardian:, params:)+ def initialize(user:, guardian:, search_term: nil, per_page: nil, page: 0)@user = user@guardian = guardian- @params = params- @params.merge!(per_page: PER_PAGE) if params[:per_page].blank?- @params[:per_page] = PER_PAGE if @params[:per_page] > PER_PAGE+ @per_page = per_page || PER_PAGE+ @per_page = PER_PAGE if @per_page > PER_PAGE++ @search_term = search_term+ @page = page.to_i@bookmarks = []@bookmark_serializer_opts = {}enddef load(&blk)- query = BookmarkQuery.new(user: @user, guardian: @guardian, params: @params)+ query =+ BookmarkQuery.new(+ user: @user,+ guardian: @guardian,+ search_term: @search_term,+ page: @page,+ per_page: @per_page,+ )+@bookmarks = query.list_all(&blk)- @has_more = (@params[:page].to_i + 1) * @params[:per_page] < query.count+ @has_more = (@page.to_i + 1) * @per_page < query.count@bookmarksend-- def per_page- @per_page ||= @params[:per_page]- endenddiff --git a/lib/bookmark_query.rb b/lib/bookmark_query.rbindex 3a54a195807..7624f011369 100644--- a/lib/bookmark_query.rb+++ b/lib/bookmark_query.rb@@ -26,19 +26,18 @@ class BookmarkQueryattr_reader :guardian, :count- def initialize(user:, guardian: nil, params: {})+ def initialize(user:, guardian: nil, search_term: nil, page: nil, per_page: nil)@user = user- @params = params+ @search_term = search_term@guardian = guardian || Guardian.new(@user)- @page = @params[:page].to_i- @limit = @params[:limit].present? ? @params[:limit].to_i : @params[:per_page]+ @page = page ? page.to_i : 0+ @per_page = per_page ? per_page.to_i : 20@count = 0enddef list_all(&blk)- search_term = @params[:q]- ts_query = search_term.present? ? Search.ts_query(term: search_term) : nil- search_term_wildcard = search_term.present? ? "%#{search_term}%" : nil+ ts_query = @search_term.present? ? Search.ts_query(term: @search_term) : nil+ search_term_wildcard = @search_term.present? ? "%#{@search_term}%" : nilqueries =Bookmark@@ -51,7 +50,7 @@ class BookmarkQuery# on a topic and that topic was moved into a private categorynext if interim_results.blank?- if search_term.present?+ if @search_term.present?interim_results =bookmarkable.perform_search_query(interim_results, search_term_wildcard, ts_query)end@@ -78,13 +77,14 @@ class BookmarkQuery@count = results.count- results = results.offset(@page * @params[:per_page]) if @page.positive?+ results = results.offset(@page * @per_page) if @page.positive?if updated_results = blk&.call(results)results = updated_resultsend- results = results.limit(@limit).to_a+ results = results.limit(@per_page).to_a+BookmarkQuery.preload(results, self)resultsenddiff --git a/plugins/chat/app/controllers/chat/api/channels_memberships_controller.rb b/plugins/chat/app/controllers/chat/api/channels_memberships_controller.rbindex 0392b3bb177..d35d63df59c 100644--- a/plugins/chat/app/controllers/chat/api/channels_memberships_controller.rb+++ b/plugins/chat/app/controllers/chat/api/channels_memberships_controller.rb@@ -1,11 +1,13 @@# frozen_string_literal: trueclass Chat::Api::ChannelsMembershipsController < Chat::Api::ChannelsController+ INDEX_LIMIT = 50+def indexparams.permit(:username, :offset, :limit)offset = params[:offset].to_i- limit = (params[:limit] || 50).to_i.clamp(1, 50)+ limit = fetch_limit_from_params(default: INDEX_LIMIT, max: INDEX_LIMIT)memberships =Chat::ChannelMembershipsQuery.call(diff --git a/spec/lib/bookmark_query_spec.rb b/spec/lib/bookmark_query_spec.rbindex 3ce8ad94711..d54c10d07d2 100644--- a/spec/lib/bookmark_query_spec.rb+++ b/spec/lib/bookmark_query_spec.rb@@ -4,10 +4,9 @@ RSpec.describe BookmarkQuery dobefore { SearchIndexer.enable }fab!(:user) { Fabricate(:user) }- let(:params) { {} }- def bookmark_query(user: nil, params: nil)- BookmarkQuery.new(user: user || self.user, params: params || self.params)+ def bookmark_query(user: nil, search_term: nil, per_page: nil)+ BookmarkQuery.new(user: user || self.user, search_term:, per_page:)enddescribe "#list_all" do@@ -67,7 +66,7 @@ RSpec.describe BookmarkQuery doexpect(bookmarks.map(&:id)).to eq([])end- context "when q param is provided" do+ context "when search_term is provided" dolet!(:post) doFabricate(:post,@@ -89,17 +88,17 @@ RSpec.describe BookmarkQuery doendit "can search by bookmark name" do- bookmarks = bookmark_query(params: { q: "check" }).list_all+ bookmarks = bookmark_query(search_term: "check").list_allexpect(bookmarks.map(&:id)).to eq([bookmark3.id])endit "can search by post content" do- bookmarks = bookmark_query(params: { q: "content" }).list_all+ bookmarks = bookmark_query(search_term: "content").list_allexpect(bookmarks.map(&:id)).to eq([bookmark4.id])endit "can search by topic title" do- bookmarks = bookmark_query(params: { q: "bugfix" }).list_all+ bookmarks = bookmark_query(search_term: "bugfix").list_allexpect(bookmarks.map(&:id)).to eq([bookmark4.id])end@@ -111,7 +110,7 @@ RSpec.describe BookmarkQuery doendit "allows searching bookmarkables by fields in other tables" do- bookmarks = bookmark_query(params: { q: "bookmarkk" }).list_all+ bookmarks = bookmark_query(search_term: "bookmarkk").list_allexpect(bookmarks.map(&:id)).to eq([bookmark5.id])endend@@ -205,10 +204,9 @@ RSpec.describe BookmarkQuery doendend- context "when the limit param is provided" do- let(:params) { { limit: 1 } }+ context "when the per_page is provided" doit "is respected" do- expect(bookmark_query.list_all.count).to eq(1)+ expect(bookmark_query(per_page: 1).list_all.count).to eq(1)endendenddiff --git a/spec/models/user_bookmark_list_spec.rb b/spec/models/user_bookmark_list_spec.rbindex 1876ef3f827..c6074caff63 100644--- a/spec/models/user_bookmark_list_spec.rb+++ b/spec/models/user_bookmark_list_spec.rb@@ -1,9 +1,8 @@# frozen_string_literal: trueRSpec.describe UserBookmarkList do- let(:params) { {} }fab!(:user) { Fabricate(:user) }- let(:list) { UserBookmarkList.new(user: user, guardian: Guardian.new(user), params: params) }+ let(:list) { UserBookmarkList.new(user: user, guardian: Guardian.new(user)) }before doregister_test_bookmarkable@@ -21,9 +20,11 @@ RSpec.describe UserBookmarkList doit "returns all types of bookmarks" dolist.load+expect(list.bookmarks.map(&:id)).to match_array([post_bookmark.id, topic_bookmark.id, user_bookmark.id],)+expect(list.has_more).to eq(false)end@@ -32,13 +33,14 @@ RSpec.describe UserBookmarkList doendcontext "when the per_page param is too high" do- let(:params) { { per_page: 1000 } }-it "does not allow more than X bookmarks to be requested per page" do22.times dobookmark = Fabricate(:bookmark, user: user, bookmarkable: Fabricate(:post))Fabricate(:topic_user, topic: bookmark.bookmarkable.topic, user: user)end++ list = UserBookmarkList.new(user: user, guardian: Guardian.new(user), per_page: 1000)+expect(list.load.count).to eq(20)endenddiff --git a/spec/rails_helper.rb b/spec/rails_helper.rbindex 63e010de110..2d0550dd8f2 100644--- a/spec/rails_helper.rb+++ b/spec/rails_helper.rb@@ -78,6 +78,7 @@ end# Requires supporting ruby files with custom matchers and macros, etc,# in spec/support/ and its subdirectories.Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }+Dir[Rails.root.join("spec/requests/examples/*.rb")].each { |f| require f }Dir[Rails.root.join("spec/system/helpers/**/*.rb")].each { |f| require f }Dir[Rails.root.join("spec/system/page_objects/**/base.rb")].each { |f| require f }diff --git a/spec/requests/admin/api_controller_spec.rb b/spec/requests/admin/api_controller_spec.rbindex d83520968f5..b582558fce9 100644--- a/spec/requests/admin/api_controller_spec.rb+++ b/spec/requests/admin/api_controller_spec.rb@@ -20,6 +20,12 @@ RSpec.describe Admin::ApiController doexpect(response.parsed_body["keys"].length).to eq(3)end+ describe "when limit params is invalid" do+ include_examples "invalid limit params",+ "/admin/api/keys.json",+ described_class::INDEX_LIMIT+ end+it "can paginate results" doget "/admin/api/keys.json?offset=0&limit=2"diff --git a/spec/requests/admin/reports_controller_spec.rb b/spec/requests/admin/reports_controller_spec.rbindex 5494fc230ac..c300947e1bf 100644--- a/spec/requests/admin/reports_controller_spec.rb+++ b/spec/requests/admin/reports_controller_spec.rb@@ -30,6 +30,12 @@ RSpec.describe Admin::ReportsController doendcontext "with invalid params" do+ context "when limit param is invalid" do+ include_examples "invalid limit params",+ "/admin/reports/topics.json",+ described_class::REPORTS_LIMIT+ end+context "with nonexistent report" doit "returns not found reports" doget "/admin/reports/bulk.json",@@ -154,6 +160,12 @@ RSpec.describe Admin::ReportsController doexpect(response.parsed_body["report"]["total"]).to eq(1)endend++ context "when limit param is invalid" do+ include_examples "invalid limit params",+ "/admin/reports/topics.json",+ described_class::REPORTS_LIMIT+ endenddescribe "when report is scoped to a category" dodiff --git a/spec/requests/admin/staff_action_logs_controller_spec.rb b/spec/requests/admin/staff_action_logs_controller_spec.rbindex 93a8bf1fd92..4724124869e 100644--- a/spec/requests/admin/staff_action_logs_controller_spec.rb+++ b/spec/requests/admin/staff_action_logs_controller_spec.rb@@ -27,6 +27,12 @@ RSpec.describe Admin::StaffActionLogsController do"action_id" => UserHistory.actions[:delete_topic],)end++ describe "when limit params is invalid" do+ include_examples "invalid limit params",+ "/admin/logs/staff_action_logs.json",+ described_class::INDEX_LIMIT+ endendcontext "when logged in as an admin" dodiff --git a/spec/requests/directory_items_controller_spec.rb b/spec/requests/directory_items_controller_spec.rbindex 6576072fcc4..94eaec500b8 100644--- a/spec/requests/directory_items_controller_spec.rb+++ b/spec/requests/directory_items_controller_spec.rb@@ -30,22 +30,7 @@ RSpec.describe DirectoryItemsController doexpect(json["directory_items"].length).to eq(2)end- it "does not exceed PAGE_SIZE if limit parameter is more than PAGE_SIZE" do- large_limit = DirectoryItemsController::PAGE_SIZE + 10- get "/directory_items.json", params: { period: "all", limit: large_limit }- expect(response.status).to eq(200)- json = response.parsed_body-- expect(json["directory_items"].length).to eq(DirectoryItemsController::PAGE_SIZE)- end-- it "handles invalid limit parameters gracefully" do- get "/directory_items.json", params: { period: "all", limit: "invalid_limit" }- expect(response.status).to eq(200)- json = response.parsed_body-- expect(json["directory_items"]).not_to be_empty- end+ include_examples "invalid limit params", "/directory_items.json", described_class::PAGE_SIZEendcontext "with exclude_groups parameter" dodiff --git a/spec/requests/drafts_controller_spec.rb b/spec/requests/drafts_controller_spec.rbindex 7b0d7f03b80..1d88db0b4a5 100644--- a/spec/requests/drafts_controller_spec.rb+++ b/spec/requests/drafts_controller_spec.rb@@ -1,14 +1,22 @@# frozen_string_literal: trueRSpec.describe DraftsController do+ fab!(:user) { Fabricate(:user) }+describe "#index" doit "requires you to be logged in" doget "/drafts.json"expect(response.status).to eq(403)end+ describe "when limit params is invalid" do+ before { sign_in(user) }++ include_examples "invalid limit params", "/drafts.json", described_class::INDEX_LIMIT+ end+it "returns correct stream length after adding a draft" do- user = sign_in(Fabricate(:user))+ sign_in(user)Draft.set(user, "xxx", 0, "{}")get "/drafts.json"expect(response.status).to eq(200)@@ -17,7 +25,7 @@ RSpec.describe DraftsController doendit "has empty stream after deleting last draft" do- user = sign_in(Fabricate(:user))+ sign_in(user)Draft.set(user, "xxx", 0, "{}")Draft.clear(user, "xxx", 0)get "/drafts.json"@@ -46,7 +54,7 @@ RSpec.describe DraftsController dodescribe "#show" doit "returns a draft if requested" do- user = sign_in(Fabricate(:user))+ sign_in(user)Draft.set(user, "hello", 0, "test")get "/drafts/hello.json"@@ -62,7 +70,7 @@ RSpec.describe DraftsController doendit "saves a draft" do- user = sign_in(Fabricate(:user))+ sign_in(user)post "/drafts.json", params: { draft_key: "xyz", data: { my: "data" }.to_json, sequence: 0 }@@ -77,7 +85,7 @@ RSpec.describe DraftsController doendit "checks for an conflict on update" do- user = sign_in(Fabricate(:user))+ sign_in(user)post = Fabricate(:post, user: user)post "/drafts.json",@@ -103,7 +111,7 @@ RSpec.describe DraftsController doendit "cant trivially resolve conflicts without interaction" do- user = sign_in(Fabricate(:user))+ sign_in(user)DraftSequence.next!(user, "abc")@@ -120,7 +128,7 @@ RSpec.describe DraftsController doendit "has a clean protocol for ownership handover" do- user = sign_in(Fabricate(:user))+ sign_in(user)post "/drafts.json",params: {@@ -170,7 +178,7 @@ RSpec.describe DraftsController doendit "raises an error for out-of-sequence draft setting" do- user = sign_in(Fabricate(:user))+ sign_in(user)seq = DraftSequence.next!(user, "abc")Draft.set(user, "abc", seq, { b: "test" }.to_json)@@ -230,7 +238,7 @@ RSpec.describe DraftsController dodescribe "#destroy" doit "destroys drafts when required" do- user = sign_in(Fabricate(:user))+ sign_in(user)Draft.set(user, "xxx", 0, "hi")delete "/drafts/xxx.json", params: { sequence: 0 }diff --git a/spec/requests/examples/invalid_limit_params.rb b/spec/requests/examples/invalid_limit_params.rbnew file mode 100644index 00000000000..9944f6acbd3--- /dev/null+++ b/spec/requests/examples/invalid_limit_params.rb@@ -0,0 +1,23 @@+# frozen_string_literal: true++RSpec.shared_examples "invalid limit params" do |endpoint, max_limit, extra_params|+ let(:params) { extra_params&.dig(:params) || {} }++ it "returns 400 response code when limit params is negative" do+ get endpoint, params: { limit: -1 }.merge(params)++ expect(response.status).to eq(400)+ end++ it "returns 400 response code when limit params is suspicious" do+ get endpoint, params: { limit: "1; DROP TABLE users" }.merge(params)++ expect(response.status).to eq(400)+ end++ it "returns 400 response code when limit params exceeds the max limit" do+ get endpoint, params: { limit: max_limit + 1 }.merge(params)++ expect(response.status).to eq(400)+ end+enddiff --git a/spec/requests/notifications_controller_spec.rb b/spec/requests/notifications_controller_spec.rbindex b9ae086d61e..c940bf129b6 100644--- a/spec/requests/notifications_controller_spec.rb+++ b/spec/requests/notifications_controller_spec.rb@@ -87,6 +87,15 @@ RSpec.describe NotificationsController doDiscourse.clear_redis_readonly!end+ describe "when limit params is invalid" do+ include_examples "invalid limit params",+ "/notifications.json",+ described_class::INDEX_LIMIT,+ params: {+ recent: true,+ }+ end+it "get notifications with all filters" donotification = Fabricate(:notification, user: user)notification2 = Fabricate(:notification, user: user)diff --git a/spec/requests/post_action_users_controller_spec.rb b/spec/requests/post_action_users_controller_spec.rbindex 2de40facfb1..d75bbaed102 100644--- a/spec/requests/post_action_users_controller_spec.rb+++ b/spec/requests/post_action_users_controller_spec.rb@@ -4,6 +4,14 @@ RSpec.describe PostActionUsersController dofab!(:user) { Fabricate(:user) }let(:post) { Fabricate(:post, user: sign_in(user)) }+ describe "index" do+ describe "when limit params is invalid" do+ include_examples "invalid limit params",+ "/post_action_users.json",+ described_class::INDEX_LIMIT+ end+ end+context "with render" doit "always allows you to see your own actions" donotify_mod = PostActionType.types[:notify_moderators]diff --git a/spec/requests/posts_controller_spec.rb b/spec/requests/posts_controller_spec.rbindex 4fef6b7fce2..c641f1b2dd4 100644--- a/spec/requests/posts_controller_spec.rb+++ b/spec/requests/posts_controller_spec.rb@@ -2254,6 +2254,14 @@ RSpec.describe PostsController doexpect(response).to be_forbiddenend+ describe "when limit params is invalid" do+ before { sign_in(moderator) }++ include_examples "invalid limit params",+ "/posts/system/deleted.json",+ described_class::DELETED_POSTS_MAX_LIMIT+ end+it "can see the deleted posts when authorized" dosign_in(moderator)get "/posts/system/deleted.json"diff --git a/spec/requests/tag_groups_controller_spec.rb b/spec/requests/tag_groups_controller_spec.rbindex 87b49faa37d..2c30910e899 100644--- a/spec/requests/tag_groups_controller_spec.rb+++ b/spec/requests/tag_groups_controller_spec.rb@@ -48,6 +48,12 @@ RSpec.describe TagGroupsController dolet(:full) { TagGroupPermission.permission_types[:full] }let(:readonly) { TagGroupPermission.permission_types[:readonly] }+ describe "when limit params is invalid" do+ include_examples "invalid limit params",+ "/tag_groups/filter/search.json",+ SiteSetting.max_tag_search_results+ end+context "for anons" doit "returns the tag group with the associated tag names" dotag_group = tag_group_with_permission(everyone, readonly)diff --git a/spec/requests/tags_controller_spec.rb b/spec/requests/tags_controller_spec.rbindex 8f96113e3a7..5a054498dee 100644--- a/spec/requests/tags_controller_spec.rb+++ b/spec/requests/tags_controller_spec.rb@@ -1103,22 +1103,10 @@ RSpec.describe TagsController do)end- it "returns error 400 for negative limit" do- get "/tags/filter/search.json", params: { q: "", limit: -1 }-- expect(response.status).to eq(400)- expect(response.parsed_body["errors"].first).to eq(- I18n.t("invalid_params", message: "limit"),- )- end-- it "returns error 400 for suspicious limit" do- get "/tags/filter/search.json", params: { q: "", limit: "1; SELECT 1" }-- expect(response.status).to eq(400)- expect(response.parsed_body["errors"].first).to eq(- I18n.t("invalid_params", message: "limit"),- )+ describe "when limit params is invalid" do+ include_examples "invalid limit params",+ "/tags/filter/search.json",+ SiteSetting.max_tag_search_resultsendit "includes required tag group information" dodiff --git a/spec/requests/users_controller_spec.rb b/spec/requests/users_controller_spec.rbindex 1c9729df0a9..605588bd063 100644--- a/spec/requests/users_controller_spec.rb+++ b/spec/requests/users_controller_spec.rb@@ -4,7 +4,7 @@ require "rotp"RSpec.describe UsersController dofab!(:user) { Fabricate(:user) }- fab!(:user1) { Fabricate(:user) }+ fab!(:user1) { Fabricate(:user, username: "someusername") }fab!(:another_user) { Fabricate(:user) }fab!(:invitee) { Fabricate(:user) }fab!(:inviter) { Fabricate(:user) }@@ -4886,11 +4886,10 @@ RSpec.describe UsersController doexpect(response.status).to eq(200)end- context "with limit" do- it "returns an error if value is invalid" do- get "/u/search/users.json", params: { limit: "-1" }- expect(response.status).to eq(400)- end+ describe "when limit params is invalid" do+ include_examples "invalid limit params",+ "/u/search/users.json",+ described_class::SEARCH_USERS_LIMITendcontext "when `enable_names` is true" do@@ -6185,6 +6184,14 @@ RSpec.describe UsersController doexpect(response.status).to eq(200)expect(response.parsed_body["bookmarks"]).to eq([])end++ describe "when limit params is invalid" do+ before { sign_in(user1) }++ include_examples "invalid limit params",+ "/u/someusername/bookmarks.json",+ described_class::BOOKMARKS_LIMIT+ endenddescribe "#bookmarks excerpts" dodiff --git a/spec/serializers/user_bookmark_list_serializer_spec.rb b/spec/serializers/user_bookmark_list_serializer_spec.rbindex 6c5934ccb25..2ec484cb9dc 100644--- a/spec/serializers/user_bookmark_list_serializer_spec.rb+++ b/spec/serializers/user_bookmark_list_serializer_spec.rb@@ -18,7 +18,7 @@ RSpec.describe UserBookmarkListSerializer dolet(:user_bookmark) { Fabricate(:bookmark, user: user, bookmarkable: Fabricate(:user)) }def run_serializer- bookmark_list = UserBookmarkList.new(user: user, guardian: Guardian.new(user), params: {})+ bookmark_list = UserBookmarkList.new(user: user, guardian: Guardian.new(user))bookmark_list.loadUserBookmarkListSerializer.new(bookmark_list)end