Sanitize Search Input
The SearchInputParsingUtils class in HST provides utility methods to sanitize query strings before using them in search operations. These methods remove invalid characters and restrict the use of wildcards, reducing the risk of malicious input.
Always use SearchInputParsingUtils to process free-text queries that you inject into an HstQuery.
For best performance, set the allowSingleNonLeadingWildCardPerTerm parameter of the parse method to false. This disables single-character wildcards within terms, which improves query execution speed.
The following example demonstrates how to sanitize user input before building and executing an HstQuery:
final HstRequestContext context = request.getRequestContext(); final HippoBean scope = context.getSiteContentBaseBean(); HstQueryBuilder hstQueryBuilder = HstQueryBuilder.create(scope) .ofTypes(BaseDocument.class); // PARSE the query String query = getPublicRequestParameter(request, "query"); String parsedQuery = SearchInputParsingUtils.parse(query, false); if (StringUtils.isNotEmpty(parsedQuery)) { hstQueryBuilder = hstQueryBuilder.where(constraint(".").contains(parsedQuery)); } final HstQuery hstQuery = hstQueryBuilder.build(); final HstQueryResult result = hstQuery.execute(); request.setAttribute("result", result);
This approach ensures that only sanitized input is used in search queries, reducing security risks and improving performance.