Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions services/search/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,9 @@ def build_search_query(query: str):
and_operands = re.split(r"[\s,&]+", or_operand)
expression = ""
for and_operand in and_operands:
if not and_operand.strip():
# Skip empty or whitespace-only operands
Comment on lines 243 to +245
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: A search query with only operators (e.g., " | ") causes build_search_query to return an empty string, leading to a database error and a 400 response.
Severity: MEDIUM

Suggested Fix

After calling build_search_query, add a check to verify if the returned search_query_str is empty. If it is, bypass the database query and return an empty result set directly to prevent the to_tsquery syntax error.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent.
Verify if this is a real issue. If it is, propose a fix; if not, explain why it's not
valid.

Location: services/search/api.py#L243-L245

Potential issue: A search query containing only operators and whitespace, such as `"  |
"` or `"  &  "`, passes the initial validation. However, the `build_search_query`
function will process this input and return an empty string. This empty string is then
passed to PostgreSQL's `to_tsquery` function within the search SQL statement, which
causes a database syntax error. The application catches this error and returns an HTTP
400 Bad Request to the user, instead of the expected behavior of returning zero search
results.

Did we get this right? 👍 / 👎 to inform future reviews.

continue
if re.fullmatch(r"'+", and_operand):
# Skip any operands that are just repeating single-quotes
continue
Expand Down
10 changes: 10 additions & 0 deletions services/search/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,16 @@ def test_search_with_vertical_bar_in_query(api_client, units):
("a, &&& , & b || || |||| |c,,,, d", "a:* & b:* | c:* & d:*"),
# Expression with repeating single-quotes
("','','''',a,b'c,d''e,f'''g,','','''", "a:* & b'c:* & d''e:* & f'''g:*"),
# Empty operands should be skipped to prevent invalid ":*" syntax
(" ", ""),
(" | ", ""),
(" & ", ""),
(" , ", ""),
("a | | b", "a:* | b:*"),
("a & & b", "a:* & b:*"),
("a, ,b", "a:* & b:*"),
(" | a", "a:*"),
("a | ", "a:*"),
],
)
def test_build_search_query(query, expected):
Expand Down