feat(iot): search the supported fleet index subset (#4913)

Floci served the fleet indexing configuration but not SearchIndex, so
an application that finds its things by name, type, group or attribute
got "Unknown operation: POST /indices/search".

SearchIndex now runs on POST /indices/search over the things of the
caller's account and region, in thing name order. Its page token names
the last thing returned, so a page continues after it even when things
before it were deleted, as measured on AWS. Like AWS's, a token
continues only the request that issued it: another queryString, or an
indexName or queryVersion sent differently, is "nextToken was from a
request with different parameters", and an empty, forged, edited or
truncated token is "Invalid nextToken". A new parser,
IotFleetIndexQuery, evaluates field:value terms with case-insensitive
values, case-sensitive field names, * and ? wildcards, existence and
match-all, quoted values, AND, OR and NOT with their symbolic forms,
leading - negation and parentheses. Precedence is the one measured on
AWS, where whitespace is an AND that binds looser than OR. The fields
are thingName, thingId, thingTypeName, thingGroupNames and attributes.*.

Requests are validated with the messages and in the order measured on
AWS: a body that is not a JSON object and every member type, member
constraints, index name, query version, a disabled index, the query,
then the page token. Within the query a syntax error comes first, then
the 12-term limit, in which each value of a field group counts and the
field does not, then the first other error, where the field of a group
is checked like any other field. A range counts as one term, and a
malformed range or an unescaped bracket outside one is a syntax error.
AWS's limits hold: a queryString of at most 1000 characters, at most 12
terms, at most two * wildcards in a value and no value starting with ?.
maxResults takes any number, truncated toward zero and capped at the int
range as on AWS. A classic shadow field needs REGISTRY_AND_SHADOW
indexing, and a named shadow field named shadow indexing and a shadow in
its filter, or it is AWS's invalid field name. Constructs AWS accepts
but Floci does not evaluate, such as ranges, comparisons, free text,
field grouping and shadow or Device Defender fields, are refused with
InvalidQueryException instead of matching nothing, and so is a search of
AWS_ThingGroups. Connectivity fields are refused like shadow and Device
Defender fields: AWS's InvalidRequestException while connectivity
indexing is off, InvalidQueryException once it is on. Documents leave
out the members a thing lacks and never carry a shadow or a
connectivity member, where AWS adds connectivity while connectivity
indexing is on.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-10 13:56:54 -04:00
1 parent 2015d01864
commit 1082941bc2
8 files changed
+1667 -23

No files matched your search

@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.iot;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
@@ -9,17 +10,20 @@ import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
/**
* Drives fleet indexing the way the AWS SDKs do: UpdateIndexingConfiguration and
* GetIndexingConfiguration on {@code /indexing/config}, DescribeIndex on {@code /indices/{indexName}}.
* Every test signs as its own account, so the configurations they store never meet.
* GetIndexingConfiguration on {@code /indexing/config}, DescribeIndex on {@code /indices/{indexName}}
* and SearchIndex on {@code /indices/search}. Every test signs as its own account, so the
* configurations and things they store never meet.
*/
@QuarkusTest
class IotFleetIndexingIntegrationTest {
@@ -283,4 +287,208 @@ class IotFleetIndexingIntegrationTest {
.statusCode(200)
.body("thingIndexingConfiguration.thingIndexingMode", equalTo("OFF"));
}
private static void post(String auth, String path, String body) {
given()
.header("Authorization", auth)
.contentType("application/json")
.body(body)
.when()
.post(path)
.then()
.statusCode(200);
}
private static ValidatableResponse search(String auth, String body) {
return given()
.header("Authorization", auth)
.contentType("application/json")
.body(body)
.when()
.post("/indices/search")
.then();
}
@Test
void searchIndexReturnsTheSdkWireShape() {
String auth = auth("111100000013", "us-east-1");
update(auth, """
{"thingIndexingConfiguration": {"thingIndexingMode": "REGISTRY", "thingConnectivityIndexingMode": "STATUS"}}
""");
post(auth, "/thing-types/search-sensor", "{}");
post(auth, "/thing-groups/search-north", "{}");
post(auth, "/things/search-a", """
{"thingTypeName": "search-sensor", "attributePayload": {"attributes": {"provider": "Acme", "site": "north"}}}
""");
post(auth, "/things/search-b", """
{"attributePayload": {"attributes": {"provider": "acme"}}}
""");
post(auth, "/things/search-c", "{}");
given()
.header("Authorization", auth)
.contentType("application/json")
.body("""
{"thingGroupName": "search-north", "thingName": "search-a"}
""")
.when()
.put("/thing-groups/addThingToThingGroup")
.then()
.statusCode(200);
search(auth, """
{"queryString": "attributes.provider:acme AND thingTypeName:search-sensor"}
""")
.statusCode(200)
.body("$", aMapWithSize(1))
.body("things", hasSize(1))
.body("things[0]", aMapWithSize(5))
.body("things[0].thingName", equalTo("search-a"))
.body("things[0].thingId", not(emptyOrNullString()))
.body("things[0].thingTypeName", equalTo("search-sensor"))
.body("things[0].thingGroupNames", contains("search-north"))
.body("things[0].attributes.provider", equalTo("Acme"))
.body("things[0].attributes.site", equalTo("north"))
.body("things[0]", not(hasKey("connectivity")));
search(auth, """
{"queryString": "thingName:search-c", "queryVersion": "2017-09-30", "indexName": "AWS_Things"}
""")
.statusCode(200)
.body("things[0]", aMapWithSize(2))
.body("things[0].thingName", equalTo("search-c"))
.body("things[0]", not(hasKey("connectivity")));
search(auth, """
{"queryString": "connectivity.connected:true"}
""")
.statusCode(400)
.body("__type", equalTo("InvalidQueryException"))
.body("message", equalTo("Floci does not support the field connectivity.connected in fleet index "
+ "queries, query string: connectivity.connected:true"));
String nextToken = search(auth, """
{"queryString": "thingName:search-*", "maxResults": 2}
""")
.statusCode(200)
.body("things.thingName", contains("search-a", "search-b"))
.body("nextToken", notNullValue())
.extract().path("nextToken");
search(auth, "{\"queryString\": \"thingName:search-*\", \"maxResults\": 2, \"nextToken\": \"" + nextToken + "\"}")
.statusCode(200)
.body("things.thingName", contains("search-c"))
.body("$", not(hasKey("nextToken")));
}
@Test
void searchIndexRejectsBadRequestsWithAwsErrors() {
String auth = auth("111100000008", "us-east-1");
update(auth, """
{"thingIndexingConfiguration": {"thingIndexingMode": "REGISTRY"}}
""");
search(auth, "{}")
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo("1 validation error detected: Value null at 'queryString' failed to satisfy "
+ "constraint: Member must not be null"));
search(auth, """
{"queryString": "*", "queryVersion": "2017-09-31"}
""")
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo("Invalid queryVersion. Expected one of: [2017-09-30]"));
search(auth, """
{"queryString": "*", "nextToken": "bogus"}
""")
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo("Invalid nextToken"));
search(auth, """
{"queryString": "ThingName:x"}
""")
.statusCode(400)
.body("__type", equalTo("InvalidQueryException"))
.body("message", equalTo("Unable to parse query, invalid field name, field name: ThingName, "
+ "query string: ThingName:x"));
search(auth, """
{"queryString": "thingName>a"}
""")
.statusCode(400)
.body("__type", equalTo("InvalidQueryException"))
.body("message", equalTo("Floci does not support comparisons in fleet index queries, "
+ "query string: thingName>a"));
search(auth, """
{"queryString": "connectivity.connected:true"}
""")
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo("Query includes one or more constraints for Connectivity attribute, "
+ "but Connectivity indexing is not enabled for AWS_Things index"));
search(auth, """
{"queryString": "*", "maxResults": 9223372036854775808}
""")
.statusCode(200);
search(auth, """
{"queryString": "*", "maxResults": -9223372036854775809}
""")
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo("1 validation error detected: Value '-2147483648' at 'maxResults' failed to "
+ "satisfy constraint: Member must have value greater than or equal to 1"));
}
@Test
void searchIndexOfADisabledIndexIsNotFound() {
String auth = auth("111100000009", "us-east-1");
search(auth, """
{"queryString": "*"}
""")
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"))
.body("message", equalTo("Index AWS_Things does not exist. "
+ "Please enable index by calling UpdateIndexingConfiguration"));
search(auth, """
{"queryString": "*", "indexName": "AWS_ThingGroups"}
""")
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"))
.body("message", equalTo("Index AWS_ThingGroups does not exist. "
+ "Please enable index by calling UpdateIndexingConfiguration"));
update(auth, """
{"thingGroupIndexingConfiguration": {"thingGroupIndexingMode": "ON"}}
""");
search(auth, """
{"queryString": "*", "indexName": "AWS_ThingGroups"}
""")
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo("Floci does not support searching AWS_ThingGroups"));
}
@Test
void searchIndexIsIsolatedPerAccountAndRegion() {
String home = auth("111100000010", "us-east-1");
String otherAccount = auth("111100000011", "us-east-1");
String otherRegion = auth("111100000010", "eu-west-1");
String indexing = """
{"thingIndexingConfiguration": {"thingIndexingMode": "REGISTRY"}}
""";
update(home, indexing);
update(otherAccount, indexing);
update(otherRegion, indexing);
post(home, "/things/isolated-thing", "{}");
String query = """
{"queryString": "thingName:isolated-thing"}
""";
search(home, query)
.statusCode(200)
.body("things.thingName", contains("isolated-thing"));
search(otherAccount, query)
.statusCode(200)
.body("things", empty());
search(otherRegion, query)
.statusCode(200)
.body("things", empty());
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.iot;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.iot.model.IotIndexingConfiguration;
@@ -14,13 +15,22 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -62,8 +72,13 @@ class IotFleetIndexingServiceTest {
new Field("thingGroupName", "String"),
new Field("thingGroupId", "String"));
private static final String CONNECTIVITY_NOT_ENABLED = "Query includes one or more constraints for Connectivity "
+ "attribute, but Connectivity indexing is not enabled for AWS_Things index";
private final ObjectMapper mapper = new ObjectMapper();
private final IotFleetIndexingService service = new IotFleetIndexingService(new InMemoryStorage<>());
private final IotServiceTestSupport iot = new IotServiceTestSupport(REGION, null);
private final IotFleetIndexingService service =
new IotFleetIndexingService(new InMemoryStorage<>(), iot.service);
private JsonNode json(String text) {
try {
@@ -675,4 +690,640 @@ class IotFleetIndexingServiceTest {
""");
assertDescribeFails("AWS_Thing", "InvalidRequestException", 400, "Unrecognized indexName AWS_Thing");
}
/**
* Four things in the default region: alpha-1 and beta-1 of type sensor, alpha-1 and alpha-2 in
* thing groups, attribute values in mixed case, and gamma with nothing but its name.
*/
private void fleet(String thingIndexing) {
update("{\"thingIndexingConfiguration\": " + thingIndexing + "}");
IotService registry = iot.service;
registry.createThingType("sensor", mapper.createObjectNode(), REGION);
registry.createThingGroup("north-group", mapper.createObjectNode(), REGION);
registry.createThingGroup("south-group", mapper.createObjectNode(), REGION);
registry.createThing("alpha-1", Map.of("site", "North", "provider", "acme"), "sensor", REGION);
registry.createThing("alpha-2", Map.of("site", "south", "provider", "ACME"), null, REGION);
registry.createThing("beta-1", Map.of("provider", "other"), "sensor", REGION);
registry.createThing("gamma", Map.of(), null, REGION);
registry.addThingToThingGroup("north-group", "alpha-1", REGION);
registry.addThingToThingGroup("south-group", "alpha-2", REGION);
registry.addThingToThingGroup("north-group", "alpha-2", REGION);
}
private void fleet() {
fleet("{\"thingIndexingMode\": \"REGISTRY\"}");
}
private ObjectNode query(String queryString) {
return mapper.createObjectNode().put("queryString", queryString);
}
private IotService.Page<ObjectNode> search(ObjectNode request) {
return service.searchIndex(request, REGION);
}
private List<String> names(String queryString) {
return search(query(queryString)).items().stream().map(thing -> thing.path("thingName").asText()).toList();
}
private ObjectNode document(String thingName) {
List<ObjectNode> things = search(query("thingName:" + thingName)).items();
assertEquals(1, things.size());
return things.get(0);
}
private void assertSearchFails(ObjectNode request, String code, int status, String message) {
AwsException failure = assertThrows(AwsException.class, () -> search(request));
assertEquals(code, failure.getErrorCode());
assertEquals(status, failure.getHttpStatus());
assertEquals(message, failure.getMessage());
}
private void assertQueryFails(String queryString, String message) {
assertSearchFails(query(queryString), "InvalidQueryException", 400, message + ", query string: " + queryString);
}
private void assertUnsupported(String queryString, String construct) {
assertQueryFails(queryString, "Floci does not support " + construct + " in fleet index queries");
}
@Test
void searchMatchesValuesCaseInsensitivelyInThingNameOrder() {
fleet();
assertEquals(List.of("alpha-1"), names("thingName:ALPHA-1"));
assertEquals(List.of("alpha-1"), names("attributes.site:north"));
assertEquals(List.of("alpha-1", "alpha-2"), names("attributes.provider:Acme"));
assertEquals(List.of("alpha-1", "beta-1"), names("thingTypeName:SENSOR"));
assertEquals(List.of("alpha-1", "alpha-2"), names("thingGroupNames:north-group"));
assertEquals(List.of("alpha-2"), names("thingGroupNames:south-group"));
assertEquals(List.of("gamma"), names("thingId:" + iot.service.describeThing("gamma", REGION).getThingId()));
assertEquals(List.of("alpha-1"), names("thingName:\"Alpha-1\""));
assertEquals(List.of(), names("thingName:alpha"));
assertEquals(List.of(), names("attributes.missing:x"));
}
@Test
void fieldNamesAreCaseSensitive() {
fleet();
assertEquals(List.of(), names("attributes.Site:north"));
assertQueryFails("ThingName:alpha-1", "Unable to parse query, invalid field name, field name: ThingName");
assertQueryFails("thingname:alpha-1", "Unable to parse query, invalid field name, field name: thingname");
}
@Test
void wildcardsMatchAnyRunOrOneCharacter() {
fleet();
assertEquals(List.of("alpha-1", "alpha-2"), names("thingName:alpha*"));
assertEquals(List.of("alpha-1", "alpha-2"), names("thingName:ALPHA-?"));
assertEquals(List.of("beta-1"), names("thingName:b?ta-1"));
assertEquals(List.of("gamma"), names("thingName:*a"));
assertEquals(List.of("alpha-1", "alpha-2"), names("attributes.provider:a*e"));
assertEquals(List.of(), names("thingName:alpha?"));
assertEquals(List.of(), names("thingName:\"alpha*\""));
assertEquals(List.of(), names("thingName:alpha\\*"));
}
@Test
void existenceAndMatchAllQueries() {
fleet();
assertEquals(List.of("alpha-1", "beta-1"), names("thingTypeName:*"));
assertEquals(List.of("alpha-1", "alpha-2"), names("attributes.site:*"));
assertEquals(List.of("alpha-1", "alpha-2"), names("thingGroupNames:*"));
assertEquals(List.of("alpha-1", "alpha-2", "beta-1", "gamma"), names("*"));
}
@Test
void booleanOperatorsFollowTheMeasuredAwsPrecedence() {
fleet();
// AND binds tighter than OR.
assertEquals(List.of("alpha-2", "gamma"),
names("thingName:gamma OR attributes.provider:acme AND attributes.site:south"));
assertEquals(List.of("alpha-2", "gamma"),
names("attributes.provider:acme AND attributes.site:south OR thingName:gamma"));
// Whitespace is an AND that binds looser than OR: (gamma OR acme) AND south.
assertEquals(List.of("alpha-2"), names("thingName:gamma OR attributes.provider:acme attributes.site:south"));
assertEquals(List.of("alpha-1", "alpha-2"), names("thingName:alpha* attributes.provider:acme"));
assertEquals(List.of("alpha-2", "gamma"),
names("(thingName:gamma OR attributes.provider:acme) AND NOT thingTypeName:sensor"));
// NOT applies to the term after it only.
assertEquals(List.of("beta-1"), names("NOT attributes.provider:acme AND thingTypeName:sensor"));
assertEquals(List.of("alpha-2", "gamma"), names("NOT thingTypeName:sensor"));
assertEquals(List.of("alpha-2", "gamma"), names("-thingTypeName:sensor"));
assertEquals(List.of("alpha-2"), names("thingName:alpha* -thingTypeName:sensor"));
assertEquals(List.of("alpha-2"), names("thingName:alpha* - thingTypeName:sensor"));
assertEquals(List.of("alpha-1", "alpha-2", "gamma"), names("-(thingTypeName:sensor AND attributes.provider:other)"));
// The symbolic forms AWS accepts.
assertEquals(List.of("alpha-2", "gamma"), names("!thingTypeName:sensor"));
assertEquals(List.of("alpha-1"), names("thingTypeName:sensor && attributes.site:north"));
assertEquals(List.of("beta-1", "gamma"), names("thingName:gamma || attributes.provider:other"));
}
@Test
void documentsCarryOnlyTheMembersAThingHas() {
fleet();
assertEquals(json("{\"thingName\": \"alpha-1\", \"thingId\": \""
+ iot.service.describeThing("alpha-1", REGION).getThingId() + "\", \"thingTypeName\": \"sensor\", "
+ "\"thingGroupNames\": [\"north-group\"], \"attributes\": {\"site\": \"North\", \"provider\": \"acme\"}}"),
document("alpha-1"));
assertEquals(json("[\"north-group\", \"south-group\"]"), document("alpha-2").get("thingGroupNames"));
assertEquals(json("{\"thingName\": \"gamma\", \"thingId\": \""
+ iot.service.describeThing("gamma", REGION).getThingId() + "\"}"), document("gamma"));
}
@Test
void connectivityFieldsAreRefusedLikeShadowAndDeviceDefenderFields() {
fleet("{\"thingIndexingMode\": \"REGISTRY\", \"thingConnectivityIndexingMode\": \"STATUS\"}");
assertUnsupported("connectivity.connected:true", "the field connectivity.connected");
assertUnsupported("connectivity.clientId:alpha-1", "the field connectivity.clientId");
assertUnsupported("connectivity.disconnectReason:CONNECTION_LOST", "the field connectivity.disconnectReason");
assertUnsupported("thingName:gamma OR connectivity.connected:false", "the field connectivity.connected");
}
@Test
void documentsCarryNoConnectivityWhileConnectivityIsIndexed() {
fleet("{\"thingIndexingMode\": \"REGISTRY\", \"thingConnectivityIndexingMode\": \"STATUS\"}");
assertFalse(document("alpha-1").has("connectivity"));
assertEquals(json("{\"thingName\": \"gamma\", \"thingId\": \""
+ iot.service.describeThing("gamma", REGION).getThingId() + "\"}"), document("gamma"));
}
@Test
void connectivityQueriesNeedConnectivityIndexing() {
fleet();
assertSearchFails(query("connectivity.connected:true"), "InvalidRequestException", 400, CONNECTIVITY_NOT_ENABLED);
assertSearchFails(query("thingName:gamma OR connectivity.clientId:gamma"), "InvalidRequestException", 400,
CONNECTIVITY_NOT_ENABLED);
assertFalse(document("alpha-1").has("connectivity"));
}
@Test
void shadowAndDeviceDefenderQueriesNeedTheirIndexing() {
fleet();
assertSearchFails(query("shadow.reported.x:1"), "InvalidRequestException", 400, "Query includes one or more "
+ "constraints for Shadow attribute, but Shadow indexing is not enabled for AWS_Things index");
assertSearchFails(query("deviceDefender.violationCount:1"), "InvalidRequestException", 400,
"Query includes one or more constraints for Devicedefender attribute, but Devicedefender indexing "
+ "is not enabled for AWS_Things index");
}
@Test
void classicAndNamedShadowFieldsFollowTheirOwnIndexing() {
fleet("""
{"thingIndexingMode": "REGISTRY", "namedShadowIndexingMode": "ON",
"filter": {"namedShadowNames": ["building"]}}
""");
assertSearchFails(query("shadow.reported.x:1"), "InvalidRequestException", 400, "Query includes one or more "
+ "constraints for Shadow attribute, but Shadow indexing is not enabled for AWS_Things index");
assertUnsupported("shadow.name.building.reported.type:x", "the field shadow.name.building.reported.type");
assertQueryFails("shadow.name.other.reported.a:1",
"Unable to parse query, invalid field name, field name: shadow.name.other.reported.a");
assertQueryFails("shadow.name.building:x",
"Unable to parse query, invalid field name, field name: shadow.name.building");
assertQueryFails("shadow.name:x", "Unable to parse query, invalid field name, field name: shadow.name");
update("""
{"thingIndexingConfiguration": {"thingIndexingMode": "REGISTRY_AND_SHADOW"}}
""");
assertQueryFails("shadow.name.building.reported.type:x",
"Unable to parse query, invalid field name, field name: shadow.name.building.reported.type");
assertUnsupported("shadow.reported.x:1", "the field shadow.reported.x");
}
@Test
void awsValidConstructsFlociDoesNotEvaluateAreRefused() {
fleet("""
{"thingIndexingMode": "REGISTRY_AND_SHADOW", "thingConnectivityIndexingMode": "STATUS",
"deviceDefenderIndexingMode": "VIOLATIONS"}
""");
assertUnsupported("attributes.site:[a TO z]", "range queries");
assertUnsupported("attributes.site:{a TO z}", "range queries");
assertUnsupported("thingName>a", "comparisons");
assertUnsupported("attributes.count>=5", "comparisons");
assertUnsupported("attributes.count<5", "comparisons");
assertUnsupported("attributes.count<=5", "comparisons");
assertUnsupported("alpha", "free text terms");
assertUnsupported("thingName:alpha-1 or thingName:gamma", "free text terms");
assertUnsupported("\"alpha-1\"", "free text terms");
assertUnsupported("attributes.site:(north OR south)", "field grouping");
assertUnsupported("shadow.reported.x:1", "the field shadow.reported.x");
assertUnsupported("deviceDefender.violationCount:1", "the field deviceDefender.violationCount");
assertUnsupported("connectivity.timestamp:0", "the field connectivity.timestamp");
assertUnsupported("connectivity.connected:true", "the field connectivity.connected");
}
@Test
void malformedQueriesAreSyntaxErrors() {
fleet();
for (String queryString : List.of("thingName:", "thingName:(a", "thingName:a AND", "AND thingName:a",
"thingName:a OR", "thingName:a NOT", "NOT", "!", "()", "thingName:a)", "thingName:a -",
"NOT NOT thingName:a", "NOT -thingName:a", "-NOT thingName:a", "thingName:a AND OR thingName:b",
"thingName:\"a", "thingName:a\"", " ", "attributes.count:>5")) {
assertQueryFails(queryString, "Unable to parse query, invalid syntax");
}
}
@Test
void rangesAreParsedAsAwsParsesThem() {
fleet();
for (String queryString : List.of("thingName:[", "thingName:[a", "thingName:[a TO", "thingName:[a TO b",
"thingName:[a to b]", "thingName:[a TO b TO c]", "thingName:{", "thingName:]", "thingName:[]",
"thingName:a]", "thingName:[aTOb]", "thingName:[a TO b]]", "thingName:a]b", "thingName:a[b",
"thingName:a}", "thingName:a{b", "attributes.a[0]:x", "thingName:[TO b]", "thingName:[a TO]",
"[a TO]", "thingName:[a TO b)", "thingName:[a\tTO\tb]")) {
assertQueryFails(queryString, "Unable to parse query, invalid syntax");
}
assertQueryFails("bogusfield:1 OR thingName:[a", "Unable to parse query, invalid syntax");
for (String queryString : List.of("thingName:[a b]", "thingName:[a TO b}", "thingName:[* TO b]",
"thingName:[ a TO b ]", "thingName:[\"a\" TO \"b\"]", "thingName:[\"a]\" TO b]",
"thingName:[a[ TO b]", "NOT thingName:[a TO b]", "(thingName:[a TO b])",
"thingName:[a TO b](thingName:c)")) {
assertUnsupported(queryString, "range queries");
}
assertUnsupported("[a TO b]", "free text terms");
assertEquals(List.of(), names("thingName:a\\]"));
assertEquals(List.of(), names("thingName:\"a]\""));
String range = "thingName:[a TO b] ";
String eight = String.join(" ", Collections.nCopies(8, "thingName:x"));
assertUnsupported(range.repeat(4) + eight, "range queries");
assertQueryFails(range.repeat(5) + eight,
"Unable to parse query, number of terms cannot exceed 12, terms found: 13");
}
@Test
void unknownFieldsAreInvalidFieldNames() {
fleet();
for (String field : List.of("bogusfield", "registry.version", "*", "attributes", "attributes.")) {
assertQueryFails(field + ":1", "Unable to parse query, invalid field name, field name: " + field);
}
}
@Test
void queryTypesAwsRejectsAreRejectedWithItsMessages() {
fleet();
assertQueryFails("+thingName:a", "Unable to parse query, unsupported operator - \"+\"");
assertQueryFails("thingName:a~", "Unable to parse query, unsupported query type - fuzzy");
assertQueryFails("thingName:a~2", "Unable to parse query, unsupported query type - fuzzy");
assertQueryFails("thingName:/a/", "Unable to parse query, unsupported query type - regular expression");
assertQueryFails("thingName:a^2", "Unable to parse query, unsupported query type - boost");
}
@Test
void escapedFuzzyAndBoostCharactersAreLiteral() {
fleet();
assertEquals(List.of(), names("thingName:a\\~b"));
assertEquals(List.of(), names("attributes.x:a\\^b"));
assertEquals(List.of(), names("thingName:\"a~b^c\""));
assertQueryFails("thingName:a~", "Unable to parse query, unsupported query type - fuzzy");
}
@Test
void aQueryStringOfAtMost1000CodePointsIsAccepted() {
fleet();
String longest = "thingName:" + "\u00e9".repeat(990);
String tooLong = longest + "\u00e9";
assertEquals(List.of(), names(longest));
assertSearchFails(query(tooLong), "InvalidRequestException", 400, "1 validation error detected: Value '"
+ tooLong + "' at 'queryString' failed to satisfy constraint: "
+ "Member must have length less than or equal to 1000");
assertEquals(List.of("gamma"), names("(".repeat(490) + "thingName:gamma" + ")".repeat(490)));
}
@Test
void aQueryOfAtMost12TermsIsAccepted() {
fleet();
String twelve = String.join(" OR ", Collections.nCopies(12, "thingName:gamma"));
String tooMany = "Unable to parse query, number of terms cannot exceed 12, terms found: 13";
assertEquals(List.of("gamma"), names(twelve));
assertEquals(List.of("alpha-1", "alpha-2", "beta-1", "gamma"),
names(String.join(" OR ", Collections.nCopies(7, "NOT thingName:z"))));
assertQueryFails(twelve + " OR thingName:gamma", tooMany);
assertQueryFails("* " + twelve, tooMany);
assertQueryFails("(" + twelve + ") AND NOT thingName:z", tooMany);
assertQueryFails("bogusfield:1 OR " + twelve, tooMany);
assertQueryFails(twelve + " OR thingName:*a*b*c*", tooMany);
}
@Test
void syntaxErrorsWinOverTheTermLimitAndOtherQueryErrors() {
fleet();
for (String queryString : List.of("thingName:z OR ".repeat(12) + "thingName:", "bogusfield:1 OR thingName:",
"thingName:a~ OR thingName:", "thingName:*a*b*c* OR thingName:",
"attributes.site:[a TO b] OR thingName:", "+thingName:a OR thingName:", "thingName:?a OR thingName:",
"bogusfield:1 OR thingName:<a", "bogusfield:1 OR (thingName:a", "bogusfield:1 AND", "bogusfield:",
"deviceDefender.violationCount:1 OR thingName:")) {
assertQueryFails(queryString, "Unable to parse query, invalid syntax");
}
}
@Test
void theTermLimitWinsOverAFieldWhoseIndexingIsOff() {
fleet();
List<String> twelve = IntStream.rangeClosed(1, 12).mapToObj(i -> "thingName:z" + i).toList();
assertQueryFails("deviceDefender.violationCount:1 OR " + String.join(" OR ", twelve) + " OR thingName:y",
"Unable to parse query, number of terms cannot exceed 12, terms found: 14");
}
@Test
void fieldGroupValuesCountAsTermsButTheFieldDoesNot() {
fleet();
List<String> values = List.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m");
String tooMany = "Unable to parse query, number of terms cannot exceed 12, terms found: 13";
assertQueryFails("thingName:(" + String.join(" OR ", values) + ")", tooMany);
assertQueryFails("thingName:(" + String.join(" OR ", values.subList(0, 12)) + ") OR thingName:x", tooMany);
assertUnsupported("thingName:(" + String.join(" OR ", values.subList(0, 11)) + ") OR thingName:x",
"field grouping");
for (String queryString : List.of("thingName:()", "thingName:(a OR)", "thingName:(a OR b")) {
assertQueryFails(queryString, "Unable to parse query, invalid syntax");
}
}
@Test
void aFieldGroupChecksItsFieldFirst() {
fleet();
String invalidFieldName = "Unable to parse query, invalid field name, field name: ";
assertQueryFails("bogusfield:(a OR b)", invalidFieldName + "bogusfield");
assertQueryFails("registry.version:(1 OR 2)", invalidFieldName + "registry.version");
assertQueryFails("attributes:(a OR b)", invalidFieldName + "attributes");
assertQueryFails("bogusfield:(a OR b) OR deviceDefender.violationCount:1", invalidFieldName + "bogusfield");
assertQueryFails("attributes.a[0]:(x OR y)", "Unable to parse query, invalid syntax");
assertQueryFails("bogusfield:(a OR b) OR thingName:", "Unable to parse query, invalid syntax");
assertQueryFails("bogusfield:(a OR b OR c OR d OR e OR f OR g OR h OR i OR j OR k OR l OR m)",
"Unable to parse query, number of terms cannot exceed 12, terms found: 13");
assertSearchFails(query("connectivity.connected:(true OR false)"), "InvalidRequestException", 400,
CONNECTIVITY_NOT_ENABLED);
assertSearchFails(query("deviceDefender.violationCount:(1 OR 2)"), "InvalidRequestException", 400,
"Query includes one or more constraints for Devicedefender attribute, but Devicedefender indexing "
+ "is not enabled for AWS_Things index");
assertUnsupported("thingName:(a OR b)", "field grouping");
}
@Test
void aValueTakesAtMostTwoUnescapedWildcards() {
fleet();
assertQueryFails("thingName:*a*b*", "Unable to parse query, invalid value - too many wildcards (*). "
+ "The maximum allowed per term is 2, field name: thingName, value: *a*b*");
assertQueryFails("attributes.x:*a*b*c", "Unable to parse query, invalid value - too many wildcards (*). "
+ "The maximum allowed per term is 2, field name: attributes.x, value: *a*b*c");
assertEquals(List.of("alpha-1", "alpha-2", "beta-1", "gamma"), names("thingName:*a*"));
assertEquals(List.of(), names("thingName:*a\\*b*"));
assertEquals(List.of(), names("thingName:\"*a*b*c*\""));
assertEquals(List.of(), names("thingName:a\\*b\\*c\\*d"));
}
@Test
void aValueCannotStartWithAQuestionMark() {
fleet();
assertQueryFails("thingName:?a", "Unable to parse query, invalid value - wildcard character (?) is not "
+ "allowed at the start of the value, field name: thingName, value: ?a");
assertEquals(List.of(), names("thingName:a?b"));
assertEquals(List.of(), names("thingName:a?b?c?d?e?f"));
}
@Test
void requestsAreValidatedInTheMeasuredAwsOrder() {
assertSearchFails(mapper.createObjectNode(), "InvalidRequestException", 400, "1 validation error detected: "
+ "Value null at 'queryString' failed to satisfy constraint: Member must not be null");
assertSearchFails(query(""), "InvalidRequestException", 400, "1 validation error detected: Value '' at "
+ "'queryString' failed to satisfy constraint: Member must have length greater than or equal to 1");
assertSearchFails(query("*").put("maxResults", 0), "InvalidRequestException", 400,
"1 validation error detected: Value '0' at 'maxResults' failed to satisfy constraint: "
+ "Member must have value greater than or equal to 1");
assertSearchFails(query("*").put("indexName", ""), "InvalidRequestException", 400,
"indexName cannot be empty.");
assertSearchFails(query("*").put("indexName", "Nope").put("queryVersion", "bogus"), "InvalidRequestException",
400, "Invalid queryVersion. Expected one of: [2017-09-30]");
assertSearchFails(query("*").put("indexName", "Nope"), "InvalidRequestException", 400,
"Unrecognized indexName Nope");
assertSearchFails(query("bogusfield:1"), "ResourceNotFoundException", 404,
"Index AWS_Things does not exist. Please enable index by calling UpdateIndexingConfiguration");
assertSearchFails(query("*").put("indexName", "AWS_ThingGroups"), "ResourceNotFoundException", 404,
"Index AWS_ThingGroups does not exist. Please enable index by calling UpdateIndexingConfiguration");
update("""
{"thingIndexingConfiguration": {"thingIndexingMode": "REGISTRY"},
"thingGroupIndexingConfiguration": {"thingGroupIndexingMode": "ON"}}
""");
assertSearchFails(query("*").put("indexName", "AWS_ThingGroups"), "InvalidRequestException", 400,
"Floci does not support searching AWS_ThingGroups");
assertEquals(List.of(), search(query("*").put("indexName", "AWS_Things").put("queryVersion", "2017-09-30"))
.items());
}
@Test
void pagesCarryATokenUntilTheLastPage() {
fleet();
IotService.Page<ObjectNode> first = search(query("thingName:alpha*").put("maxResults", 1));
assertEquals("alpha-1", first.items().get(0).path("thingName").asText());
assertEquals(1, first.items().size());
assertNotNull(first.nextToken());
IotService.Page<ObjectNode> second =
search(query("thingName:alpha*").put("maxResults", 1).put("nextToken", first.nextToken()));
assertEquals("alpha-2", second.items().get(0).path("thingName").asText());
assertNull(second.nextToken());
assertNull(search(query("thingName:alpha*")).nextToken());
assertSearchFails(query("*").put("nextToken", "bogus"), "InvalidRequestException", 400, "Invalid nextToken");
assertSearchFails(query("bogusfield:1").put("nextToken", "bogus"), "InvalidQueryException", 400,
"Unable to parse query, invalid field name, field name: bogusfield, query string: bogusfield:1");
}
@Test
void aHugeMaxResultsReturnsTheRemainingThingsWithoutAToken() {
fleet();
String token = search(query("*").put("maxResults", 1)).nextToken();
IotService.Page<ObjectNode> rest =
search(query("*").put("maxResults", Integer.MAX_VALUE).put("nextToken", token));
assertEquals(List.of("alpha-2", "beta-1", "gamma"), thingNames(rest));
assertNull(rest.nextToken());
}
@Test
void aPageTokenContinuesAfterTheLastThingReturnedWhenEarlierThingsAreDeleted() {
fleet();
IotService.Page<ObjectNode> first = search(query("thingName:alpha*").put("maxResults", 1));
assertEquals(List.of("alpha-1"), thingNames(first));
assertNotNull(first.nextToken());
iot.service.deleteThing("alpha-1", REGION);
IotService.Page<ObjectNode> second =
search(query("thingName:alpha*").put("maxResults", 1).put("nextToken", first.nextToken()));
assertEquals(List.of("alpha-2"), thingNames(second));
assertNull(second.nextToken());
}
@Test
void aPageTokenOnlyContinuesTheRequestThatIssuedIt() {
fleet();
String token = search(query("thingName:alpha*").put("maxResults", 1)).nextToken();
assertEquals(List.of("alpha-2"),
thingNames(search(query("thingName:alpha*").put("maxResults", 5).put("nextToken", token))));
assertEquals(List.of("alpha-2"), thingNames(search(query("thingName:alpha*").put("nextToken", token))));
String differentParameters = "nextToken was from a request with different parameters";
assertSearchFails(query("thingName:alpha* ").put("nextToken", token), "InvalidRequestException", 400,
differentParameters);
assertSearchFails(query("*").put("nextToken", token), "InvalidRequestException", 400, differentParameters);
assertSearchFails(query("thingName:alpha*").put("indexName", "AWS_Things").put("nextToken", token),
"InvalidRequestException", 400, differentParameters);
assertSearchFails(query("thingName:alpha*").put("queryVersion", "2017-09-30").put("nextToken", token),
"InvalidRequestException", 400, differentParameters);
String explicit = search(query("thingName:alpha*").put("indexName", "AWS_Things")
.put("queryVersion", "2017-09-30").put("maxResults", 1)).nextToken();
assertEquals(List.of("alpha-2"), thingNames(search(query("thingName:alpha*").put("indexName", "AWS_Things")
.put("queryVersion", "2017-09-30").put("nextToken", explicit))));
assertSearchFails(query("thingName:alpha*").put("nextToken", explicit), "InvalidRequestException", 400,
differentParameters);
assertSearchFails(query("bogusfield:1").put("nextToken", token), "InvalidQueryException", 400,
"Unable to parse query, invalid field name, field name: bogusfield, query string: bogusfield:1");
}
@Test
void aTokenThisOperationCouldNotHaveIssuedIsInvalid() {
fleet();
String bareThingName = Base64.getUrlEncoder().withoutPadding()
.encodeToString("alpha-1".getBytes(StandardCharsets.UTF_8));
for (String token : List.of("YQ", "", "AAAA", bareThingName)) {
assertSearchFails(query("*").put("nextToken", token), "InvalidRequestException", 400,
"Invalid nextToken");
}
String issued = search(query("thingName:alpha*").put("maxResults", 1)).nextToken();
String decoded = new String(Base64.getUrlDecoder().decode(issued), StandardCharsets.UTF_8);
String edited = Base64.getUrlEncoder().withoutPadding()
.encodeToString((decoded.substring(0, decoded.length() - 1) + "0").getBytes(StandardCharsets.UTF_8));
String shortened = Base64.getUrlEncoder().withoutPadding()
.encodeToString(decoded.substring(0, decoded.length() - 1).getBytes(StandardCharsets.UTF_8));
String truncated = issued.substring(0, issued.length() - 2);
for (String token : List.of(edited, shortened, truncated)) {
assertSearchFails(query("thingName:alpha*").put("nextToken", token), "InvalidRequestException", 400,
"Invalid nextToken");
}
assertEquals(List.of("alpha-2"), thingNames(search(query("thingName:alpha*").put("nextToken", issued))));
}
@Test
void maxResultsIsAnyJsonNumberOfAtLeastOne() {
fleet();
assertEquals(List.of("alpha-1"), thingNames(search(query("*").put("maxResults", 1.5))));
IotService.Page<ObjectNode> all = search(query("*").put("maxResults", 2147483648L));
assertEquals(List.of("alpha-1", "alpha-2", "beta-1", "gamma"), thingNames(all));
assertNull(all.nextToken());
assertEquals(4, search(query("*").put("maxResults", 500)).items().size());
assertSearchFails(query("*").put("maxResults", "5"), "SerializationException", 400,
"maxResults must be a JSON number");
assertSearchFails(query("*").put("maxResults", true), "SerializationException", 400,
"maxResults must be a JSON number");
}
@Test
void maxResultsIsTruncatedAndSaturatedAtTheIntRange() {
fleet();
IotService.Page<ObjectNode> all = search(query("*").put("maxResults", new BigInteger("9223372036854775808")));
assertEquals(List.of("alpha-1", "alpha-2", "beta-1", "gamma"), thingNames(all));
assertNull(all.nextToken());
assertEquals(4, search(query("*").put("maxResults", new BigDecimal("1e30"))).items().size());
assertSearchFails(query("*").put("maxResults", new BigInteger("-9223372036854775809")),
"InvalidRequestException", 400, "1 validation error detected: Value '-2147483648' at 'maxResults' "
+ "failed to satisfy constraint: Member must have value greater than or equal to 1");
assertSearchFails(query("*").put("maxResults", 0.5), "InvalidRequestException", 400,
"1 validation error detected: Value '0' at 'maxResults' failed to satisfy constraint: "
+ "Member must have value greater than or equal to 1");
assertSearchFails(query("*").put("maxResults", -1), "InvalidRequestException", 400,
"1 validation error detected: Value '-1' at 'maxResults' failed to satisfy constraint: "
+ "Member must have value greater than or equal to 1");
}
@Test
void indexNameMustBeAJsonString() {
fleet();
assertSearchFails(query("*").put("indexName", 1), "SerializationException", 400,
"indexName must be a JSON string");
assertSearchFails(query("*").put("indexName", true), "SerializationException", 400,
"indexName must be a JSON string");
}
@Test
void aBodyThatIsNotAJsonObjectIsASerializationError() {
fleet();
for (String body : List.of("[]", "\"x\"", "1", "null", "[{\"queryString\":\"*\"}]")) {
assertSearchBodyFails(body, "request body must be a JSON object");
}
}
@Test
void memberTypeErrorsComeBeforeEveryOtherError() {
fleet();
assertSearchBodyFails("{\"queryString\":\"bogusfield:\",\"nextToken\":1}", "nextToken must be a JSON string");
assertSearchBodyFails("{\"queryString\":\"*\",\"indexName\":\"\",\"queryVersion\":1}",
"queryVersion must be a JSON string");
assertSearchBodyFails("{\"queryString\":\"\",\"nextToken\":true}", "nextToken must be a JSON string");
assertSearchBodyFails("{\"queryString\":\"*\",\"indexName\":\"nope\",\"nextToken\":1}",
"nextToken must be a JSON string");
}
private void assertSearchBodyFails(String body, String message) {
AwsException failure = assertThrows(AwsException.class,
() -> service.searchIndex(json(body), REGION), body);
assertEquals("SerializationException", failure.getErrorCode(), body);
assertEquals(400, failure.getHttpStatus(), body);
assertEquals(message, failure.getMessage(), body);
}
private static List<String> thingNames(IotService.Page<ObjectNode> page) {
return page.items().stream().map(thing -> thing.path("thingName").asText()).toList();
}
@Test
void searchSeesOnlyTheCallersRegion() {
fleet();
iot.service.createThing("alpha-9", Map.of("provider", "acme"), null, "eu-west-1");
assertEquals(List.of("alpha-1", "alpha-2"), names("attributes.provider:acme"));
assertThrows(AwsException.class, () -> service.searchIndex(query("*"), "eu-west-1"));
service.updateIndexingConfiguration(json("""
{"thingIndexingConfiguration": {"thingIndexingMode": "REGISTRY"}}
"""), "eu-west-1");
List<ObjectNode> other = service.searchIndex(query("attributes.provider:acme"), "eu-west-1").items();
assertEquals(1, other.size());
assertEquals("alpha-9", other.get(0).path("thingName").asText());
}
}