Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.Map;
import java.util.regex.Pattern;

import org.keycloak.models.ModelValidationException;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserProvider;
Expand Down Expand Up @@ -87,6 +88,9 @@ public static Map<String, String> getFields(final String query) {
String name = "";
while (i < chars.length && chars[i] != ':') {
if (chars[i] == '\\') {
if (i + 1 >= chars.length) {
throw new ModelValidationException("Invalid search query: unterminated escape sequence");
}
if (chars[i+1] == '\"') {
i++;
}
Expand Down Expand Up @@ -123,6 +127,9 @@ else if(chars[i] == ' ' && !inQuotes) {
String value = "";
while (i < chars.length) {
if (chars[i] == '\\') {
if (i + 1 >= chars.length) {
throw new ModelValidationException("Invalid search query: unterminated escape sequence");
}
if (chars[i+1] == '\"') {
i++;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@
import java.util.HashMap;
import java.util.Map;

import org.keycloak.models.ModelValidationException;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;

/**
* @author Vaclav Muzikar <vmuzikar@redhat.com>
Expand Down Expand Up @@ -61,6 +64,14 @@ public void testGetFields() {

testParseQuery("k:val1",
"k", "val1");

assertInvalidQuery("key:val\\");
assertInvalidQuery("key\\");
assertInvalidQuery("key:\"val\\");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The original issue lists additional malformed inputs beyond trailing backslashes: "key \", key ", "key \"1\"". It would be good to add test cases for these as well to confirm they're handled gracefully (some may already work via the existing loop bounds, but explicit coverage prevents future fixes on this).

}

private void assertInvalidQuery(String query) {
assertThrows(ModelValidationException.class, () -> SearchQueryUtils.getFields(query));
}

private void testParseQuery(String query, String... expectedStr) {
Expand Down
Loading