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?
This commit is contained in:
Daniel Uber 2021-12-27 12:30:36 -06:00 committed by GitHub
parent 4d40ea18a2
commit c879c5b3d8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 7 additions and 0 deletions

View file

@ -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(
[

View file

@ -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