A platform for community discussion. Free, open, simple.
SECURITY: Limit Category search term and word count (#41588)
Juan David Martínez Cubillos7d635130bfcf
diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rbindex 32e805b36c8..7d7f1fb478b 100644--- a/app/controllers/categories_controller.rb+++ b/app/controllers/categories_controller.rb@@ -36,6 +36,8 @@ class CategoriesController < ApplicationControllerMIN_CATEGORIES_TOPICS = 5MAX_CATEGORIES_TOPICS = 100MAX_CATEGORIES_LIMIT = 25+ MAX_CATEGORY_SEARCH_TERM_LENGTH = 250+ MAX_CATEGORY_SEARCH_WORDS = 25def redirectreturn if handle_permalink("/category/#{params[:path]}")@@ -469,7 +471,7 @@ class CategoriesController < ApplicationControllerenddef search- term = params[:term].to_s.strip+ term = params[:term].to_s.strip[0, MAX_CATEGORY_SEARCH_TERM_LENGTH]parent_category_id = params[:parent_category_id].to_i if params[:parent_category_id].present?include_uncategorized =(@@ -512,7 +514,13 @@ class CategoriesController < ApplicationControllercategories = Category.secured(guardian)- if term.present? && words = term.split+ if term.present?+ words = []+ term.scan(/\S+/) do |word|+ words << word+ break if words.size >= MAX_CATEGORY_SEARCH_WORDS+ end+words.each do |word|categories =categories.where(diff --git a/spec/requests/categories_controller_spec.rb b/spec/requests/categories_controller_spec.rbindex bdd64ac55ba..2036e51b453 100644--- a/spec/requests/categories_controller_spec.rb+++ b/spec/requests/categories_controller_spec.rb@@ -2048,6 +2048,30 @@ RSpec.describe CategoriesController doexpect(response.parsed_body["categories"].map { |c| c["name"] }).to include("Editions")end++ it "limits the number of term words used in SQL filters" do+ long_term = 50.times.map { |index| "word#{index}" }.join(" ")++ queries = track_sql_queries { post "/categories/search.json", params: { term: long_term } }++ expect(response.status).to eq(200)++ category_search_queries =+ queries.select { |query| query.match?(/FROM "?categories"?/i) && query.match?(/ILIKE/i) }+ ilike_counts = category_search_queries.map { |query| query.scan(/\bILIKE\b/i).size }++ expect(ilike_counts).to be_present+ expect(ilike_counts.max).to be <= 25+ end++ it "limits the term length used in SQL filters" do+ long_term = "a" * 300++ queries = track_sql_queries { post "/categories/search.json", params: { term: long_term } }++ expect(response.status).to eq(200)+ expect(queries.join("\n")).not_to include(long_term)+ endendcontext "with parent_category_id" do