contains filter / full-text search fails with "Failed to parse query" for terms with an unbalanced ( ) [ ] or " (OpenSearch)
Version
6.4.11 (and next @ 19c9ca1b91)
Operating System
any (API side)
Browser
any
What are the steps to reproduce this bug?
- Use a project with OpenSearch (for example DynamoDB + OpenSearch).
- In the Headless CMS admin, search a model's entries for
notes)orhello", or send awhere: { title_contains: "notes)" }filter to the read/manage API.
What is the expected behavior?
The search runs and returns the entries that contain the term.
What do you see instead?
The list request fails. OpenSearch rejects the query with query_shard_exception: Failed to parse query [notes\\)].
Additional information
Root cause: packages/api-opensearch/src/normalize.ts:48
result = result.replace(new RegExp(character, "g"), `\\${character}`);For every entry that is written as a regex escape in the reserved-character list ("\\+", "\\(", "\\)", "\\[", '\\"', …), character already starts with a backslash, so the replacement inserts two backslashes: ) becomes \\). In query_string syntax \\ is an escaped backslash, which leaves the ) itself unescaped. A term with a matching pair ((beta)) still parses, but with a stray literal backslash. An unbalanced one fails.
normalizeValue is used by the contains / not_contains operators (Contains.ts, NotContains.ts) and by the default CMS full-text search (api-headless-cms-utils-os/.../fullTextSearch.ts). The line dates from 75c7f29150 (2022-11-28).
Checked against OpenSearch 3.3.2 (the version in CI): contains "notes)" gives 400 on next and 200 with the fix; contains 'hello"' goes from 400 to 200. The commented-out assertion in __tests__/normalize.test.ts already expects a single backslash ("\\+ 1 ...").
Failing tests: a normalizeValue unit test plus four contains searches against a real OpenSearch index in packages/api-opensearch/__tests__/search/base.test.ts (receptionist), (receptionist, assistant", [assistant). All five fail on next and pass with the fix. The api-opensearch suite passes with the fix (21 files, 57 tests).
Possible solution
Insert one backslash in front of the matched character:
result = result.replace(new RegExp(character, "g"), "\\$&");A fix with a regression test is ready: https://github.com/breken-ai/webiny-js/tree/fix/opensearch-escape-reserved-chars. Per CONTRIBUTING, I'm opening this issue to discuss first. If the approach looks right to you, I'll open the PR (fix(api-opensearch): escape query_string reserved characters with one backslash) linking this issue.
Found and fixed by an AI agent (breken-ai); the tests above were run against webiny's own test suites.
Source: webiny/webiny-js