feat(rekognition): add face collection lifecycle and search (#8001) (#8004)

Recreate the reviewed Rekognition changes on the existing upstream main base using a verified commit. The complete file tree is identical to PR head 19f259b43e1ec8a3ce5fd2a50eb9c21e4ed604df, preserving the collection, pagination, persistence and model-validation fixes while removing the unsigned merge.

Generate constraints for every modeled operation with constraints=True. Select the served operation in the handler, validate its request once, then dispatch. Preserve UnknownOperationException for unserved actions.

Move constraint tests to the handler boundary and verify newly modeled operations are detected without maintaining an allowlist. Verified 189 Java tests, 55 generator tests, Checkstyle, generated-data, documentation and partition checks. Addresses review 5865133468.
This commit is contained in:
jwoa95 authored and GitHub committed 2026-11-11 22:19:38 -04:00
1 parent e0f04b7323
commit a27670c4bb
27 files changed
+3297 -47

No files matched your search

@@ -55,7 +55,7 @@ class PartitionCrossServiceSmokeIntegrationTest {
"eventbridge", "eventbridgev2", "firehose", "fis", "glue", "guardduty", "iot", "kinesis", "kinesisanalytics", "lambda",
"lambdamicrovms", "lambdaweb", "memorydb", "msk", "mwaa", "networkfirewall", "oam", "opensearch", "organizations",
"paymentcryptography", "pipes", "quicksight", "ram", "rds", "redshift", "redshiftserverless",
"resourceexplorer2", "resourcegroups", "route53resolver",
"rekognition", "resourceexplorer2", "resourcegroups", "route53resolver",
"s3tables", "s3vectors", "sagemaker", "scheduler", "secretsmanager", "servicequotas", "ses", "signer", "sns", "sqs",
"stepfunctions", "timestreaminfluxdb", "transfer", "verifiedpermissions", "wafv2",
"xray");
@@ -72,6 +72,20 @@ class PartitionCrossServiceSmokeIntegrationTest {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@ParameterizedTest
@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
void rekognitionCollectionArn(PartitionCase partitionCase) {
String region = offered(partitionCase, "rekognition");
String id = unique("smoke-collection", partitionCase);
String body = "{\"CollectionId\":\"" + id + "\"}";
String arn = signed(region, "rekognition").contentType(JSON_1_1)
.header("X-Amz-Target", "RekognitionService.CreateCollection").body(body)
.post("/").then().statusCode(200).extract().path("CollectionArn");
cleanup.register(() -> signed(region, "rekognition").contentType(JSON_1_1)
.header("X-Amz-Target", "RekognitionService.DeleteCollection").body(body).post("/"));
PartitionMatrix.assertArnIn(partitionCase, arn);
}
@ParameterizedTest
@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
void quickSightDashboardArn(PartitionCase partitionCase) {
@@ -22,12 +22,16 @@ class RequestConstraintCheckTest {
"shapes": {
"PutInput": {"type": "structure", "required": ["name"],
"members": {"name": "Name", "items": "Items", "count": "Count", "labels": "Labels",
"kind": "Kind", "quoted": "Quoted"}},
"kind": "Kind", "quoted": "Quoted", "percent": "Percent",
"double": "Double", "wide": "Wide"}},
"Name": {"type": "string", "min": 2, "max": 5, "pattern": "[a-z]+"},
"Quoted": {"type": "string", "pattern": "[a-z]+", "quotedPattern": "[a-z]*"},
"Items": {"type": "list", "max": 2, "member": "Item"},
"Item": {"type": "structure", "required": ["id"], "members": {"id": "Name"}},
"Count": {"type": "integer", "min": 1, "max": 10},
"Percent": {"type": "float", "min": 0, "max": 100},
"Double": {"type": "double", "min": 0, "max": 100},
"Wide": {"type": "long", "min": 9007199254740993, "max": 9007199254740995},
"Labels": {"type": "map", "key": "Name", "value": "Name"},
"Kind": {"type": "string", "enum": ["A", "B"]}
}}
@@ -42,7 +46,7 @@ class RequestConstraintCheckTest {
}
@Override
public AwsException bounds(String path, String type, Long min, Long max, long size) {
public AwsException bounds(String path, String type, Long min, Long max, Number size) {
return fail("bounds " + path + " " + type + " " + min + ".." + max + " " + size);
}
@@ -123,6 +127,19 @@ class RequestConstraintCheckTest {
assertEquals("bounds Put.name string 2..5 1", violation("{\"name\":\"\\uD83D\\uDE00\"}"));
}
@Test
void fractionalBoundsAreNotTruncatedAndLongBoundsStayExact() {
assertDoesNotThrow(() -> CHECK.check("Put", json("{\"name\":\"ab\",\"percent\":99.5,\"double\":0.5}")));
assertEquals("bounds Put.percent float 0..100 100.1", violation("{\"name\":\"ab\",\"percent\":100.1}"));
assertEquals("bounds Put.percent float 0..100 -0.1", violation("{\"name\":\"ab\",\"percent\":-0.1}"));
assertEquals("type Put.percent float", violation("{\"name\":\"ab\",\"percent\":\"50\"}"));
assertEquals("bounds Put.double double 0..100 100.1", violation("{\"name\":\"ab\",\"double\":100.1}"));
assertEquals("type Put.count integer", violation("{\"name\":\"ab\",\"count\":2147483648}"));
assertDoesNotThrow(() -> CHECK.check("Put", json("{\"name\":\"ab\",\"wide\":9007199254740993}")));
assertEquals("bounds Put.wide long 9007199254740993..9007199254740995 9007199254740992",
violation("{\"name\":\"ab\",\"wide\":9007199254740992}"));
}
@ParameterizedTest
@ValueSource(strings = {"InvalidRequestException", "InvalidParameterException", "ValidationException"})
void standardMessagesPreserveTheWireFormatForEachServiceCode(String errorCode) {
@@ -143,6 +160,10 @@ class RequestConstraintCheckTest {
+ "'Member must have value greater than or equal to 1'"},
{"{\"name\":\"ab\",\"count\":11}", "Invalid parameter at 'count' failed to satisfy constraint: "
+ "'Member must have value less than or equal to 10'"},
{"{\"name\":\"ab\",\"percent\":-0.1}", "Invalid parameter at 'percent' failed to satisfy constraint: "
+ "'Member must have value greater than or equal to 0'"},
{"{\"name\":\"ab\",\"percent\":100.1}", "Invalid parameter at 'percent' failed to satisfy constraint: "
+ "'Member must have value less than or equal to 100'"},
{"{\"name\":\"ab\",\"kind\":\"C\"}", "Invalid parameter at 'kind' failed to satisfy constraint: "
+ "'Member must satisfy enum value set: [A, B]'"},
{"{\"name\":\"ab\",\"items\":[{},{},{}]}", "Invalid parameter at 'items' failed to satisfy constraint: "
@@ -0,0 +1,204 @@
package io.floci.aws.services.rekognition;
import io.floci.aws.core.common.ServiceConfigAccess;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.CreateCollectionResponse;
import software.amazon.awssdk.services.rekognition.model.DescribeCollectionResponse;
import software.amazon.awssdk.services.rekognition.model.Face;
import software.amazon.awssdk.services.rekognition.model.Image;
import software.amazon.awssdk.services.rekognition.model.IndexFacesResponse;
import software.amazon.awssdk.services.rekognition.model.InvalidParameterException;
import software.amazon.awssdk.services.rekognition.model.ListCollectionsResponse;
import software.amazon.awssdk.services.rekognition.model.ListFacesResponse;
import software.amazon.awssdk.services.rekognition.model.ResourceAlreadyExistsException;
import software.amazon.awssdk.services.rekognition.model.ResourceNotFoundException;
import software.amazon.awssdk.services.rekognition.model.SearchFacesByImageResponse;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
@TestProfile(RekognitionCollectionIntegrationTest.PersistentCollectionsProfile.class)
class RekognitionCollectionIntegrationTest {
private static final String STORAGE_PATH = "target/rekognition-collections-it";
@TestHTTPResource
URI endpoint;
@Inject
ServiceConfigAccess serviceConfigAccess;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void sdkExercisesCollectionAndFaceLifecycle() {
given().put("/mock-bucket");
given().body(TestImages.jpeg(100, 100)).put("/mock-bucket/collection-face.jpg").then().statusCode(200);
String id = "collection-" + UUID.randomUUID();
try (RekognitionClient client = client(Region.US_EAST_1, "test")) {
Instant before = Instant.now().minusSeconds(1);
CreateCollectionResponse created = client.createCollection(r -> r.collectionId(id));
try {
assertEquals("persistent", serviceConfigAccess.storageMode("rekognition"));
assertTrue(Files.exists(Path.of(STORAGE_PATH, "rekognition-collections.json")));
assertEquals(200, created.statusCode());
assertThrows(ResourceAlreadyExistsException.class, () -> client.createCollection(r -> r.collectionId(id)));
DescribeCollectionResponse described = client.describeCollection(r -> r.collectionId(id));
assertEquals(created.collectionArn(), described.collectionARN());
assertEquals(0L, described.faceCount());
assertTrue(described.creationTimestamp().isAfter(before));
assertTrue(described.creationTimestamp().isBefore(Instant.now().plusSeconds(1)));
assertTrue(client.listCollectionsPaginator(r -> r.maxResults(1)).collectionIds().stream().anyMatch(id::equals));
ListCollectionsResponse emptyCollections = client.listCollections(r -> r.maxResults(0));
assertTrue(emptyCollections.collectionIds().isEmpty());
assertNotNull(emptyCollections.nextToken());
assertTrue(client.listCollections(r -> r.nextToken(emptyCollections.nextToken())).collectionIds().contains(id));
Image image = Image.builder().s3Object(s3 -> s3.bucket("mock-bucket").name("collection-face.jpg")).build();
IndexFacesResponse indexed = client.indexFaces(r -> r.collectionId(id).image(image).externalImageId("photo-1"));
assertEquals(2, indexed.faceRecords().size());
Face face = indexed.faceRecords().getFirst().face();
assertEquals(0.4f, face.boundingBox().width());
assertEquals(created.faceModelVersion(), face.indexFacesModelVersion());
assertEquals(face.faceId(), client.indexFaces(r -> r.collectionId(id).image(image).externalImageId("photo-1"))
.faceRecords().getFirst().face().faceId());
client.indexFaces(r -> r.collectionId(id).image(image).externalImageId("photo-2").maxFaces(1));
assertEquals(3L, client.describeCollection(r -> r.collectionId(id)).faceCount());
Set<String> allIds = new HashSet<>();
client.listFacesPaginator(r -> r.collectionId(id).maxResults(1)).faces().forEach(f -> assertTrue(allIds.add(f.faceId())));
assertEquals(3, allIds.size());
List<String> orderedIds = client.listFacesPaginator(r -> r.collectionId(id).maxResults(1))
.faces().stream().map(Face::faceId).toList();
assertEquals(orderedIds.stream().sorted().toList(), orderedIds);
ListFacesResponse emptyFaces = client.listFaces(r -> r.collectionId(id).maxResults(0));
assertTrue(emptyFaces.faces().isEmpty());
assertNotNull(emptyFaces.nextToken());
assertEquals(3, client.listFaces(r -> r.collectionId(id).nextToken(emptyFaces.nextToken())).faces().size());
ListFacesResponse filtered = client.listFaces(r -> r.collectionId(id).faceIds(face.faceId()));
assertEquals(1, filtered.faces().size());
assertEquals("photo-1", filtered.faces().getFirst().externalImageId());
assertEquals(1, client.searchFaces(r -> r.collectionId(id).faceId(face.faceId())).faceMatches().size());
SearchFacesByImageResponse searched = client.searchFacesByImage(r -> r.collectionId(id).image(image).faceMatchThreshold(100f));
assertEquals(2, searched.faceMatches().size());
assertEquals(100f, searched.faceMatches().getFirst().similarity());
assertEquals(face.boundingBox(), searched.searchedFaceBoundingBox());
assertEquals(1, client.searchFacesByImage(r -> r.collectionId(id).image(image).maxFaces(1)).faceMatches().size());
assertEquals(Set.of(face.faceId()), Set.copyOf(client.deleteFaces(r -> r.collectionId(id).faceIds(face.faceId())).deletedFaces()));
assertEquals(2L, client.describeCollection(r -> r.collectionId(id)).faceCount());
assertThrows(InvalidParameterException.class, () -> client.searchFaces(r -> r.collectionId(id).faceId(face.faceId())));
} finally {
assertEquals(200, client.deleteCollection(r -> r.collectionId(id)).statusCode());
}
assertThrows(ResourceNotFoundException.class, () -> client.describeCollection(r -> r.collectionId(id)));
client.createCollection(r -> r.collectionId(id));
try {
assertEquals(0L, client.describeCollection(r -> r.collectionId(id)).faceCount());
} finally {
client.deleteCollection(r -> r.collectionId(id));
}
}
}
@Test
void sdkCollectionsAreIsolatedByAccountAndRegion() {
String id = "isolated-" + UUID.randomUUID();
try (RekognitionClient owner = client(Region.US_EAST_1, "000000000001");
RekognitionClient otherAccount = client(Region.US_EAST_1, "000000000002");
RekognitionClient otherRegion = client(Region.EU_WEST_1, "000000000001")) {
owner.createCollection(r -> r.collectionId(id));
try {
assertThrows(ResourceNotFoundException.class, () -> otherAccount.describeCollection(r -> r.collectionId(id)));
assertThrows(ResourceNotFoundException.class, () -> otherRegion.describeCollection(r -> r.collectionId(id)));
assertFalse(otherAccount.listCollections().collectionIds().contains(id));
assertFalse(otherRegion.listCollections().collectionIds().contains(id));
} finally {
owner.deleteCollection(r -> r.collectionId(id));
}
}
}
@Test
void bytesImagesKeepEmptyDetectionAndCollectionCallsValidateImages() {
String id = "empty-" + UUID.randomUUID();
try (RekognitionClient client = client(Region.US_EAST_1, "test")) {
client.createCollection(r -> r.collectionId(id));
try {
Image image = Image.builder().bytes(SdkBytes.fromByteArray(TestImages.jpeg(100, 100))).build();
assertTrue(client.indexFaces(r -> r.collectionId(id).image(image)).faceRecords().isEmpty());
assertTrue(client.listFaces(r -> r.collectionId(id)).faces().isEmpty());
assertThrows(InvalidParameterException.class, () -> client.searchFacesByImage(r -> r.collectionId(id).image(image)));
for (String action : new String[] {"IndexFaces", "SearchFacesByImage"}) {
given().contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", "RekognitionService." + action)
.body("{\"CollectionId\":\"" + id + "\",\"Image\":{\"Bytes\":\"not base64!\"}}")
.post("/").then().statusCode(400).body("__type", equalTo("SerializationException"));
}
} finally {
client.deleteCollection(r -> r.collectionId(id));
}
}
}
@Test
void collectionRequestsRejectModeledConstraintViolations() {
given().put("/mock-bucket");
given().body(TestImages.jpeg(100, 100)).put("/mock-bucket/collection-face.jpg").then().statusCode(200);
String image = "\"Image\":{\"S3Object\":{\"Bucket\":\"mock-bucket\",\"Name\":\"collection-face.jpg\"}}";
String[][] cases = {
{"CreateCollection", "{\"CollectionId\":\"bad/id\"}", "InvalidParameterException"},
{"CreateCollection", "{\"CollectionId\":\"tenant\",\"Tags\":{\"aws:owner\":\"team\"}}", "InvalidParameterException"},
{"DeleteCollection", "{}", "InvalidParameterException"},
{"DescribeCollection", "{\"CollectionId\":1}", "SerializationException"},
{"ListCollections", "{\"MaxResults\":4097}", "InvalidParameterException"},
{"ListCollections", "{\"MaxResults\":2147483648}", "SerializationException"},
{"IndexFaces", "{\"CollectionId\":\"tenant\"," + image + ",\"DetectionAttributes\":[\"UNKNOWN\"]}", "InvalidParameterException"},
{"IndexFaces", "{\"CollectionId\":\"tenant\"," + image + ",\"QualityFilter\":\"BAD\"}", "InvalidParameterException"},
{"ListFaces", "{\"CollectionId\":\"tenant\",\"FaceIds\":[]}", "InvalidParameterException"},
{"DeleteFaces", "{\"CollectionId\":\"tenant\",\"FaceIds\":[\"bad-id\"]}", "InvalidParameterException"},
{"SearchFaces", "{\"CollectionId\":\"tenant\",\"FaceId\":\"00000000-0000-0000-0000-000000000000\",\"FaceMatchThreshold\":-0.1}", "InvalidParameterException"},
{"SearchFacesByImage", "{\"CollectionId\":\"tenant\"," + image + ",\"FaceMatchThreshold\":100.1}", "InvalidParameterException"},
{"SearchFacesByImage", "{\"CollectionId\":\"tenant\"," + image + ",\"FaceMatchThreshold\":\"50\"}", "SerializationException"}
};
for (String[] testCase : cases) {
given().contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", "RekognitionService." + testCase[0])
.body(testCase[1]).post("/").then().statusCode(400).body("__type", equalTo(testCase[2]));
}
}
private RekognitionClient client(Region region, String account) {
return AwsTestClients.create(RekognitionClient.builder(), account, region, endpoint);
}
public static class PersistentCollectionsProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.storage.services.rekognition.mode", "persistent",
"floci.storage.persistent-path", STORAGE_PATH);
}
}
}
@@ -0,0 +1,324 @@
package io.floci.aws.services.rekognition;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AiMockConfigLoader;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.ServiceConfigAccess;
import io.floci.aws.core.storage.StorageFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class RekognitionCollectionServiceTest {
private static final String ACCOUNT = "123456789012";
private static final String REGION = "us-east-1";
private final ObjectMapper mapper = new ObjectMapper();
private final AiMockConfigLoader mocks = mock(AiMockConfigLoader.class);
private final RegionResolver resolver = new RegionResolver(REGION, ACCOUNT);
private RekognitionCollectionService service;
@BeforeEach
void setUp() throws Exception {
when(mocks.lookup("rekognition", "photos/face.jpg", "DetectFaces"))
.thenReturn(Optional.of(mapper.readTree("""
{"FaceDetails":[
{"Confidence":99.5,"BoundingBox":{"Width":0.1,"Height":0.1,"Top":0.5,"Left":0.5}},
{"Confidence":99.9,"BoundingBox":{"Width":0.4,"Height":0.4,"Top":0.1,"Left":0.1}}
]}
""")));
service = new RekognitionCollectionService(storage("memory", Path.of("target/rekognition-unit")),
mapper, resolver, mocks);
}
@Test
void collectionLifecycleAndRegionIsolation() {
ObjectNode created = service.createCollection(request(), REGION);
assertEquals("arn:aws:rekognition:us-east-1:" + ACCOUNT + ":collection/tenant", created.path("CollectionArn").asText());
assertEquals(200, created.path("StatusCode").asInt());
assertError("ResourceAlreadyExistsException", () -> service.createCollection(request(), REGION));
ObjectNode described = service.describeCollection(request(), REGION);
assertTrue(described.path("CreationTimestamp").asDouble() > 1_700_000_000);
assertEquals(created.path("CollectionArn"), described.path("CollectionARN"));
assertEquals(0, described.path("FaceCount").asInt());
assertEquals(0, service.listCollections(mapper.createObjectNode(), "eu-west-1").path("CollectionIds").size());
assertError("ResourceNotFoundException", () -> service.describeCollection(request(), "eu-west-1"));
service.createCollection(request(), "eu-west-1");
service.deleteCollection(request(), REGION);
assertError("ResourceNotFoundException", () -> service.deleteCollection(request(), REGION));
assertEquals(0, service.describeCollection(request(), "eu-west-1").path("FaceCount").asInt());
}
@Test
void indexedRecordsAreStableAndSearchDoesNotMatchOtherPositions() {
service.createCollection(request(), REGION);
ObjectNode indexed = service.indexFaces(imageRequest().put("ExternalImageId", "first"), REGION, "photos/face.jpg");
assertEquals(2, indexed.path("FaceRecords").size());
assertEquals(0.4, indexed.at("/FaceRecords/0/Face/BoundingBox/Width").asDouble());
String faceId = indexed.at("/FaceRecords/0/Face/FaceId").asText();
ObjectNode repeated = service.indexFaces(imageRequest().put("ExternalImageId", "first"), REGION, "photos/face.jpg");
assertEquals(indexed, repeated);
service.indexFaces(imageRequest().put("ExternalImageId", "second"), REGION, "photos/face.jpg");
assertEquals(4, service.describeCollection(request(), REGION).path("FaceCount").asInt());
ObjectNode found = service.searchFaces(request().put("FaceId", faceId), REGION);
assertEquals(1, found.path("FaceMatches").size());
assertEquals("second", found.at("/FaceMatches/0/Face/ExternalImageId").asText());
assertEquals(100.0, found.at("/FaceMatches/0/Similarity").asDouble());
assertEquals(2, service.searchFacesByImage(imageRequest(), REGION, "photos/face.jpg").path("FaceMatches").size());
ObjectNode deletes = request();
String unknown = "00000000-0000-0000-0000-000000000000";
deletes.putArray("FaceIds").add(faceId).add(unknown);
ObjectNode deleted = service.deleteFaces(deletes, REGION);
assertEquals(faceId, deleted.at("/DeletedFaces/0").asText());
assertEquals(unknown, deleted.at("/UnsuccessfulFaceDeletions/0/FaceId").asText());
assertEquals("FACE_NOT_FOUND", deleted.at("/UnsuccessfulFaceDeletions/0/Reasons/0").asText());
assertError("InvalidParameterException", () -> service.searchFaces(request().put("FaceId", faceId), REGION));
service.deleteCollection(request(), REGION);
service.createCollection(request(), REGION);
assertEquals(0, service.listFaces(request(), REGION).path("Faces").size());
}
@Test
void maxFacesReportsUnindexedFacesAndEmptyDetectionDoesNotInventFaces() {
service.createCollection(request(), REGION);
ObjectNode result = service.indexFaces(imageRequest().put("MaxFaces", 1), REGION, "photos/face.jpg");
assertEquals(1, result.path("FaceRecords").size());
assertEquals("EXCEEDS_MAX_FACES", result.at("/UnindexedFaces/0/Reasons/0").asText());
ObjectNode empty = service.indexFaces(imageRequest(), REGION, null);
assertEquals(0, empty.path("FaceRecords").size());
assertError("InvalidParameterException", () -> service.searchFacesByImage(imageRequest(), REGION, null));
}
@Test
void paginationIsCompleteScopedAndSupportsMaximumLengthNames() {
for (int i = 0; i < 3; i++) {
service.createCollection(request().put("CollectionId", "x".repeat(254) + i), REGION);
}
ObjectNode pageRequest = mapper.createObjectNode().put("MaxResults", 1);
Set<String> ids = new HashSet<>();
String token = null;
do {
if (token != null) {
pageRequest.put("NextToken", token);
}
ObjectNode result = service.listCollections(pageRequest, REGION);
assertEquals(result.path("CollectionIds").size(), result.path("FaceModelVersions").size());
result.path("CollectionIds").forEach(id -> assertTrue(ids.add(id.asText())));
token = result.path("NextToken").asText(null);
if (token != null) {
assertTrue(token.length() <= 255);
String cursor = token;
assertError("InvalidPaginationTokenException", () -> service.listCollections(
mapper.createObjectNode().put("NextToken", cursor), "eu-west-1"));
}
} while (token != null);
assertEquals(3, ids.size());
service.createCollection(request(), REGION);
service.indexFaces(imageRequest(), REGION, "photos/face.jpg");
ObjectNode first = service.listFaces(request().put("MaxResults", 1), REGION);
ObjectNode second = service.listFaces(request().put("NextToken", first.path("NextToken").asText()), REGION);
assertEquals(1, second.path("Faces").size());
assertNotEquals(first.at("/Faces/0/FaceId"), second.at("/Faces/0/FaceId"));
ObjectNode filtered = request();
filtered.putArray("FaceIds").add(first.at("/Faces/0/FaceId").asText());
assertEquals(1, service.listFaces(filtered, REGION).path("Faces").size());
assertError("InvalidPaginationTokenException", () -> service.listFaces(
filtered.put("NextToken", first.path("NextToken").asText()), REGION));
}
@Test
void resetClearsCollections() {
service.createCollection(request(), REGION);
service.indexFaces(imageRequest(), REGION, "photos/face.jpg");
service.clear();
assertError("ResourceNotFoundException", () -> service.describeCollection(request(), REGION));
}
@Test
void zeroSizedPagesPreserveTheCursorAndValidateTokens() {
assertFalse(service.listCollections(request().put("MaxResults", 0), REGION).has("NextToken"));
service.createCollection(request(), REGION);
service.createCollection(request().put("CollectionId", "other"), REGION);
ObjectNode empty = service.listCollections(request().put("MaxResults", 0), REGION);
assertTrue(empty.path("CollectionIds").isEmpty());
assertTrue(empty.hasNonNull("NextToken"));
assertEquals(service.listCollections(request(), REGION).path("CollectionIds"),
service.listCollections(request().put("NextToken", empty.path("NextToken").asText()), REGION)
.path("CollectionIds"));
String token = service.listCollections(request().put("MaxResults", 1), REGION).path("NextToken").asText();
ObjectNode paused = service.listCollections(request().put("MaxResults", 0).put("NextToken", token), REGION);
assertEquals(token, paused.path("NextToken").asText());
assertEquals(1, service.listCollections(request().put("NextToken", paused.path("NextToken").asText()), REGION)
.path("CollectionIds").size());
assertError("InvalidPaginationTokenException", () -> service.listCollections(
request().put("MaxResults", 0).put("NextToken", "garbage"), REGION));
assertError("InvalidPaginationTokenException", () -> service.listCollections(
request().put("MaxResults", 0).put("NextToken", token), "eu-west-1"));
assertFalse(service.listFaces(request().put("MaxResults", 0), REGION).has("NextToken"));
service.indexFaces(imageRequest(), REGION, "photos/face.jpg");
ObjectNode emptyFaces = service.listFaces(request().put("MaxResults", 0), REGION);
assertTrue(emptyFaces.path("Faces").isEmpty());
assertTrue(emptyFaces.hasNonNull("NextToken"));
assertEquals(service.listFaces(request(), REGION).path("Faces"), service.listFaces(
request().put("NextToken", emptyFaces.path("NextToken").asText()), REGION).path("Faces"));
String faceToken = service.listFaces(request().put("MaxResults", 1), REGION).path("NextToken").asText();
assertEquals(faceToken, service.listFaces(request().put("MaxResults", 0).put("NextToken", faceToken), REGION)
.path("NextToken").asText());
assertEquals(1, service.listFaces(request().put("NextToken", faceToken), REGION).path("Faces").size());
assertError("InvalidPaginationTokenException", () -> service.listFaces(
request().put("MaxResults", 0).put("NextToken", "garbage"), REGION));
assertError("InvalidPaginationTokenException", () -> service.listFaces(
request().put("CollectionId", "other").put("MaxResults", 0).put("NextToken", faceToken), REGION));
}
@Test
void listsUseIdOrderAndResumeAfterDeletedIds() {
List<String> expected = List.of("alpha", "bravo", "charlie", "delta", "echo", "foxtrot");
for (String id : expected.reversed()) {
service.createCollection(request().put("CollectionId", id), REGION);
}
List<String> actual = new ArrayList<>();
service.listCollections(request(), REGION).path("CollectionIds").forEach(id -> actual.add(id.asText()));
assertEquals(expected, actual);
ObjectNode first = service.listCollections(request().put("MaxResults", 1), REGION);
service.deleteCollection(request().put("CollectionId", "alpha"), REGION);
service.createCollection(request().put("CollectionId", "aardvark"), REGION);
assertEquals("bravo", service.listCollections(request().put("MaxResults", 1)
.put("NextToken", first.path("NextToken").asText()), REGION).at("/CollectionIds/0").asText());
service.createCollection(request(), REGION);
for (int i = 0; i < 8; i++) {
service.indexFaces(imageRequest().put("ExternalImageId", "photo-" + i), REGION, "photos/face.jpg");
}
List<String> faceIds = new ArrayList<>();
String token = null;
do {
ObjectNode pageRequest = request().put("MaxResults", 1);
if (token != null) {
pageRequest.put("NextToken", token);
}
ObjectNode page = service.listFaces(pageRequest, REGION);
faceIds.add(page.at("/Faces/0/FaceId").asText());
token = page.path("NextToken").asText(null);
ObjectNode deletion = request();
deletion.putArray("FaceIds").add(faceIds.getLast());
service.deleteFaces(deletion, REGION);
} while (token != null);
assertEquals(16, faceIds.size());
assertEquals(faceIds.stream().sorted().toList(), faceIds);
}
@Test
void faceWritesLeaveMetadataAndOtherCollectionsUntouched(@TempDir Path path) throws Exception {
StorageFactory storage = storage("persistent", path);
try {
RekognitionCollectionService writer = new RekognitionCollectionService(storage, mapper, resolver, mocks);
writer.createCollection(request(), REGION);
writer.createCollection(request().put("CollectionId", "other"), REGION);
writer.indexFaces(imageRequest().put("CollectionId", "other"), REGION, "photos/face.jpg");
Map<Path, FileTime> untouched = markFiles(path);
ObjectNode indexed = writer.indexFaces(imageRequest(), REGION, "photos/face.jpg");
for (Map.Entry<Path, FileTime> file : untouched.entrySet()) {
assertEquals(file.getValue(), Files.getLastModifiedTime(file.getKey()), file.getKey().toString());
}
assertTrue(Files.isDirectory(path.resolve("rekognition-faces")));
assertFalse(mapper.readTree(path.resolve("rekognition-collections.json").toFile()).toString().contains("FaceId"));
Map<Path, FileTime> unchanged = markFiles(path);
assertEquals(indexed, writer.indexFaces(imageRequest(), REGION, "photos/face.jpg"));
for (Map.Entry<Path, FileTime> file : unchanged.entrySet()) {
assertEquals(file.getValue(), Files.getLastModifiedTime(file.getKey()), file.getKey().toString());
}
ObjectNode deletion = request();
deletion.putArray("FaceIds").add(indexed.at("/FaceRecords/0/Face/FaceId").asText());
writer.deleteFaces(deletion, REGION);
for (Map.Entry<Path, FileTime> file : untouched.entrySet()) {
assertEquals(file.getValue(), Files.getLastModifiedTime(file.getKey()), file.getKey().toString());
}
writer.deleteCollection(request(), REGION);
writer.createCollection(request(), REGION);
assertEquals(0, writer.listFaces(request(), REGION).path("Faces").size());
assertEquals(2, writer.listFaces(request().put("CollectionId", "other"), REGION).path("Faces").size());
writer.clear();
writer.createCollection(request().put("CollectionId", "other"), REGION);
assertEquals(0, writer.listFaces(request().put("CollectionId", "other"), REGION).path("Faces").size());
} finally {
storage.shutdownAll();
}
}
private Map<Path, FileTime> markFiles(Path path) throws Exception {
Map<Path, FileTime> result = new HashMap<>();
try (Stream<Path> files = Files.walk(path)) {
for (Path file : files.filter(Files::isRegularFile).toList()) {
Files.setLastModifiedTime(file, FileTime.fromMillis(1_000));
result.put(file, Files.getLastModifiedTime(file));
}
}
return result;
}
@ParameterizedTest
@ValueSource(strings = {"persistent", "hybrid", "wal"})
void collectionAndFaceMetadataSurviveStorageRestart(String mode, @TempDir Path path) {
StorageFactory storage = storage(mode, path);
RekognitionCollectionService writer = new RekognitionCollectionService(storage, mapper, resolver, mocks);
writer.createCollection(request(), REGION);
ObjectNode indexed = writer.indexFaces(imageRequest(), REGION, "photos/face.jpg");
storage.shutdownAll();
StorageFactory restored = storage(mode, path);
try {
RekognitionCollectionService reader = new RekognitionCollectionService(restored, mapper, resolver, mocks);
assertEquals(2, reader.describeCollection(request(), REGION).path("FaceCount").asInt());
String faceId = indexed.at("/FaceRecords/0/Face/FaceId").asText();
assertEquals(faceId, reader.searchFaces(request().put("FaceId", faceId), REGION).path("SearchedFaceId").asText());
assertEquals(1, reader.searchFacesByImage(imageRequest(), REGION, "photos/face.jpg").path("FaceMatches").size());
} finally {
restored.shutdownAll();
}
}
private StorageFactory storage(String mode, Path path) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.storage().persistentPath()).thenReturn(path.toString());
when(config.storage().wal().compactionIntervalMs()).thenReturn(60_000L);
when(config.defaultAccountId()).thenReturn(ACCOUNT);
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
when(access.storageMode("rekognition")).thenReturn(mode);
when(access.storageFlushInterval("rekognition")).thenReturn(60_000L);
return new StorageFactory(config, access);
}
private ObjectNode request() {
return mapper.createObjectNode().put("CollectionId", "tenant");
}
private ObjectNode imageRequest() {
ObjectNode request = request();
request.putObject("Image").putObject("S3Object").put("Bucket", "photos").put("Name", "face.jpg");
return request;
}
private static void assertError(String code, Runnable action) {
assertEquals(code, assertThrows(AwsException.class, action::run).getErrorCode());
}
}
@@ -346,7 +346,7 @@ class RekognitionIntegrationTest {
void unknownAction_returnsUnknownOperationError() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "RekognitionService.IndexFaces")
.header("X-Amz-Target", "RekognitionService.UnknownAction")
.header("Authorization", AUTH_HEADER)
.body("{}")
.when()
@@ -0,0 +1,85 @@
package io.floci.aws.services.rekognition;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsErrorResponse;
import io.floci.aws.core.common.AwsException;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class RekognitionJsonHandlerTest {
private static final String REGION = "us-east-1";
private static final ObjectMapper MAPPER = new ObjectMapper();
private final RekognitionService detection = mock(RekognitionService.class);
private final RekognitionImageValidator images = mock(RekognitionImageValidator.class);
private final RekognitionCollectionService collections = mock(RekognitionCollectionService.class);
private final RekognitionJsonHandler handler = new RekognitionJsonHandler(detection, images, collections);
@ParameterizedTest
@ValueSource(strings = {"CreateCollection", "DeleteCollection", "DescribeCollection", "ListCollections",
"IndexFaces", "ListFaces", "DeleteFaces", "SearchFaces", "SearchFacesByImage", "DetectLabels",
"DetectFaces", "DetectText", "CompareFaces", "DetectModerationLabels"})
void everyServedActionValidatesBeforeDispatch(String action) throws Exception {
AwsException error = assertThrows(AwsException.class,
() -> handler.handle(action, MAPPER.readTree("[]"), REGION));
assertEquals("SerializationException", error.getErrorCode());
verifyNoInteractions(detection, images, collections);
}
@ParameterizedTest
@MethodSource("invalidRequests")
void modeledConstraintsAreCheckedBeforeImageReadsOrWrites(String action, String body, String code) throws Exception {
JsonNode request = MAPPER.readTree(body);
AwsException error = assertThrows(AwsException.class, () -> handler.handle(action, request, REGION));
assertEquals(code, error.getErrorCode());
verifyNoInteractions(detection, images, collections);
}
static Stream<Arguments> invalidRequests() {
String image = "\"Image\":{\"Bytes\":\"\"}";
return Stream.of(
Arguments.of("CreateCollection", "{\"CollectionId\":\"bad/id\"}", "InvalidParameterException"),
Arguments.of("CreateCollection", "{\"CollectionId\":123}", "SerializationException"),
Arguments.of("CreateCollection", "{\"CollectionId\":\"tenant\",\"Tags\":{\"aws:owner\":\"team\"}}", "InvalidParameterException"),
Arguments.of("CreateCollection", "{\"CollectionId\":\"tenant\",\"Tags\":{\"owner\":\"invalid!\"}}", "InvalidParameterException"),
Arguments.of("IndexFaces", "{\"CollectionId\":\"tenant\"," + image + ",\"MaxFaces\":0}", "InvalidParameterException"),
Arguments.of("IndexFaces", "{\"CollectionId\":\"tenant\"," + image + ",\"QualityFilter\":\"BAD\"}", "InvalidParameterException"),
Arguments.of("IndexFaces", "{\"CollectionId\":\"tenant\"," + image + ",\"DetectionAttributes\":[\"UNKNOWN\"]}", "InvalidParameterException"),
Arguments.of("ListFaces", "{\"CollectionId\":\"tenant\",\"MaxResults\":1.2}", "SerializationException"),
Arguments.of("DeleteFaces", "{\"CollectionId\":\"tenant\"}", "InvalidParameterException"),
Arguments.of("SearchFacesByImage", "{\"CollectionId\":\"tenant\"," + image + ",\"FaceMatchThreshold\":101}", "InvalidParameterException"),
Arguments.of("DetectLabels", "{" + image + ",\"MinConfidence\":101}", "InvalidParameterException"),
Arguments.of("DetectFaces", "{" + image + ",\"Attributes\":[\"UNKNOWN\"]}", "InvalidParameterException"),
Arguments.of("CompareFaces", "{\"SourceImage\":{\"Bytes\":\"\"},\"TargetImage\":{\"Bytes\":\"\"},\"SimilarityThreshold\":-0.1}", "InvalidParameterException"));
}
@ParameterizedTest
@ValueSource(strings = {"UnknownAction", "CreateProject"})
void unservedActionsReturnUnknownOperationBeforeCheckingTheirModeledInput(String action) throws Exception {
try (Response response = handler.handle(action, MAPPER.readTree("[]"), REGION)) {
assertEquals(400, response.getStatus());
assertEquals("UnknownOperationException", ((AwsErrorResponse) response.getEntity()).type());
}
verifyNoInteractions(detection, images, collections);
}
@Test
void validRequestsReachTheirOperation() throws Exception {
JsonNode request = MAPPER.readTree("{\"CollectionId\":\"tenant\"}");
when(collections.createCollection(request, REGION)).thenReturn(MAPPER.createObjectNode().put("StatusCode", 200));
try (Response response = handler.handle("CreateCollection", request, REGION)) {
assertEquals(200, response.getStatus());
}
verify(collections).createCollection(request, REGION);
verifyNoInteractions(detection, images);
}
}