Skip to content

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.rb
index 32e805b36c8..7d7f1fb478b 100644
--- a/app/controllers/categories_controller.rb
+++ b/app/controllers/categories_controller.rb
@@ -36,6 +36,8 @@ class CategoriesController < ApplicationController
MIN_CATEGORIES_TOPICS = 5
MAX_CATEGORIES_TOPICS = 100
MAX_CATEGORIES_LIMIT = 25
+ MAX_CATEGORY_SEARCH_TERM_LENGTH = 250
+ MAX_CATEGORY_SEARCH_WORDS = 25
def redirect
return if handle_permalink("/category/#{params[:path]}")
@@ -469,7 +471,7 @@ class CategoriesController < ApplicationController
end
def 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 < ApplicationController
categories = 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.rb
index bdd64ac55ba..2036e51b453 100644
--- a/spec/requests/categories_controller_spec.rb
+++ b/spec/requests/categories_controller_spec.rb
@@ -2048,6 +2048,30 @@ RSpec.describe CategoriesController do
expect(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)
+ end
end
context "with parent_category_id" do