From 07dc6efdc95f1893bc20f1d564bc7183cf5de6c2 Mon Sep 17 00:00:00 2001 From: Daniel Waterworth Date: Wed, 1 May 2024 13:27:46 -0500 Subject: [PATCH] DEV: Use safer SQL functions for string queries in CategoryHashTagDataSource (#26836) Instead of `LIKE`, use either `starts_with` or `position`. This way the term isn't interpreted as a pattern. --- app/services/category_hashtag_data_source.rb | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/app/services/category_hashtag_data_source.rb b/app/services/category_hashtag_data_source.rb index 299a7fdc731..2ef743517c1 100644 --- a/app/services/category_hashtag_data_source.rb +++ b/app/services/category_hashtag_data_source.rb @@ -60,10 +60,13 @@ class CategoryHashtagDataSource .includes(:parent_category) if condition == HashtagAutocompleteService.search_conditions[:starts_with] - base_search = base_search.where("LOWER(slug) LIKE :term", term: "#{term}%") + base_search = base_search.where("starts_with(LOWER(slug), LOWER(:term))", term: term) elsif condition == HashtagAutocompleteService.search_conditions[:contains] base_search = - base_search.where("LOWER(name) LIKE :term OR LOWER(slug) LIKE :term", term: "%#{term}%") + base_search.where( + "position(LOWER(:term) IN LOWER(name)) <> 0 OR position(LOWER(:term) IN LOWER(slug)) <> 0", + term: term, + ) else raise Discourse::InvalidParameters.new("Unknown search condition: #{condition}") end