From c879c5b3d82fbefad430a20deb19a0c8b629668f Mon Sep 17 00:00:00 2001 From: Daniel Uber Date: Mon, 27 Dec 2021 12:30:36 -0600 Subject: [PATCH] Remove slash characters from user name search term (#15867) * Remove slash characters from user supplied user search input Prevents an error when the search term includes '\' PG::SyntaxError: ERROR: syntax error in tsquery https://app.honeybadger.io/projects/66984/faults/79391397 I had originally thought to add this cleanup to Search::Username but decided to move it as close to the generated (invalid) query as possible to prevent alternate paths finding their way here. * Add spec Since there's no existing tests for the scope - I put the test code on the caller (Search::Username) rather than the model (User), this seems reasonable. * When the term is empty (or only slashes) just return null relation * Handle nil input (search for nothing) correctly One of the request specs sends a username search with no query, so we can't call nil.delete or nil.empty?, use blank? of empty? --- app/models/user.rb | 3 +++ spec/services/search/username_spec.rb | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/app/models/user.rb b/app/models/user.rb index 8e0f18040..aeec196d9 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -185,6 +185,9 @@ class User < ApplicationRecord # => https://stackoverflow.com/a/11007216/4186181 # scope :search_by_name_and_username, lambda { |term| + term = term&.delete("\\") # prevents syntax error in tsquery + return none if term.blank? + where( sanitize_sql_array( [ diff --git a/spec/services/search/username_spec.rb b/spec/services/search/username_spec.rb index 0940d2a21..8ea430574 100644 --- a/spec/services/search/username_spec.rb +++ b/spec/services/search/username_spec.rb @@ -80,5 +80,9 @@ RSpec.describe Search::Username, type: :service do expect(results.size).to eq(max_results) expect([alex.username, alexsmith.username]).to include(results.first[:username]) end + + it "sanitizes the input when given slashes" do + expect(described_class.search_documents("\\")).to eq([]) + end end end