diff --git a/Makefile b/Makefile index 28861b3da0..ff4d83ce27 100644 --- a/Makefile +++ b/Makefile @@ -285,6 +285,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s $(PYTHON) tools/aws/regen_payment_cryptography_shapes.py $(PYTHON) tools/aws/regen_payment_cryptography_data_shapes.py $(PYTHON) tools/aws/regen_securityhub_shapes.py + $(PYTHON) tools/aws/regen_rekognition_shapes.py $(PYTHON) tools/aws/regen_iam_shapes.py $(PYTHON) tools/aws/regen_sts_shapes.py $(PYTHON) tools/aws/regen_apigateway_types.py @@ -394,6 +395,10 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres echo "error: Security Hub request shapes are out of date; run 'make aws-data-sync'."; \ exit 1; \ } + @$(PYTHON) tools/aws/regen_rekognition_shapes.py --check || { \ + echo "error: Rekognition request shapes are out of date; run 'make aws-data-sync'."; \ + exit 1; \ + } @$(PYTHON) tools/aws/regen_apigateway_types.py --check || { \ echo "error: API Gateway integration types are out of date; run 'make aws-data-sync'."; \ exit 1; \ diff --git a/docs/services/index.md b/docs/services/index.md index 2ff3fa78d9..71c16f44d5 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -142,7 +142,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [CloudTrail](cloudtrail.md) | `POST /` + `X-Amz-Target: com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.*` | JSON 1.1 | 14 | | [Textract](textract.md) | `POST /` + `X-Amz-Target: Textract.*` | JSON 1.1 | 6 | | [Comprehend](comprehend.md) | `POST /` + `X-Amz-Target: Comprehend_20171127.*` | JSON 1.1 | 5 | -| [Rekognition](rekognition.md) | `POST /` + `X-Amz-Target: RekognitionService.*` | JSON 1.1 | 5 | +| [Rekognition](rekognition.md) | `POST /` + `X-Amz-Target: RekognitionService.*` | JSON 1.1 | 14 | | [Translate](translate.md) | `POST /` + `X-Amz-Target: AWSShineFrontendService_20170701.*` | JSON 1.1 | 3 | | [Transcribe](transcribe.md) | `POST /` + `X-Amz-Target: Transcribe.*` | JSON 1.1 | 8 | | [Pricing](pricing.md) | `POST /` + `X-Amz-Target: AWSPriceListService.*` | JSON 1.1 | 5 | diff --git a/docs/services/rekognition.md b/docs/services/rekognition.md index 5146a43703..ea53306e4f 100644 --- a/docs/services/rekognition.md +++ b/docs/services/rekognition.md @@ -8,6 +8,15 @@ | Action | Description | | --- | --- | +| `CreateCollection` | Create an account- and region-scoped face collection | +| `DeleteCollection` | Delete a collection and all its indexed face records | +| `DescribeCollection` | Return collection metadata, face count, and model version | +| `ListCollections` | List collections with pagination | +| `IndexFaces` | Store configured face detections in a collection | +| `ListFaces` | List indexed face metadata with pagination and face ID filtering | +| `DeleteFaces` | Remove indexed face records | +| `SearchFaces` | Search a collection using an indexed face ID | +| `SearchFacesByImage` | Search a collection using the largest configured face in an image | | `DetectLabels` | Detect objects, scenes, and concepts in an image | | `DetectFaces` | Detect faces in an image and their attributes | | `DetectText` | Detect text in an image | @@ -17,11 +26,12 @@ ## Emulation Behavior -- **Stub responses:** every action returns a fixed, AWS-shaped response. No image +- **Stub image analysis:** image-analysis actions return fixed, AWS-shaped responses. No image analysis is performed: what an image shows never changes the result. - **Images are checked as Rekognition checks them:** an image Rekognition refuses is refused here, with Rekognition's error, before any response. Measured against - Rekognition in us-east-2, for each operation and for both `Bytes` and `S3Object`: + Rekognition in us-east-2 for the synchronous image-analysis operations and for both + `Bytes` and `S3Object`. Collection image operations reuse this validation: - Anything but a JPEG or PNG (WebP, GIF, other bytes) is refused with `InvalidImageFormatException`, and so is a cut-off or hollow file the way Rekognition judges it: a PNG without an `IDAT` or `IEND` chunk, or a JPEG cut inside its headers or @@ -62,8 +72,7 @@ - **Both `Bytes` and `S3Object`:** supplying both is accepted rather than rejected, since nothing in the Rekognition API model declares that combination invalid. The bytes are what is checked. -- **Out of scope:** face-collection persistence (`CreateCollection`, - `IndexFaces`, `SearchFaces`), custom-model training (`Projects`, `Datasets`, +- **Out of scope:** custom-model training (`Projects`, `Datasets`, `ProjectVersions`), live video (`StreamProcessor`), async video jobs (`Start*`/`Get*` Celebrity/Content/Face/Label/Person/Segment/Text detection), and Face Liveness sessions are not implemented. @@ -73,6 +82,8 @@ | Variable | Default | Description | |---|---|---| | `FLOCI_SERVICES_REKOGNITION_ENABLED` | `true` | Enable or disable the service | +| `FLOCI_STORAGE_SERVICES_REKOGNITION_MODE` | global storage mode | Collection and face metadata storage: `memory`, `persistent`, `hybrid`, or `wal` | +| `FLOCI_STORAGE_SERVICES_REKOGNITION_FLUSH_INTERVAL_MS` | `5000` | Metadata flush interval in hybrid mode | | `AI_MOCK_CONFIG` | unset | Path to a shared mock-response config file — see "Mock Responses" below | ## Mock Responses @@ -105,11 +116,82 @@ when its modification time changes, so it can be edited without restarting the e missing file, an unset `AI_MOCK_CONFIG`, or no matching entry all fall back to the default stub. +## Face Collections + +Collections and their indexed face records are isolated by account and region. They use +Floci's configured storage backend, survive restarts in durable modes, and are removed by +emulator reset. Deleting a collection removes its faces. Creating an existing collection +returns `ResourceAlreadyExistsException`; operations on a missing collection return +`ResourceNotFoundException`. Collection names are case-sensitive. + +Face records are stored separately from collection metadata. Durable modes partition faces +by collection into 32 shards, so indexing and deleting faces write only affected shards +and leave other collections untouched. WAL mode journals individual face changes. + +`IndexFaces` stores the `FaceDetails` from the same `DetectFaces` mock configuration used +by synchronous detection. Without a matching mock, it returns empty `FaceRecords` and +`UnindexedFaces`, consistent with the default empty face detection. For example: + +```json +{ + "rekognition": { + "my-bucket/person.jpg": { + "DetectFaces": { + "FaceDetails": [{ + "BoundingBox": { "Width": 0.4, "Height": 0.4, "Left": 0.1, "Top": 0.1 }, + "Confidence": 99.9 + }] + } + } + } +} +``` + +Upload a valid JPEG or PNG at that S3 key before indexing. Face IDs and image IDs are +generated by Floci. Re-indexing the same image reference, face position, and +`ExternalImageId` returns the existing records. `MaxFaces` selects the largest bounding +boxes, up to 100; remaining detections appear in `UnindexedFaces` with reason +`EXCEEDS_MAX_FACES`. `DetectionAttributes` and `QualityFilter` do not change configured +detections; supply the desired attributes and quality in the mock file. The collection +model version is an emulated `7.0`, independent of the synchronous stub model version. + +`ListCollections` and `ListFaces` accept `MaxResults` and opaque `NextToken` cursors. +Results are ordered by collection ID or face ID. `MaxResults: 0` returns an empty page +with a continuation token when results remain; resuming with a positive page size returns +those results. Tokens are scoped to the account, region, operation, and filters, remain +within the 255-character limit, and expire when the emulator restarts. +`ListFaces` also supports `FaceIds` filtering. User association actions are not implemented, +so `UserCount` is zero and a `UserId` filter returns no faces. Creation-time tags are +retained; collection tagging APIs are not implemented. + +Search is deterministic and does no biometric analysis. A match requires the same image +reference and bounding-box position, and returns similarity `100`. S3 references include +bucket, key, and optional version; equal bytes at different S3 keys are distinct. Raw image +bytes are never persisted. `SearchFaces` excludes the source face itself, so indexing the +same reference under another `ExternalImageId` allows a match. `SearchFacesByImage` uses +the largest configured detection and returns `InvalidParameterException` if there are no +configured faces. Both search operations enforce `MaxFaces` and validate +`FaceMatchThreshold`; every deterministic match meets any valid threshold from 0 to 100. + +These semantics support local collection lifecycle and application workflow tests. +They do not reproduce AWS's face recognition model or quality filtering. + +The AWS action contracts are documented in the +[Rekognition API Reference](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateCollection.html) +and [face collection guide](https://docs.aws.amazon.com/rekognition/latest/dg/collections.html). + ## Examples ```bash export AWS_ENDPOINT_URL=http://localhost:4566 +aws rekognition create-collection --collection-id tenant-1 +aws rekognition index-faces --collection-id tenant-1 \ + --external-image-id person-1 \ + --image '{"S3Object":{"Bucket":"my-bucket","Name":"person.jpg"}}' +aws rekognition list-faces --collection-id tenant-1 +aws rekognition delete-collection --collection-id tenant-1 + aws rekognition detect-labels \ --image '{"S3Object":{"Bucket":"my-bucket","Name":"photo.jpg"}}' \ --endpoint-url $AWS_ENDPOINT_URL diff --git a/pom.xml b/pom.xml index c6ce737b60..4886d46496 100644 --- a/pom.xml +++ b/pom.xml @@ -350,6 +350,12 @@ + + software.amazon.awssdk + rekognition + ${aws.sdk.version} + test + software.amazon.awssdk accessanalyzer diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 8dea71aeb7..1bcd293352 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -357,6 +357,7 @@ public interface EmulatorConfig { } interface ServiceStorageOverrides { + RekognitionStorageConfig rekognition(); SsmStorageConfig ssm(); SqsStorageConfig sqs(); S3StorageConfig s3(); @@ -409,6 +410,13 @@ public interface EmulatorConfig { SageMakerStorageConfig sagemaker(); } + interface RekognitionStorageConfig { + Optional mode(); + + @WithDefault("5000") + long flushIntervalMs(); + } + interface ApsStorageConfig { Optional mode(); diff --git a/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java b/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java index 16e22ace8a..cc8fe7ec62 100644 --- a/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java +++ b/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java @@ -30,7 +30,7 @@ public final class RequestConstraintCheck { AwsException type(String path, String type); /** {@code size} (a length, a count or a number's value) is outside {@code min}..{@code max}. */ - AwsException bounds(String path, String type, Long min, Long max, long size); + AwsException bounds(String path, String type, Long min, Long max, Number size); /** A string does not match the shape's {@code pattern}. */ AwsException pattern(String path, String pattern); @@ -51,9 +51,11 @@ public final class RequestConstraintCheck { } @Override - public AwsException bounds(String path, String type, Long min, Long max, long size) { - String measure = "integer".equals(type) || "long".equals(type) ? "value" : "length"; - return min != null && size < min + public AwsException bounds(String path, String type, Long min, Long max, Number size) { + boolean fractional = "float".equals(type) || "double".equals(type); + String measure = fractional || "integer".equals(type) || "long".equals(type) ? "value" : "length"; + boolean below = min != null && (fractional ? size.doubleValue() < min : size.longValue() < min); + return below ? invalid(path, "Member must have " + measure + " greater than or equal to " + min) : invalid(path, "Member must have " + measure + " less than or equal to " + max); } @@ -140,15 +142,18 @@ public final class RequestConstraintCheck { case "list" -> value.isArray(); case "string" -> value.isTextual(); case "boolean" -> value.isBoolean(); - case "integer", "long" -> value.isIntegralNumber() && value.canConvertToLong(); + case "integer" -> value.isIntegralNumber() && value.canConvertToInt(); + case "long" -> value.isIntegralNumber() && value.canConvertToLong(); + case "float", "double" -> value.isNumber(); default -> false; }; if (!validType) { throw messages.type(path, type); } - long size = switch (type) { + Number size = switch (type) { case "string" -> value.textValue().codePointCount(0, value.textValue().length()); case "integer", "long" -> value.longValue(); + case "float", "double" -> value.doubleValue(); default -> value.size(); }; checkBounds(shape, path, type, size); @@ -196,10 +201,17 @@ public final class RequestConstraintCheck { } } - private void checkBounds(JsonNode shape, String path, String type, long size) { + private void checkBounds(JsonNode shape, String path, String type, Number size) { Long min = shape.has("min") ? shape.get("min").asLong() : null; Long max = shape.has("max") ? shape.get("max").asLong() : null; - if (min != null && size < min || max != null && size > max) { + boolean outside; + if ("float".equals(type) || "double".equals(type)) { + double number = size.doubleValue(); + outside = !Double.isFinite(number) || min != null && number < min || max != null && number > max; + } else { + outside = min != null && size.longValue() < min || max != null && size.longValue() > max; + } + if (outside) { throw messages.bounds(path, type, min, max, size); } } diff --git a/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java b/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java index 956ff738ad..64e5c3dbd7 100644 --- a/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java @@ -667,7 +667,8 @@ public class ResolvedServiceCatalog { protocols(ServiceProtocol.JSON), Set.of("Comprehend_20171127."), Set.of("comprehend"), Set.of(), Set.of()), descriptor("rekognition", "rekognition", config.services().rekognition().enabled(), true, - null, null, 5000L, null, ServiceProtocol.JSON, + "rekognition", storageMode(config.storage().services().rekognition().mode(), config.storage().mode()), + config.storage().services().rekognition().flushIntervalMs(), null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), Set.of("RekognitionService."), Set.of("rekognition"), Set.of(), Set.of()), descriptor("pricing", "pricing", config.services().pricing().enabled(), true, diff --git a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayDocumentationRequestShapes.java b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayDocumentationRequestShapes.java index 777552f604..23203695c7 100644 --- a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayDocumentationRequestShapes.java +++ b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayDocumentationRequestShapes.java @@ -18,7 +18,7 @@ final class ApiGatewayDocumentationRequestShapes { } @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 bad(path + " is outside the modeled bounds."); } diff --git a/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsRequestShapes.java b/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsRequestShapes.java index fb9ded8f42..04a3400342 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsRequestShapes.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsRequestShapes.java @@ -33,9 +33,9 @@ final class CloudWatchLogsRequestShapes { } @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) { String measure = "integer".equals(type) || "long".equals(type) ? "value" : "length"; - return max != null && size > max + return max != null && size.longValue() > max ? violation(path, "Member must have " + measure + " less than or equal to " + max) : violation(path, "Member must have " + measure + " greater than or equal to " + min); } diff --git a/src/main/java/io/floci/aws/services/rekognition/RekognitionCollectionService.java b/src/main/java/io/floci/aws/services/rekognition/RekognitionCollectionService.java new file mode 100644 index 0000000000..9317b31897 --- /dev/null +++ b/src/main/java/io/floci/aws/services/rekognition/RekognitionCollectionService.java @@ -0,0 +1,324 @@ +package io.floci.aws.services.rekognition; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AiMockConfigLoader; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.Digests; +import io.floci.aws.core.common.PaginatedResult; +import io.floci.aws.core.common.Pagination; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.Resettable; +import io.floci.aws.core.common.SignedMarkers; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.rekognition.model.FaceCollection; +import io.floci.aws.services.rekognition.model.FaceCollection.IndexedFace; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; + +/** Collection metadata is real state; face detection and matching use deterministic mock data. */ +@ApplicationScoped +public class RekognitionCollectionService implements Resettable { + static final String MODEL_VERSION = "7.0"; + private final StorageBackend collections; + private final AccountAwareStorageBackend> indexedFaces; + private final SignedMarkers markers = new SignedMarkers(255); + private final ObjectMapper mapper; + private final RegionResolver regionResolver; + private final AiMockConfigLoader mocks; + + @Inject + public RekognitionCollectionService(StorageFactory storageFactory, ObjectMapper mapper, + RegionResolver regionResolver, AiMockConfigLoader mocks) { + this.collections = storageFactory.create("rekognition", "rekognition-collections.json", new TypeReference<>() {}); + this.indexedFaces = storageFactory.createPartitioned("rekognition", "rekognition-faces.json", + new TypeReference>>() {}, IndexedFace.class, 32); + this.mapper = mapper; + this.regionResolver = regionResolver; + this.mocks = mocks; + } + + public synchronized ObjectNode createCollection(JsonNode request, String region) { + String id = request.path("CollectionId").asText(); + Map tags = tags(request); + String key = key(region, id); + if (collections.get(key).isPresent()) { + throw new AwsException("ResourceAlreadyExistsException", "Collection already exists: " + id, 400); + } + Instant now = Instant.now(); + FaceCollection collection = new FaceCollection(id, + regionResolver.buildArn("rekognition", region, "collection/" + id), MODEL_VERSION, + now.getEpochSecond() + now.getNano() / 1_000_000_000.0, tags); + collections.put(key, collection); + return mapper.createObjectNode().put("StatusCode", 200).put("CollectionArn", collection.arn()) + .put("FaceModelVersion", collection.modelVersion()); + } + + public synchronized ObjectNode describeCollection(JsonNode request, String region) { + FaceCollection collection = requireCollection(request, region); + return mapper.createObjectNode().put("CollectionARN", collection.arn()) + .put("CreationTimestamp", collection.creationTimestamp()) + .put("FaceCount", faces(region, collection).size()).put("UserCount", 0) + .put("FaceModelVersion", collection.modelVersion()); + } + + public synchronized ObjectNode deleteCollection(JsonNode request, String region) { + FaceCollection collection = requireCollection(request, region); + indexedFaces.delete(key(region, collection.id())); + collections.delete(key(region, collection.id())); + return mapper.createObjectNode().put("StatusCode", 200); + } + + public synchronized ObjectNode listCollections(JsonNode request, String region) { + List all = collections.scan(key -> key.startsWith(region + ":")); + PaginatedResult page = page(all, FaceCollection::id, request, + "collections:" + regionResolver.getAccountId() + ":" + region); + ObjectNode result = mapper.createObjectNode(); + ArrayNode ids = result.putArray("CollectionIds"); + ArrayNode versions = result.putArray("FaceModelVersions"); + page.items().forEach(collection -> { + ids.add(collection.id()); + versions.add(collection.modelVersion()); + }); + putToken(result, page.nextToken()); + return result; + } + + public synchronized ObjectNode indexFaces(JsonNode request, String region, String mockKey) { + FaceCollection collection = requireCollection(request, region); + String externalId = request.path("ExternalImageId").asText(null); + int maxFaces = request.path("MaxFaces").asInt(100); + String imageKey = imageKey(request.get("Image")); + List details = faceDetails(mockKey); + details.sort(Comparator.comparingDouble(RekognitionCollectionService::area).reversed()); + String collectionKey = key(region, collection.id()); + Map faces = new HashMap<>(faces(region, collection)); + Map existing = new HashMap<>(); + faces.values().forEach(face -> existing.put(new FaceIdentity(face.imageKey(), face.position(), + face.face().path("ExternalImageId").asText(null)), face)); + String imageId = faces.values().stream().filter(face -> face.imageKey().equals(imageKey)) + .map(face -> face.face().path("ImageId").asText()).findFirst().orElseGet(() -> UUID.randomUUID().toString()); + Map additions = new HashMap<>(); + ObjectNode result = mapper.createObjectNode().put("FaceModelVersion", collection.modelVersion()); + ArrayNode records = result.putArray("FaceRecords"); + ArrayNode unindexed = result.putArray("UnindexedFaces"); + for (int i = 0; i < details.size(); i++) { + ObjectNode detail = details.get(i); + if (i >= Math.min(maxFaces, 100)) { + ObjectNode rejected = unindexed.addObject(); + rejected.set("FaceDetail", detail.deepCopy()); + rejected.putArray("Reasons").add("EXCEEDS_MAX_FACES"); + continue; + } + String position = position(detail); + FaceIdentity identity = new FaceIdentity(imageKey, position, externalId); + IndexedFace indexed = existing.get(identity); + if (indexed == null) { + ObjectNode face = mapper.createObjectNode().put("FaceId", UUID.randomUUID().toString()) + .put("ImageId", imageId).put("Confidence", detail.path("Confidence").asDouble(99.0)) + .put("IndexFacesModelVersion", collection.modelVersion()); + face.set("BoundingBox", detail.path("BoundingBox").deepCopy()); + if (externalId != null) { + face.put("ExternalImageId", externalId); + } + indexed = new IndexedFace(imageKey, position, face, detail.deepCopy()); + String id = face.path("FaceId").asText(); + faces.put(id, indexed); + additions.put(id, indexed); + existing.put(identity, indexed); + } + ObjectNode record = records.addObject(); + record.set("Face", indexed.face().deepCopy()); + record.set("FaceDetail", indexed.detail().deepCopy()); + } + if (indexedFaces.writesEntries()) { + additions.forEach((id, face) -> indexedFaces.putEntry(collectionKey, id, face)); + } else if (!additions.isEmpty()) { + indexedFaces.put(collectionKey, Map.copyOf(faces)); + } + return result; + } + + public synchronized ObjectNode listFaces(JsonNode request, String region) { + FaceCollection collection = requireCollection(request, region); + List ids = faceIds(request); + String userId = request.path("UserId").asText(null); + List faces = faces(region, collection).values().stream() + .filter(face -> ids == null || ids.contains(face.face().path("FaceId").asText())) + .filter(face -> userId == null || userId.equals(face.face().path("UserId").asText(null))).toList(); + PaginatedResult page = page(faces, face -> face.face().path("FaceId").asText(), request, + "faces:" + collection.arn() + ":" + Digests.sha256Hex(String.valueOf(ids) + ":" + userId)); + ObjectNode result = mapper.createObjectNode().put("FaceModelVersion", collection.modelVersion()); + ArrayNode entries = result.putArray("Faces"); + page.items().forEach(face -> entries.add(face.face().deepCopy())); + putToken(result, page.nextToken()); + return result; + } + + public synchronized ObjectNode deleteFaces(JsonNode request, String region) { + FaceCollection collection = requireCollection(request, region); + List ids = faceIds(request); + ObjectNode result = mapper.createObjectNode(); + ArrayNode deleted = result.putArray("DeletedFaces"); + ArrayNode unsuccessful = result.putArray("UnsuccessfulFaceDeletions"); + String collectionKey = key(region, collection.id()); + Map remaining = new HashMap<>(faces(region, collection)); + for (String id : new LinkedHashSet<>(ids)) { + if (remaining.remove(id) != null) { + deleted.add(id); + if (indexedFaces.writesEntries()) { + indexedFaces.removeEntry(collectionKey, id); + } + } else { + unsuccessful.addObject().put("FaceId", id).putArray("Reasons").add("FACE_NOT_FOUND"); + } + } + if (!indexedFaces.writesEntries() && !deleted.isEmpty()) { + indexedFaces.put(collectionKey, Map.copyOf(remaining)); + } + return result; + } + + public synchronized ObjectNode searchFaces(JsonNode request, String region) { + FaceCollection collection = requireCollection(request, region); + String id = request.path("FaceId").asText(); + Map faces = faces(region, collection); + IndexedFace source = faces.get(id); + if (source == null) { + throw invalid("FaceId is not indexed in this collection."); + } + ObjectNode result = matches(collection, faces, source.imageKey(), source.position(), id, request); + return result.put("SearchedFaceId", id); + } + + public synchronized ObjectNode searchFacesByImage(JsonNode request, String region, String mockKey) { + FaceCollection collection = requireCollection(request, region); + ObjectNode detail = faceDetails(mockKey).stream().max(Comparator.comparingDouble(RekognitionCollectionService::area)) + .orElseThrow(() -> invalid("There are no faces in the image. Should be at least 1.")); + ObjectNode result = matches(collection, faces(region, collection), imageKey(request.get("Image")), + position(detail), null, request); + result.set("SearchedFaceBoundingBox", detail.path("BoundingBox").deepCopy()); + return result.put("SearchedFaceConfidence", detail.path("Confidence").asDouble(99.0)); + } + + private ObjectNode matches(FaceCollection collection, Map faces, String imageKey, + String position, String excludedId, JsonNode request) { + int limit = request.path("MaxFaces").asInt(4096); + ObjectNode result = mapper.createObjectNode().put("FaceModelVersion", collection.modelVersion()); + ArrayNode matches = result.putArray("FaceMatches"); + faces.values().stream().filter(face -> face.imageKey().equals(imageKey) && face.position().equals(position)) + .filter(face -> !face.face().path("FaceId").asText().equals(excludedId)) + .sorted(Comparator.comparing(face -> face.face().path("FaceId").asText())).limit(limit) + .forEach(face -> { + ObjectNode match = matches.addObject().put("Similarity", 100.0); + match.set("Face", face.face().deepCopy()); + }); + return result; + } + + private List faceDetails(String mockKey) { + JsonNode details = mocks.lookup("rekognition", mockKey, "DetectFaces") + .map(response -> response.path("FaceDetails")).orElse(mapper.createArrayNode()); + List result = new ArrayList<>(); + for (JsonNode detail : details) { + if (detail instanceof ObjectNode object && object.path("BoundingBox").isObject()) { + result.add(object.deepCopy()); + } + } + return result; + } + + private static double area(JsonNode detail) { + return detail.path("BoundingBox").path("Width").asDouble() * detail.path("BoundingBox").path("Height").asDouble(); + } + + private static String position(JsonNode detail) { + JsonNode box = detail.path("BoundingBox"); + return box.path("Left").asDouble() + ":" + box.path("Top").asDouble() + ":" + + box.path("Width").asDouble() + ":" + box.path("Height").asDouble(); + } + + private static String imageKey(JsonNode image) { + if (image.hasNonNull("Bytes")) { + return Digests.sha256Hex(Base64.getEncoder().encodeToString(Base64.getDecoder().decode(image.get("Bytes").asText()))); + } + JsonNode s3 = image.path("S3Object"); + return Digests.sha256Hex(s3.path("Bucket").asText() + "\n" + s3.path("Name").asText() + "\n" + s3.path("Version").asText()); + } + + private PaginatedResult page(List all, Function cursor, JsonNode request, String scope) { + int limit = request.path("MaxResults").asInt(1000); + String token = request.path("NextToken").asText(null); + PaginatedResult page = Pagination.slice(all, cursor, Math.max(1, limit), token, markers, scope, + ignored -> new AwsException("InvalidPaginationTokenException", "Invalid NextToken.", 400)); + if (limit == 0) { + String continuation = page.items().isEmpty() ? null : token == null ? markers.issue(scope, "") : token; + return new PaginatedResult<>(List.of(), continuation); + } + return page; + } + + private static void putToken(ObjectNode result, String token) { + if (token != null) { + result.put("NextToken", token); + } + } + + private FaceCollection requireCollection(JsonNode request, String region) { + String id = request.path("CollectionId").asText(); + return collections.get(key(region, id)).orElseThrow(() -> + new AwsException("ResourceNotFoundException", "Collection not found: " + id, 400)); + } + + private Map faces(String region, FaceCollection collection) { + return indexedFaces.get(key(region, collection.id())).orElse(Map.of()); + } + + private record FaceIdentity(String imageKey, String position, String externalId) {} + + private static String key(String region, String id) { + return region + ":" + id; + } + + private static List faceIds(JsonNode request) { + JsonNode ids = request.get("FaceIds"); + if (ids == null || ids.isNull()) { + return null; + } + List result = new ArrayList<>(); + ids.forEach(id -> result.add(id.asText())); + return result; + } + + private static Map tags(JsonNode request) { + Map result = new HashMap<>(); + request.path("Tags").properties().forEach(tag -> result.put(tag.getKey(), tag.getValue().asText())); + return Map.copyOf(result); + } + + private static AwsException invalid(String message) { + return new AwsException("InvalidParameterException", message, 400); + } + + @Override + public synchronized void clear() { + indexedFaces.clear(); + collections.clear(); + } +} diff --git a/src/main/java/io/floci/aws/services/rekognition/RekognitionJsonHandler.java b/src/main/java/io/floci/aws/services/rekognition/RekognitionJsonHandler.java index 08a05abce1..9213dea3eb 100644 --- a/src/main/java/io/floci/aws/services/rekognition/RekognitionJsonHandler.java +++ b/src/main/java/io/floci/aws/services/rekognition/RekognitionJsonHandler.java @@ -8,6 +8,7 @@ import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; import java.util.function.Predicate; +import java.util.function.Supplier; /** * JSON 1.1 handler for Amazon Rekognition API operations. * Dispatches X-Amz-Target: RekognitionService.* actions to {@link RekognitionService}. @@ -19,37 +20,55 @@ public class RekognitionJsonHandler { private static final Logger LOG = Logger.getLogger(RekognitionJsonHandler.class); private final RekognitionService rekognitionService; private final RekognitionImageValidator imageValidator; + private final RekognitionCollectionService collectionService; @Inject - public RekognitionJsonHandler(RekognitionService rekognitionService, RekognitionImageValidator imageValidator) { + public RekognitionJsonHandler(RekognitionService rekognitionService, RekognitionImageValidator imageValidator, + RekognitionCollectionService collectionService) { this.rekognitionService = rekognitionService; this.imageValidator = imageValidator; + this.collectionService = collectionService; } /** * Dispatches Rekognition actions received via the AwsJson11Controller. - * Only sync image-analysis actions are implemented; face-collection persistence - * (CreateCollection/IndexFaces/SearchFaces), custom-model training (Projects/ + * Sync image-analysis and face collections are implemented; custom-model training (Projects/ * Datasets/ProjectVersions), live video (StreamProcessor), async video jobs * (the Start and Get pairs for Celebrity/Content/Face/Label/Person/Segment/Text * detection), and Face Liveness sessions are out of scope. */ public Response handle(String action, JsonNode request, String region) { LOG.debugv("Rekognition action: {0}", action); - return switch (action) { - case "DetectLabels" -> rekognitionService.detectLabels(validImage(action, request, region)); - case "DetectFaces" -> rekognitionService.detectFaces(validImage(action, request, region)); - case "DetectText" -> rekognitionService.detectText(validImage(action, request, region)); - case "CompareFaces" -> { + Supplier operation = switch (action) { + case "CreateCollection" -> () -> Response.ok(collectionService.createCollection(request, region)).build(); + case "DeleteCollection" -> () -> Response.ok(collectionService.deleteCollection(request, region)).build(); + case "DescribeCollection" -> () -> Response.ok(collectionService.describeCollection(request, region)).build(); + case "ListCollections" -> () -> Response.ok(collectionService.listCollections(request, region)).build(); + case "IndexFaces" -> () -> Response.ok(collectionService.indexFaces(request, region, + validImage(action, request, region))).build(); + case "ListFaces" -> () -> Response.ok(collectionService.listFaces(request, region)).build(); + case "DeleteFaces" -> () -> Response.ok(collectionService.deleteFaces(request, region)).build(); + case "SearchFaces" -> () -> Response.ok(collectionService.searchFaces(request, region)).build(); + case "SearchFacesByImage" -> () -> Response.ok(collectionService.searchFacesByImage(request, region, + validImage(action, request, region))).build(); + case "DetectLabels" -> () -> rekognitionService.detectLabels(validImage(action, request, region)); + case "DetectFaces" -> () -> rekognitionService.detectFaces(validImage(action, request, region)); + case "DetectText" -> () -> rekognitionService.detectText(validImage(action, request, region)); + case "CompareFaces" -> () -> { String sourceKey = requireImage(request, "SourceImage"); requireImage(request, "TargetImage"); imageValidator.validate(action, request, region, "SourceImage", "TargetImage"); - yield rekognitionService.compareFaces(sourceKey); - } - case "DetectModerationLabels" -> rekognitionService.detectModerationLabels(validImage(action, request, region)); - default -> Response.status(400) + return rekognitionService.compareFaces(sourceKey); + }; + case "DetectModerationLabels" -> () -> rekognitionService.detectModerationLabels(validImage(action, request, region)); + default -> null; + }; + if (operation == null) { + return Response.status(400) .entity(new AwsErrorResponse("UnknownOperationException", "Unknown operation: RekognitionService." + action)) .build(); - }; + } + RekognitionRequestShapes.check(action, request); + return operation.get(); } /** The image's mock-response key, once the image has the shape and content Rekognition accepts. */ private String validImage(String action, JsonNode request, String region) { diff --git a/src/main/java/io/floci/aws/services/rekognition/RekognitionRequestShapes.java b/src/main/java/io/floci/aws/services/rekognition/RekognitionRequestShapes.java new file mode 100644 index 0000000000..d15eb2afc9 --- /dev/null +++ b/src/main/java/io/floci/aws/services/rekognition/RekognitionRequestShapes.java @@ -0,0 +1,51 @@ +package io.floci.aws.services.rekognition; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RequestConstraintCheck; + +import java.util.List; + +/** Request constraints vendored from botocore by regen_rekognition_shapes.py. */ +final class RekognitionRequestShapes { + + private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load( + "aws/rekognition-request-shapes.json", "Rekognition request shapes", + new RequestConstraintCheck.Messages() { + @Override + public AwsException type(String path, String type) { + return new AwsException("SerializationException", path + " must be a " + type + ".", 400); + } + + @Override + public AwsException bounds(String path, String type, Long min, Long max, Number size) { + return invalid(path + " is outside the modeled bounds."); + } + + @Override + public AwsException pattern(String path, String pattern) { + return invalid(path + " does not match the modeled pattern."); + } + + @Override + public AwsException enumValue(String path, List values) { + return invalid(path + " must be one of " + values + "."); + } + + @Override + public AwsException required(String path) { + return invalid(path + " is required."); + } + }); + + private RekognitionRequestShapes() { + } + + static void check(String operation, JsonNode request) { + CHECK.check(operation, request); + } + + private static AwsException invalid(String message) { + return new AwsException("InvalidParameterException", message, 400); + } +} diff --git a/src/main/java/io/floci/aws/services/rekognition/model/FaceCollection.java b/src/main/java/io/floci/aws/services/rekognition/model/FaceCollection.java new file mode 100644 index 0000000000..ae070954a5 --- /dev/null +++ b/src/main/java/io/floci/aws/services/rekognition/model/FaceCollection.java @@ -0,0 +1,14 @@ +package io.floci.aws.services.rekognition.model; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.Map; + +@RegisterForReflection +public record FaceCollection(String id, String arn, String modelVersion, double creationTimestamp, + Map tags) { + + @RegisterForReflection + public record IndexedFace(String imageKey, String position, ObjectNode face, ObjectNode detail) {} +} diff --git a/src/main/java/io/floci/aws/services/resourcegroups/ResourceGroupsRequestShapes.java b/src/main/java/io/floci/aws/services/resourcegroups/ResourceGroupsRequestShapes.java index 517fe07f71..e2a71af2d4 100644 --- a/src/main/java/io/floci/aws/services/resourcegroups/ResourceGroupsRequestShapes.java +++ b/src/main/java/io/floci/aws/services/resourcegroups/ResourceGroupsRequestShapes.java @@ -22,7 +22,7 @@ final class ResourceGroupsRequestShapes { } @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 bad(path + " is outside the modeled bounds."); } diff --git a/src/main/java/io/floci/aws/services/securityhub/SecurityHubRequestShapes.java b/src/main/java/io/floci/aws/services/securityhub/SecurityHubRequestShapes.java index 36046153f1..787676c757 100644 --- a/src/main/java/io/floci/aws/services/securityhub/SecurityHubRequestShapes.java +++ b/src/main/java/io/floci/aws/services/securityhub/SecurityHubRequestShapes.java @@ -27,7 +27,7 @@ final class SecurityHubRequestShapes { } @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) { if ("BatchImportFindings.Findings".equals(path)) { return invalid("Findings must contain between " + min + " and " + max + " findings."); } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 436496300a..722f3aed75 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -222,6 +222,8 @@ floci: # metric datapoints, the S3 object index) fold their .wal file into the store's JSON file. compaction-interval-ms: 30000 services: + rekognition: + flush-interval-ms: 5000 ssm: flush-interval-ms: 5000 dynamodb: diff --git a/src/main/resources/aws/rekognition-request-shapes.json b/src/main/resources/aws/rekognition-request-shapes.json new file mode 100644 index 0000000000..0dd24fb655 --- /dev/null +++ b/src/main/resources/aws/rekognition-request-shapes.json @@ -0,0 +1,2013 @@ +{ + "_source": { + "generator": "tools/aws/regen_rekognition_shapes.py", + "botocore": "botocore 1.43.118 (installed package)" + }, + "operations": { + "AssociateFaces": "AssociateFacesRequest", + "CompareFaces": "CompareFacesRequest", + "CopyProjectVersion": "CopyProjectVersionRequest", + "CreateCollection": "CreateCollectionRequest", + "CreateDataset": "CreateDatasetRequest", + "CreateFaceLivenessSession": "CreateFaceLivenessSessionRequest", + "CreateProject": "CreateProjectRequest", + "CreateProjectVersion": "CreateProjectVersionRequest", + "CreateStreamProcessor": "CreateStreamProcessorRequest", + "CreateUser": "CreateUserRequest", + "DeleteCollection": "DeleteCollectionRequest", + "DeleteDataset": "DeleteDatasetRequest", + "DeleteFaces": "DeleteFacesRequest", + "DeleteProject": "DeleteProjectRequest", + "DeleteProjectPolicy": "DeleteProjectPolicyRequest", + "DeleteProjectVersion": "DeleteProjectVersionRequest", + "DeleteStreamProcessor": "DeleteStreamProcessorRequest", + "DeleteUser": "DeleteUserRequest", + "DescribeCollection": "DescribeCollectionRequest", + "DescribeDataset": "DescribeDatasetRequest", + "DescribeProjectVersions": "DescribeProjectVersionsRequest", + "DescribeProjects": "DescribeProjectsRequest", + "DescribeStreamProcessor": "DescribeStreamProcessorRequest", + "DetectCustomLabels": "DetectCustomLabelsRequest", + "DetectFaces": "DetectFacesRequest", + "DetectLabels": "DetectLabelsRequest", + "DetectModerationLabels": "DetectModerationLabelsRequest", + "DetectProtectiveEquipment": "DetectProtectiveEquipmentRequest", + "DetectText": "DetectTextRequest", + "DisassociateFaces": "DisassociateFacesRequest", + "DistributeDatasetEntries": "DistributeDatasetEntriesRequest", + "GetCelebrityInfo": "GetCelebrityInfoRequest", + "GetCelebrityRecognition": "GetCelebrityRecognitionRequest", + "GetContentModeration": "GetContentModerationRequest", + "GetFaceDetection": "GetFaceDetectionRequest", + "GetFaceLivenessSessionResults": "GetFaceLivenessSessionResultsRequest", + "GetFaceSearch": "GetFaceSearchRequest", + "GetLabelDetection": "GetLabelDetectionRequest", + "GetMediaAnalysisJob": "GetMediaAnalysisJobRequest", + "GetPersonTracking": "GetPersonTrackingRequest", + "GetSegmentDetection": "GetSegmentDetectionRequest", + "GetTextDetection": "GetTextDetectionRequest", + "IndexFaces": "IndexFacesRequest", + "ListCollections": "ListCollectionsRequest", + "ListDatasetEntries": "ListDatasetEntriesRequest", + "ListDatasetLabels": "ListDatasetLabelsRequest", + "ListFaces": "ListFacesRequest", + "ListMediaAnalysisJobs": "ListMediaAnalysisJobsRequest", + "ListProjectPolicies": "ListProjectPoliciesRequest", + "ListStreamProcessors": "ListStreamProcessorsRequest", + "ListTagsForResource": "ListTagsForResourceRequest", + "ListUsers": "ListUsersRequest", + "PutProjectPolicy": "PutProjectPolicyRequest", + "RecognizeCelebrities": "RecognizeCelebritiesRequest", + "SearchFaces": "SearchFacesRequest", + "SearchFacesByImage": "SearchFacesByImageRequest", + "SearchUsers": "SearchUsersRequest", + "SearchUsersByImage": "SearchUsersByImageRequest", + "StartCelebrityRecognition": "StartCelebrityRecognitionRequest", + "StartContentModeration": "StartContentModerationRequest", + "StartFaceDetection": "StartFaceDetectionRequest", + "StartFaceSearch": "StartFaceSearchRequest", + "StartLabelDetection": "StartLabelDetectionRequest", + "StartMediaAnalysisJob": "StartMediaAnalysisJobRequest", + "StartPersonTracking": "StartPersonTrackingRequest", + "StartProjectVersion": "StartProjectVersionRequest", + "StartSegmentDetection": "StartSegmentDetectionRequest", + "StartStreamProcessor": "StartStreamProcessorRequest", + "StartTextDetection": "StartTextDetectionRequest", + "StopProjectVersion": "StopProjectVersionRequest", + "StopStreamProcessor": "StopStreamProcessorRequest", + "TagResource": "TagResourceRequest", + "UntagResource": "UntagResourceRequest", + "UpdateDatasetEntries": "UpdateDatasetEntriesRequest", + "UpdateStreamProcessor": "UpdateStreamProcessorRequest" + }, + "shapes": { + "Asset": { + "type": "structure", + "members": { + "GroundTruthManifest": "GroundTruthManifest" + } + }, + "Assets": { + "type": "list", + "member": "Asset" + }, + "AssociateFacesRequest": { + "type": "structure", + "required": [ + "CollectionId", + "UserId", + "FaceIds" + ], + "members": { + "CollectionId": "CollectionId", + "UserId": "UserId", + "FaceIds": "UserFaceIdList", + "UserMatchThreshold": "Percent", + "ClientRequestToken": "ClientRequestToken" + } + }, + "Attribute": { + "type": "string", + "enum": [ + "DEFAULT", + "ALL", + "AGE_RANGE", + "BEARD", + "EMOTIONS", + "EYE_DIRECTION", + "EYEGLASSES", + "EYES_OPEN", + "GENDER", + "MOUTH_OPEN", + "MUSTACHE", + "FACE_OCCLUDED", + "SMILE", + "SUNGLASSES" + ] + }, + "Attributes": { + "type": "list", + "member": "Attribute" + }, + "AuditImagesLimit": { + "type": "integer", + "min": 0, + "max": 4 + }, + "BlackFrame": { + "type": "structure", + "members": { + "MaxPixelThreshold": "MaxPixelThreshold", + "MinCoveragePercentage": "MinCoveragePercentage" + } + }, + "Boolean": { + "type": "boolean" + }, + "BoundingBox": { + "type": "structure", + "members": { + "Width": "Float", + "Height": "Float", + "Left": "Float", + "Top": "Float" + } + }, + "BoundingBoxHeight": { + "type": "float", + "min": 0, + "max": 1 + }, + "BoundingBoxWidth": { + "type": "float", + "min": 0, + "max": 1 + }, + "CelebrityRecognitionSortBy": { + "type": "string", + "enum": [ + "ID", + "TIMESTAMP" + ] + }, + "ChallengePreference": { + "type": "structure", + "required": [ + "Type" + ], + "members": { + "Type": "ChallengeType", + "Versions": "Versions" + } + }, + "ChallengePreferences": { + "type": "list", + "member": "ChallengePreference" + }, + "ChallengeType": { + "type": "string", + "enum": [ + "FaceMovementAndLightChallenge", + "FaceMovementChallenge" + ] + }, + "ClientRequestToken": { + "type": "string", + "min": 1, + "max": 64, + "pattern": "^[a-zA-Z0-9-_]+$" + }, + "CollectionId": { + "type": "string", + "min": 1, + "max": 255, + "pattern": "[a-zA-Z0-9_.\\-]+" + }, + "CompareFacesRequest": { + "type": "structure", + "required": [ + "SourceImage", + "TargetImage" + ], + "members": { + "SourceImage": "Image", + "TargetImage": "Image", + "SimilarityThreshold": "Percent", + "QualityFilter": "QualityFilter" + } + }, + "ConnectedHomeLabel": { + "type": "string" + }, + "ConnectedHomeLabels": { + "type": "list", + "min": 1, + "max": 128, + "member": "ConnectedHomeLabel" + }, + "ConnectedHomeSettings": { + "type": "structure", + "required": [ + "Labels" + ], + "members": { + "Labels": "ConnectedHomeLabels", + "MinConfidence": "Percent" + } + }, + "ConnectedHomeSettingsForUpdate": { + "type": "structure", + "members": { + "Labels": "ConnectedHomeLabels", + "MinConfidence": "Percent" + } + }, + "ContentClassifier": { + "type": "string", + "enum": [ + "FreeOfPersonallyIdentifiableInformation", + "FreeOfAdultContent" + ] + }, + "ContentClassifiers": { + "type": "list", + "max": 256, + "member": "ContentClassifier" + }, + "ContentModerationAggregateBy": { + "type": "string", + "enum": [ + "TIMESTAMPS", + "SEGMENTS" + ] + }, + "ContentModerationSortBy": { + "type": "string", + "enum": [ + "NAME", + "TIMESTAMP" + ] + }, + "CopyProjectVersionRequest": { + "type": "structure", + "required": [ + "SourceProjectArn", + "SourceProjectVersionArn", + "DestinationProjectArn", + "VersionName", + "OutputConfig" + ], + "members": { + "SourceProjectArn": "ProjectArn", + "SourceProjectVersionArn": "ProjectVersionArn", + "DestinationProjectArn": "ProjectArn", + "VersionName": "VersionName", + "OutputConfig": "OutputConfig", + "Tags": "TagMap", + "KmsKeyId": "KmsKeyId" + } + }, + "CreateCollectionRequest": { + "type": "structure", + "required": [ + "CollectionId" + ], + "members": { + "CollectionId": "CollectionId", + "Tags": "TagMap" + } + }, + "CreateDatasetRequest": { + "type": "structure", + "required": [ + "DatasetType", + "ProjectArn" + ], + "members": { + "DatasetSource": "DatasetSource", + "DatasetType": "DatasetType", + "ProjectArn": "ProjectArn", + "Tags": "TagMap" + } + }, + "CreateFaceLivenessSessionRequest": { + "type": "structure", + "members": { + "KmsKeyId": "KmsKeyId", + "Settings": "CreateFaceLivenessSessionRequestSettings", + "ClientRequestToken": "ClientRequestToken" + } + }, + "CreateFaceLivenessSessionRequestSettings": { + "type": "structure", + "members": { + "OutputConfig": "LivenessOutputConfig", + "AuditImagesLimit": "AuditImagesLimit", + "ChallengePreferences": "ChallengePreferences" + } + }, + "CreateProjectRequest": { + "type": "structure", + "required": [ + "ProjectName" + ], + "members": { + "ProjectName": "ProjectName", + "Feature": "CustomizationFeature", + "AutoUpdate": "ProjectAutoUpdate", + "Tags": "TagMap" + } + }, + "CreateProjectVersionRequest": { + "type": "structure", + "required": [ + "ProjectArn", + "VersionName", + "OutputConfig" + ], + "members": { + "ProjectArn": "ProjectArn", + "VersionName": "VersionName", + "OutputConfig": "OutputConfig", + "TrainingData": "TrainingData", + "TestingData": "TestingData", + "Tags": "TagMap", + "KmsKeyId": "KmsKeyId", + "VersionDescription": "VersionDescription", + "FeatureConfig": "CustomizationFeatureConfig" + } + }, + "CreateStreamProcessorRequest": { + "type": "structure", + "required": [ + "Input", + "Output", + "Name", + "Settings", + "RoleArn" + ], + "members": { + "Input": "StreamProcessorInput", + "Output": "StreamProcessorOutput", + "Name": "StreamProcessorName", + "Settings": "StreamProcessorSettings", + "RoleArn": "RoleArn", + "Tags": "TagMap", + "NotificationChannel": "StreamProcessorNotificationChannel", + "KmsKeyId": "KmsKeyId", + "RegionsOfInterest": "RegionsOfInterest", + "DataSharingPreference": "StreamProcessorDataSharingPreference" + } + }, + "CreateUserRequest": { + "type": "structure", + "required": [ + "CollectionId", + "UserId" + ], + "members": { + "CollectionId": "CollectionId", + "UserId": "UserId", + "ClientRequestToken": "ClientRequestToken" + } + }, + "CustomizationFeature": { + "type": "string", + "enum": [ + "CONTENT_MODERATION", + "CUSTOM_LABELS" + ] + }, + "CustomizationFeatureConfig": { + "type": "structure", + "members": { + "ContentModeration": "CustomizationFeatureContentModerationConfig" + } + }, + "CustomizationFeatureContentModerationConfig": { + "type": "structure", + "members": { + "ConfidenceThreshold": "Percent" + } + }, + "CustomizationFeatures": { + "type": "list", + "min": 1, + "max": 2, + "member": "CustomizationFeature" + }, + "DatasetArn": { + "type": "string", + "min": 20, + "max": 2048, + "pattern": "(^arn:[a-z\\d-]+:rekognition:[a-z\\d-]+:\\d{12}:project\\/[a-zA-Z0-9_.\\-]{1,255}\\/dataset\\/(train|test)\\/[0-9]+$)" + }, + "DatasetChanges": { + "type": "structure", + "required": [ + "GroundTruth" + ], + "members": { + "GroundTruth": "GroundTruthBlob" + } + }, + "DatasetLabel": { + "type": "string", + "min": 1, + "max": 255, + "pattern": ".{1,}" + }, + "DatasetLabels": { + "type": "list", + "min": 1, + "max": 10, + "member": "DatasetLabel" + }, + "DatasetSource": { + "type": "structure", + "members": { + "GroundTruthManifest": "GroundTruthManifest", + "DatasetArn": "DatasetArn" + } + }, + "DatasetType": { + "type": "string", + "enum": [ + "TRAIN", + "TEST" + ] + }, + "DeleteCollectionRequest": { + "type": "structure", + "required": [ + "CollectionId" + ], + "members": { + "CollectionId": "CollectionId" + } + }, + "DeleteDatasetRequest": { + "type": "structure", + "required": [ + "DatasetArn" + ], + "members": { + "DatasetArn": "DatasetArn" + } + }, + "DeleteFacesRequest": { + "type": "structure", + "required": [ + "CollectionId", + "FaceIds" + ], + "members": { + "CollectionId": "CollectionId", + "FaceIds": "FaceIdList" + } + }, + "DeleteProjectPolicyRequest": { + "type": "structure", + "required": [ + "ProjectArn", + "PolicyName" + ], + "members": { + "ProjectArn": "ProjectArn", + "PolicyName": "ProjectPolicyName", + "PolicyRevisionId": "ProjectPolicyRevisionId" + } + }, + "DeleteProjectRequest": { + "type": "structure", + "required": [ + "ProjectArn" + ], + "members": { + "ProjectArn": "ProjectArn" + } + }, + "DeleteProjectVersionRequest": { + "type": "structure", + "required": [ + "ProjectVersionArn" + ], + "members": { + "ProjectVersionArn": "ProjectVersionArn" + } + }, + "DeleteStreamProcessorRequest": { + "type": "structure", + "required": [ + "Name" + ], + "members": { + "Name": "StreamProcessorName" + } + }, + "DeleteUserRequest": { + "type": "structure", + "required": [ + "CollectionId", + "UserId" + ], + "members": { + "CollectionId": "CollectionId", + "UserId": "UserId", + "ClientRequestToken": "ClientRequestToken" + } + }, + "DescribeCollectionRequest": { + "type": "structure", + "required": [ + "CollectionId" + ], + "members": { + "CollectionId": "CollectionId" + } + }, + "DescribeDatasetRequest": { + "type": "structure", + "required": [ + "DatasetArn" + ], + "members": { + "DatasetArn": "DatasetArn" + } + }, + "DescribeProjectVersionsRequest": { + "type": "structure", + "required": [ + "ProjectArn" + ], + "members": { + "ProjectArn": "ProjectArn", + "VersionNames": "VersionNames", + "NextToken": "ExtendedPaginationToken", + "MaxResults": "ProjectVersionsPageSize" + } + }, + "DescribeProjectsRequest": { + "type": "structure", + "members": { + "NextToken": "ExtendedPaginationToken", + "MaxResults": "ProjectsPageSize", + "ProjectNames": "ProjectNames", + "Features": "CustomizationFeatures" + } + }, + "DescribeStreamProcessorRequest": { + "type": "structure", + "required": [ + "Name" + ], + "members": { + "Name": "StreamProcessorName" + } + }, + "DetectCustomLabelsRequest": { + "type": "structure", + "required": [ + "ProjectVersionArn", + "Image" + ], + "members": { + "ProjectVersionArn": "ProjectVersionArn", + "Image": "Image", + "MaxResults": "UInteger", + "MinConfidence": "Percent" + } + }, + "DetectFacesRequest": { + "type": "structure", + "required": [ + "Image" + ], + "members": { + "Image": "Image", + "Attributes": "Attributes" + } + }, + "DetectLabelsFeatureList": { + "type": "list", + "min": 0, + "max": 2, + "member": "DetectLabelsFeatureName" + }, + "DetectLabelsFeatureName": { + "type": "string", + "enum": [ + "GENERAL_LABELS", + "IMAGE_PROPERTIES" + ] + }, + "DetectLabelsImagePropertiesSettings": { + "type": "structure", + "members": { + "MaxDominantColors": "DetectLabelsMaxDominantColors" + } + }, + "DetectLabelsMaxDominantColors": { + "type": "integer", + "min": 0, + "max": 20 + }, + "DetectLabelsRequest": { + "type": "structure", + "required": [ + "Image" + ], + "members": { + "Image": "Image", + "MaxLabels": "UInteger", + "MinConfidence": "Percent", + "Features": "DetectLabelsFeatureList", + "Settings": "DetectLabelsSettings" + } + }, + "DetectLabelsSettings": { + "type": "structure", + "members": { + "GeneralLabels": "GeneralLabelsSettings", + "ImageProperties": "DetectLabelsImagePropertiesSettings" + } + }, + "DetectModerationLabelsRequest": { + "type": "structure", + "required": [ + "Image" + ], + "members": { + "Image": "Image", + "MinConfidence": "Percent", + "HumanLoopConfig": "HumanLoopConfig", + "ProjectVersion": "ProjectVersionId" + } + }, + "DetectProtectiveEquipmentRequest": { + "type": "structure", + "required": [ + "Image" + ], + "members": { + "Image": "Image", + "SummarizationAttributes": "ProtectiveEquipmentSummarizationAttributes" + } + }, + "DetectTextFilters": { + "type": "structure", + "members": { + "WordFilter": "DetectionFilter", + "RegionsOfInterest": "RegionsOfInterest" + } + }, + "DetectTextRequest": { + "type": "structure", + "required": [ + "Image" + ], + "members": { + "Image": "Image", + "Filters": "DetectTextFilters" + } + }, + "DetectionFilter": { + "type": "structure", + "members": { + "MinConfidence": "Percent", + "MinBoundingBoxHeight": "BoundingBoxHeight", + "MinBoundingBoxWidth": "BoundingBoxWidth" + } + }, + "DisassociateFacesRequest": { + "type": "structure", + "required": [ + "CollectionId", + "UserId", + "FaceIds" + ], + "members": { + "CollectionId": "CollectionId", + "UserId": "UserId", + "ClientRequestToken": "ClientRequestToken", + "FaceIds": "UserFaceIdList" + } + }, + "DistributeDataset": { + "type": "structure", + "required": [ + "Arn" + ], + "members": { + "Arn": "DatasetArn" + } + }, + "DistributeDatasetEntriesRequest": { + "type": "structure", + "required": [ + "Datasets" + ], + "members": { + "Datasets": "DistributeDatasetMetadataList" + } + }, + "DistributeDatasetMetadataList": { + "type": "list", + "min": 2, + "max": 2, + "member": "DistributeDataset" + }, + "ExtendedPaginationToken": { + "type": "string", + "max": 1024 + }, + "ExternalImageId": { + "type": "string", + "min": 1, + "max": 255, + "pattern": "[a-zA-Z0-9_.\\-:]+" + }, + "FaceAttributes": { + "type": "string", + "enum": [ + "DEFAULT", + "ALL" + ] + }, + "FaceId": { + "type": "string", + "pattern": "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" + }, + "FaceIdList": { + "type": "list", + "min": 1, + "max": 4096, + "member": "FaceId" + }, + "FaceSearchSettings": { + "type": "structure", + "members": { + "CollectionId": "CollectionId", + "FaceMatchThreshold": "Percent" + } + }, + "FaceSearchSortBy": { + "type": "string", + "enum": [ + "INDEX", + "TIMESTAMP" + ] + }, + "Float": { + "type": "float" + }, + "FlowDefinitionArn": { + "type": "string", + "max": 256 + }, + "GeneralLabelsFilterList": { + "type": "list", + "min": 0, + "max": 100, + "member": "GeneralLabelsFilterValue" + }, + "GeneralLabelsFilterValue": { + "type": "string", + "min": 0, + "max": 50, + "pattern": "[A-Za-z0-9\u00e0\u00e2\u00e8\u00e7\u00f1\u00f3'-_(). ]*" + }, + "GeneralLabelsSettings": { + "type": "structure", + "members": { + "LabelInclusionFilters": "GeneralLabelsFilterList", + "LabelExclusionFilters": "GeneralLabelsFilterList", + "LabelCategoryInclusionFilters": "GeneralLabelsFilterList", + "LabelCategoryExclusionFilters": "GeneralLabelsFilterList" + } + }, + "GetCelebrityInfoRequest": { + "type": "structure", + "required": [ + "Id" + ], + "members": { + "Id": "RekognitionUniqueId" + } + }, + "GetCelebrityRecognitionRequest": { + "type": "structure", + "required": [ + "JobId" + ], + "members": { + "JobId": "JobId", + "MaxResults": "MaxResults", + "NextToken": "PaginationToken", + "SortBy": "CelebrityRecognitionSortBy" + } + }, + "GetContentModerationRequest": { + "type": "structure", + "required": [ + "JobId" + ], + "members": { + "JobId": "JobId", + "MaxResults": "MaxResults", + "NextToken": "PaginationToken", + "SortBy": "ContentModerationSortBy", + "AggregateBy": "ContentModerationAggregateBy" + } + }, + "GetFaceDetectionRequest": { + "type": "structure", + "required": [ + "JobId" + ], + "members": { + "JobId": "JobId", + "MaxResults": "MaxResults", + "NextToken": "PaginationToken" + } + }, + "GetFaceLivenessSessionResultsRequest": { + "type": "structure", + "required": [ + "SessionId" + ], + "members": { + "SessionId": "LivenessSessionId" + } + }, + "GetFaceSearchRequest": { + "type": "structure", + "required": [ + "JobId" + ], + "members": { + "JobId": "JobId", + "MaxResults": "MaxResults", + "NextToken": "PaginationToken", + "SortBy": "FaceSearchSortBy" + } + }, + "GetLabelDetectionRequest": { + "type": "structure", + "required": [ + "JobId" + ], + "members": { + "JobId": "JobId", + "MaxResults": "MaxResults", + "NextToken": "PaginationToken", + "SortBy": "LabelDetectionSortBy", + "AggregateBy": "LabelDetectionAggregateBy" + } + }, + "GetMediaAnalysisJobRequest": { + "type": "structure", + "required": [ + "JobId" + ], + "members": { + "JobId": "MediaAnalysisJobId" + } + }, + "GetPersonTrackingRequest": { + "type": "structure", + "required": [ + "JobId" + ], + "members": { + "JobId": "JobId", + "MaxResults": "MaxResults", + "NextToken": "PaginationToken", + "SortBy": "PersonTrackingSortBy" + } + }, + "GetSegmentDetectionRequest": { + "type": "structure", + "required": [ + "JobId" + ], + "members": { + "JobId": "JobId", + "MaxResults": "MaxResults", + "NextToken": "PaginationToken" + } + }, + "GetTextDetectionRequest": { + "type": "structure", + "required": [ + "JobId" + ], + "members": { + "JobId": "JobId", + "MaxResults": "MaxResults", + "NextToken": "PaginationToken" + } + }, + "GroundTruthBlob": { + "type": "blob", + "min": 1, + "max": 5242880 + }, + "GroundTruthManifest": { + "type": "structure", + "members": { + "S3Object": "S3Object" + } + }, + "HasErrors": { + "type": "boolean" + }, + "HumanLoopConfig": { + "type": "structure", + "required": [ + "HumanLoopName", + "FlowDefinitionArn" + ], + "members": { + "HumanLoopName": "HumanLoopName", + "FlowDefinitionArn": "FlowDefinitionArn", + "DataAttributes": "HumanLoopDataAttributes" + } + }, + "HumanLoopDataAttributes": { + "type": "structure", + "members": { + "ContentClassifiers": "ContentClassifiers" + } + }, + "HumanLoopName": { + "type": "string", + "min": 1, + "max": 63, + "pattern": "^[a-z0-9](-*[a-z0-9])*" + }, + "Image": { + "type": "structure", + "members": { + "S3Object": "S3Object" + } + }, + "IndexFacesRequest": { + "type": "structure", + "required": [ + "CollectionId", + "Image" + ], + "members": { + "CollectionId": "CollectionId", + "Image": "Image", + "ExternalImageId": "ExternalImageId", + "DetectionAttributes": "Attributes", + "MaxFaces": "MaxFacesToIndex", + "QualityFilter": "QualityFilter" + } + }, + "InferenceUnits": { + "type": "integer", + "min": 1 + }, + "IsLabeled": { + "type": "boolean" + }, + "JobId": { + "type": "string", + "min": 1, + "max": 64, + "pattern": "^[a-zA-Z0-9-_]+$" + }, + "JobTag": { + "type": "string", + "min": 1, + "max": 1024, + "pattern": "[a-zA-Z0-9_.\\-:+=\\/]+" + }, + "KinesisDataArn": { + "type": "string", + "pattern": "(^arn:([a-z\\d-]+):kinesis:([a-z\\d-]+):\\d{12}:.+$)" + }, + "KinesisDataStream": { + "type": "structure", + "members": { + "Arn": "KinesisDataArn" + } + }, + "KinesisVideoArn": { + "type": "string", + "pattern": "(^arn:([a-z\\d-]+):kinesisvideo:([a-z\\d-]+):\\d{12}:.+$)" + }, + "KinesisVideoStream": { + "type": "structure", + "members": { + "Arn": "KinesisVideoArn" + } + }, + "KinesisVideoStreamFragmentNumber": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "^[0-9]+$" + }, + "KinesisVideoStreamStartSelector": { + "type": "structure", + "members": { + "ProducerTimestamp": "ULong", + "FragmentNumber": "KinesisVideoStreamFragmentNumber" + } + }, + "KmsKeyId": { + "type": "string", + "min": 1, + "max": 2048, + "pattern": "^[A-Za-z0-9][A-Za-z0-9:_/+=,@.-]{0,2048}$" + }, + "LabelDetectionAggregateBy": { + "type": "string", + "enum": [ + "TIMESTAMPS", + "SEGMENTS" + ] + }, + "LabelDetectionFeatureList": { + "type": "list", + "min": 0, + "max": 1, + "member": "LabelDetectionFeatureName" + }, + "LabelDetectionFeatureName": { + "type": "string", + "enum": [ + "GENERAL_LABELS" + ] + }, + "LabelDetectionSettings": { + "type": "structure", + "members": { + "GeneralLabels": "GeneralLabelsSettings" + } + }, + "LabelDetectionSortBy": { + "type": "string", + "enum": [ + "NAME", + "TIMESTAMP" + ] + }, + "ListCollectionsRequest": { + "type": "structure", + "members": { + "NextToken": "PaginationToken", + "MaxResults": "PageSize" + } + }, + "ListDatasetEntriesPageSize": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListDatasetEntriesRequest": { + "type": "structure", + "required": [ + "DatasetArn" + ], + "members": { + "DatasetArn": "DatasetArn", + "ContainsLabels": "DatasetLabels", + "Labeled": "IsLabeled", + "SourceRefContains": "QueryString", + "HasErrors": "HasErrors", + "NextToken": "ExtendedPaginationToken", + "MaxResults": "ListDatasetEntriesPageSize" + } + }, + "ListDatasetLabelsPageSize": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListDatasetLabelsRequest": { + "type": "structure", + "required": [ + "DatasetArn" + ], + "members": { + "DatasetArn": "DatasetArn", + "NextToken": "ExtendedPaginationToken", + "MaxResults": "ListDatasetLabelsPageSize" + } + }, + "ListFacesRequest": { + "type": "structure", + "required": [ + "CollectionId" + ], + "members": { + "CollectionId": "CollectionId", + "NextToken": "PaginationToken", + "MaxResults": "PageSize", + "UserId": "UserId", + "FaceIds": "FaceIdList" + } + }, + "ListMediaAnalysisJobsPageSize": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListMediaAnalysisJobsRequest": { + "type": "structure", + "members": { + "NextToken": "ExtendedPaginationToken", + "MaxResults": "ListMediaAnalysisJobsPageSize" + } + }, + "ListProjectPoliciesPageSize": { + "type": "integer", + "min": 1, + "max": 5 + }, + "ListProjectPoliciesRequest": { + "type": "structure", + "required": [ + "ProjectArn" + ], + "members": { + "ProjectArn": "ProjectArn", + "NextToken": "ExtendedPaginationToken", + "MaxResults": "ListProjectPoliciesPageSize" + } + }, + "ListStreamProcessorsRequest": { + "type": "structure", + "members": { + "NextToken": "PaginationToken", + "MaxResults": "MaxResults" + } + }, + "ListTagsForResourceRequest": { + "type": "structure", + "required": [ + "ResourceArn" + ], + "members": { + "ResourceArn": "ResourceArn" + } + }, + "ListUsersRequest": { + "type": "structure", + "required": [ + "CollectionId" + ], + "members": { + "CollectionId": "CollectionId", + "MaxResults": "MaxUserResults", + "NextToken": "PaginationToken" + } + }, + "LivenessOutputConfig": { + "type": "structure", + "required": [ + "S3Bucket" + ], + "members": { + "S3Bucket": "S3Bucket", + "S3KeyPrefix": "LivenessS3KeyPrefix" + } + }, + "LivenessS3KeyPrefix": { + "type": "string", + "max": 950, + "pattern": "\\S*" + }, + "LivenessSessionId": { + "type": "string", + "min": 36, + "max": 36, + "pattern": "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" + }, + "MaxDurationInSecondsULong": { + "type": "long", + "min": 1, + "max": 120 + }, + "MaxFaces": { + "type": "integer", + "min": 1, + "max": 4096 + }, + "MaxFacesToIndex": { + "type": "integer", + "min": 1 + }, + "MaxPixelThreshold": { + "type": "float", + "min": 0, + "max": 1 + }, + "MaxResults": { + "type": "integer", + "min": 1 + }, + "MaxUserResults": { + "type": "integer", + "min": 1, + "max": 500 + }, + "MediaAnalysisDetectModerationLabelsConfig": { + "type": "structure", + "members": { + "MinConfidence": "Percent", + "ProjectVersion": "ProjectVersionId" + } + }, + "MediaAnalysisInput": { + "type": "structure", + "required": [ + "S3Object" + ], + "members": { + "S3Object": "S3Object" + } + }, + "MediaAnalysisJobId": { + "type": "string", + "min": 1, + "max": 64, + "pattern": "^[a-zA-Z0-9-_]+$" + }, + "MediaAnalysisJobName": { + "type": "string", + "min": 1, + "max": 64, + "pattern": "[a-zA-Z0-9_.\\-]+" + }, + "MediaAnalysisOperationsConfig": { + "type": "structure", + "members": { + "DetectModerationLabels": "MediaAnalysisDetectModerationLabelsConfig" + } + }, + "MediaAnalysisOutputConfig": { + "type": "structure", + "required": [ + "S3Bucket" + ], + "members": { + "S3Bucket": "S3Bucket", + "S3KeyPrefix": "MediaAnalysisS3KeyPrefix" + } + }, + "MediaAnalysisS3KeyPrefix": { + "type": "string", + "max": 800, + "pattern": "\\S*" + }, + "MinCoveragePercentage": { + "type": "float", + "min": 0, + "max": 100 + }, + "NotificationChannel": { + "type": "structure", + "required": [ + "SNSTopicArn", + "RoleArn" + ], + "members": { + "SNSTopicArn": "SNSTopicArn", + "RoleArn": "RoleArn" + } + }, + "OutputConfig": { + "type": "structure", + "members": { + "S3Bucket": "S3Bucket", + "S3KeyPrefix": "S3KeyPrefix" + } + }, + "PageSize": { + "type": "integer", + "min": 0, + "max": 4096 + }, + "PaginationToken": { + "type": "string", + "max": 255 + }, + "Percent": { + "type": "float", + "min": 0, + "max": 100 + }, + "PersonTrackingSortBy": { + "type": "string", + "enum": [ + "INDEX", + "TIMESTAMP" + ] + }, + "Point": { + "type": "structure", + "members": { + "X": "Float", + "Y": "Float" + } + }, + "Polygon": { + "type": "list", + "member": "Point" + }, + "ProjectArn": { + "type": "string", + "min": 20, + "max": 2048, + "pattern": "(^arn:[a-z\\d-]+:rekognition:[a-z\\d-]+:\\d{12}:project\\/[a-zA-Z0-9_.\\-]{1,255}\\/[0-9]+$)" + }, + "ProjectAutoUpdate": { + "type": "string", + "enum": [ + "ENABLED", + "DISABLED" + ] + }, + "ProjectName": { + "type": "string", + "min": 1, + "max": 255, + "pattern": "[a-zA-Z0-9_.\\-]+" + }, + "ProjectNames": { + "type": "list", + "min": 1, + "max": 10, + "member": "ProjectName" + }, + "ProjectPolicyDocument": { + "type": "string", + "min": 1, + "max": 2000, + "pattern": "[\\u0009\\u000A\\u000D\\u0020-\\u00FF]+" + }, + "ProjectPolicyName": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "[a-zA-Z0-9_.\\-]+" + }, + "ProjectPolicyRevisionId": { + "type": "string", + "max": 64, + "pattern": "[0-9A-Fa-f]+" + }, + "ProjectVersionArn": { + "type": "string", + "min": 20, + "max": 2048, + "pattern": "(^arn:[a-z\\d-]+:rekognition:[a-z\\d-]+:\\d{12}:project\\/[a-zA-Z0-9_.\\-]{1,255}\\/version\\/[a-zA-Z0-9_.\\-]{1,255}\\/[0-9]+$)" + }, + "ProjectVersionId": { + "type": "string", + "min": 20, + "max": 2048, + "pattern": "(^arn:[a-z\\d-]+:rekognition:[a-z\\d-]+:\\d{12}:project\\/[a-zA-Z0-9_.\\-]{1,255}\\/version\\/[a-zA-Z0-9_.\\-]{1,255}\\/[0-9]+$)" + }, + "ProjectVersionsPageSize": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ProjectsPageSize": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ProtectiveEquipmentSummarizationAttributes": { + "type": "structure", + "required": [ + "MinConfidence", + "RequiredEquipmentTypes" + ], + "members": { + "MinConfidence": "Percent", + "RequiredEquipmentTypes": "ProtectiveEquipmentTypes" + } + }, + "ProtectiveEquipmentType": { + "type": "string", + "enum": [ + "FACE_COVER", + "HAND_COVER", + "HEAD_COVER" + ] + }, + "ProtectiveEquipmentTypes": { + "type": "list", + "member": "ProtectiveEquipmentType" + }, + "PutProjectPolicyRequest": { + "type": "structure", + "required": [ + "ProjectArn", + "PolicyName", + "PolicyDocument" + ], + "members": { + "ProjectArn": "ProjectArn", + "PolicyName": "ProjectPolicyName", + "PolicyRevisionId": "ProjectPolicyRevisionId", + "PolicyDocument": "ProjectPolicyDocument" + } + }, + "QualityFilter": { + "type": "string", + "enum": [ + "NONE", + "AUTO", + "LOW", + "MEDIUM", + "HIGH" + ] + }, + "QueryString": { + "type": "string", + "min": 1, + "max": 2048, + "pattern": ".*\\S.*" + }, + "RecognizeCelebritiesRequest": { + "type": "structure", + "required": [ + "Image" + ], + "members": { + "Image": "Image" + } + }, + "RegionOfInterest": { + "type": "structure", + "members": { + "BoundingBox": "BoundingBox", + "Polygon": "Polygon" + } + }, + "RegionsOfInterest": { + "type": "list", + "min": 0, + "max": 10, + "member": "RegionOfInterest" + }, + "RekognitionUniqueId": { + "type": "string", + "pattern": "[0-9A-Za-z]*" + }, + "ResourceArn": { + "type": "string", + "min": 20, + "max": 2048 + }, + "RoleArn": { + "type": "string", + "pattern": "arn:aws:iam::\\d{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+" + }, + "S3Bucket": { + "type": "string", + "min": 3, + "max": 255, + "pattern": "[0-9A-Za-z\\.\\-_]*" + }, + "S3Destination": { + "type": "structure", + "members": { + "Bucket": "S3Bucket", + "KeyPrefix": "S3KeyPrefix" + } + }, + "S3KeyPrefix": { + "type": "string", + "max": 1024 + }, + "S3Object": { + "type": "structure", + "members": { + "Bucket": "S3Bucket", + "Name": "S3ObjectName", + "Version": "S3ObjectVersion" + } + }, + "S3ObjectName": { + "type": "string", + "min": 1, + "max": 1024 + }, + "S3ObjectVersion": { + "type": "string", + "min": 1, + "max": 1024 + }, + "SNSTopicArn": { + "type": "string", + "pattern": "(^arn:aws:sns:.*:\\w{12}:.+$)" + }, + "SearchFacesByImageRequest": { + "type": "structure", + "required": [ + "CollectionId", + "Image" + ], + "members": { + "CollectionId": "CollectionId", + "Image": "Image", + "MaxFaces": "MaxFaces", + "FaceMatchThreshold": "Percent", + "QualityFilter": "QualityFilter" + } + }, + "SearchFacesRequest": { + "type": "structure", + "required": [ + "CollectionId", + "FaceId" + ], + "members": { + "CollectionId": "CollectionId", + "FaceId": "FaceId", + "MaxFaces": "MaxFaces", + "FaceMatchThreshold": "Percent" + } + }, + "SearchUsersByImageRequest": { + "type": "structure", + "required": [ + "CollectionId", + "Image" + ], + "members": { + "CollectionId": "CollectionId", + "Image": "Image", + "UserMatchThreshold": "Percent", + "MaxUsers": "MaxUserResults", + "QualityFilter": "QualityFilter" + } + }, + "SearchUsersRequest": { + "type": "structure", + "required": [ + "CollectionId" + ], + "members": { + "CollectionId": "CollectionId", + "UserId": "UserId", + "FaceId": "FaceId", + "UserMatchThreshold": "Percent", + "MaxUsers": "MaxUserResults" + } + }, + "SegmentConfidence": { + "type": "float", + "min": 50, + "max": 100 + }, + "SegmentType": { + "type": "string", + "enum": [ + "TECHNICAL_CUE", + "SHOT" + ] + }, + "SegmentTypes": { + "type": "list", + "min": 1, + "member": "SegmentType" + }, + "StartCelebrityRecognitionRequest": { + "type": "structure", + "required": [ + "Video" + ], + "members": { + "Video": "Video", + "ClientRequestToken": "ClientRequestToken", + "NotificationChannel": "NotificationChannel", + "JobTag": "JobTag" + } + }, + "StartContentModerationRequest": { + "type": "structure", + "required": [ + "Video" + ], + "members": { + "Video": "Video", + "MinConfidence": "Percent", + "ClientRequestToken": "ClientRequestToken", + "NotificationChannel": "NotificationChannel", + "JobTag": "JobTag" + } + }, + "StartFaceDetectionRequest": { + "type": "structure", + "required": [ + "Video" + ], + "members": { + "Video": "Video", + "ClientRequestToken": "ClientRequestToken", + "NotificationChannel": "NotificationChannel", + "FaceAttributes": "FaceAttributes", + "JobTag": "JobTag" + } + }, + "StartFaceSearchRequest": { + "type": "structure", + "required": [ + "Video", + "CollectionId" + ], + "members": { + "Video": "Video", + "ClientRequestToken": "ClientRequestToken", + "FaceMatchThreshold": "Percent", + "CollectionId": "CollectionId", + "NotificationChannel": "NotificationChannel", + "JobTag": "JobTag" + } + }, + "StartLabelDetectionRequest": { + "type": "structure", + "required": [ + "Video" + ], + "members": { + "Video": "Video", + "ClientRequestToken": "ClientRequestToken", + "MinConfidence": "Percent", + "NotificationChannel": "NotificationChannel", + "JobTag": "JobTag", + "Features": "LabelDetectionFeatureList", + "Settings": "LabelDetectionSettings" + } + }, + "StartMediaAnalysisJobRequest": { + "type": "structure", + "required": [ + "OperationsConfig", + "Input", + "OutputConfig" + ], + "members": { + "ClientRequestToken": "ClientRequestToken", + "JobName": "MediaAnalysisJobName", + "OperationsConfig": "MediaAnalysisOperationsConfig", + "Input": "MediaAnalysisInput", + "OutputConfig": "MediaAnalysisOutputConfig", + "KmsKeyId": "KmsKeyId" + } + }, + "StartPersonTrackingRequest": { + "type": "structure", + "required": [ + "Video" + ], + "members": { + "Video": "Video", + "ClientRequestToken": "ClientRequestToken", + "NotificationChannel": "NotificationChannel", + "JobTag": "JobTag" + } + }, + "StartProjectVersionRequest": { + "type": "structure", + "required": [ + "ProjectVersionArn", + "MinInferenceUnits" + ], + "members": { + "ProjectVersionArn": "ProjectVersionArn", + "MinInferenceUnits": "InferenceUnits", + "MaxInferenceUnits": "InferenceUnits" + } + }, + "StartSegmentDetectionFilters": { + "type": "structure", + "members": { + "TechnicalCueFilter": "StartTechnicalCueDetectionFilter", + "ShotFilter": "StartShotDetectionFilter" + } + }, + "StartSegmentDetectionRequest": { + "type": "structure", + "required": [ + "Video", + "SegmentTypes" + ], + "members": { + "Video": "Video", + "ClientRequestToken": "ClientRequestToken", + "NotificationChannel": "NotificationChannel", + "JobTag": "JobTag", + "Filters": "StartSegmentDetectionFilters", + "SegmentTypes": "SegmentTypes" + } + }, + "StartShotDetectionFilter": { + "type": "structure", + "members": { + "MinSegmentConfidence": "SegmentConfidence" + } + }, + "StartStreamProcessorRequest": { + "type": "structure", + "required": [ + "Name" + ], + "members": { + "Name": "StreamProcessorName", + "StartSelector": "StreamProcessingStartSelector", + "StopSelector": "StreamProcessingStopSelector" + } + }, + "StartTechnicalCueDetectionFilter": { + "type": "structure", + "members": { + "MinSegmentConfidence": "SegmentConfidence", + "BlackFrame": "BlackFrame" + } + }, + "StartTextDetectionFilters": { + "type": "structure", + "members": { + "WordFilter": "DetectionFilter", + "RegionsOfInterest": "RegionsOfInterest" + } + }, + "StartTextDetectionRequest": { + "type": "structure", + "required": [ + "Video" + ], + "members": { + "Video": "Video", + "ClientRequestToken": "ClientRequestToken", + "NotificationChannel": "NotificationChannel", + "JobTag": "JobTag", + "Filters": "StartTextDetectionFilters" + } + }, + "StopProjectVersionRequest": { + "type": "structure", + "required": [ + "ProjectVersionArn" + ], + "members": { + "ProjectVersionArn": "ProjectVersionArn" + } + }, + "StopStreamProcessorRequest": { + "type": "structure", + "required": [ + "Name" + ], + "members": { + "Name": "StreamProcessorName" + } + }, + "StreamProcessingStartSelector": { + "type": "structure", + "members": { + "KVSStreamStartSelector": "KinesisVideoStreamStartSelector" + } + }, + "StreamProcessingStopSelector": { + "type": "structure", + "members": { + "MaxDurationInSeconds": "MaxDurationInSecondsULong" + } + }, + "StreamProcessorDataSharingPreference": { + "type": "structure", + "required": [ + "OptIn" + ], + "members": { + "OptIn": "Boolean" + } + }, + "StreamProcessorInput": { + "type": "structure", + "members": { + "KinesisVideoStream": "KinesisVideoStream" + } + }, + "StreamProcessorName": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "[a-zA-Z0-9_.\\-]+" + }, + "StreamProcessorNotificationChannel": { + "type": "structure", + "required": [ + "SNSTopicArn" + ], + "members": { + "SNSTopicArn": "SNSTopicArn" + } + }, + "StreamProcessorOutput": { + "type": "structure", + "members": { + "KinesisDataStream": "KinesisDataStream", + "S3Destination": "S3Destination" + } + }, + "StreamProcessorParameterToDelete": { + "type": "string", + "enum": [ + "ConnectedHomeMinConfidence", + "RegionsOfInterest" + ] + }, + "StreamProcessorParametersToDelete": { + "type": "list", + "member": "StreamProcessorParameterToDelete" + }, + "StreamProcessorSettings": { + "type": "structure", + "members": { + "FaceSearch": "FaceSearchSettings", + "ConnectedHome": "ConnectedHomeSettings" + } + }, + "StreamProcessorSettingsForUpdate": { + "type": "structure", + "members": { + "ConnectedHomeForUpdate": "ConnectedHomeSettingsForUpdate" + } + }, + "TagKey": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "^(?!aws:)[\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*$" + }, + "TagKeyList": { + "type": "list", + "min": 0, + "max": 200, + "member": "TagKey" + }, + "TagMap": { + "type": "map", + "min": 0, + "max": 200, + "key": "TagKey", + "value": "TagValue" + }, + "TagResourceRequest": { + "type": "structure", + "required": [ + "ResourceArn", + "Tags" + ], + "members": { + "ResourceArn": "ResourceArn", + "Tags": "TagMap" + } + }, + "TagValue": { + "type": "string", + "min": 0, + "max": 256, + "pattern": "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$" + }, + "TestingData": { + "type": "structure", + "members": { + "Assets": "Assets", + "AutoCreate": "Boolean" + } + }, + "TrainingData": { + "type": "structure", + "members": { + "Assets": "Assets" + } + }, + "UInteger": { + "type": "integer", + "min": 0 + }, + "ULong": { + "type": "long", + "min": 0 + }, + "UntagResourceRequest": { + "type": "structure", + "required": [ + "ResourceArn", + "TagKeys" + ], + "members": { + "ResourceArn": "ResourceArn", + "TagKeys": "TagKeyList" + } + }, + "UpdateDatasetEntriesRequest": { + "type": "structure", + "required": [ + "DatasetArn", + "Changes" + ], + "members": { + "DatasetArn": "DatasetArn", + "Changes": "DatasetChanges" + } + }, + "UpdateStreamProcessorRequest": { + "type": "structure", + "required": [ + "Name" + ], + "members": { + "Name": "StreamProcessorName", + "SettingsForUpdate": "StreamProcessorSettingsForUpdate", + "RegionsOfInterestForUpdate": "RegionsOfInterest", + "DataSharingPreferenceForUpdate": "StreamProcessorDataSharingPreference", + "ParametersToDelete": "StreamProcessorParametersToDelete" + } + }, + "UserFaceIdList": { + "type": "list", + "min": 1, + "max": 100, + "member": "FaceId" + }, + "UserId": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "[a-zA-Z0-9_.\\-:]+" + }, + "Version": { + "type": "string", + "min": 5, + "max": 11, + "pattern": "^(0|[1-9]\\d{0,2})\\.(0|[1-9]\\d{0,2})\\.(0|[1-9]\\d{0,2})$" + }, + "VersionDescription": { + "type": "string", + "min": 1, + "max": 255, + "pattern": "[a-zA-Z0-9-_. ()':,;?]+" + }, + "VersionName": { + "type": "string", + "min": 1, + "max": 255, + "pattern": "[a-zA-Z0-9_.\\-]+" + }, + "VersionNames": { + "type": "list", + "min": 1, + "max": 10, + "member": "VersionName" + }, + "Versions": { + "type": "structure", + "members": { + "Minimum": "Version", + "Maximum": "Version" + } + }, + "Video": { + "type": "structure", + "members": { + "S3Object": "S3Object" + } + } + } +} diff --git a/src/test/java/io/floci/aws/core/common/PartitionCrossServiceSmokeIntegrationTest.java b/src/test/java/io/floci/aws/core/common/PartitionCrossServiceSmokeIntegrationTest.java index 6031de7e44..2f6d7d93a6 100644 --- a/src/test/java/io/floci/aws/core/common/PartitionCrossServiceSmokeIntegrationTest.java +++ b/src/test/java/io/floci/aws/core/common/PartitionCrossServiceSmokeIntegrationTest.java @@ -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) { diff --git a/src/test/java/io/floci/aws/core/common/RequestConstraintCheckTest.java b/src/test/java/io/floci/aws/core/common/RequestConstraintCheckTest.java index 16f84e5366..3277114dd1 100644 --- a/src/test/java/io/floci/aws/core/common/RequestConstraintCheckTest.java +++ b/src/test/java/io/floci/aws/core/common/RequestConstraintCheckTest.java @@ -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: " diff --git a/src/test/java/io/floci/aws/services/rekognition/RekognitionCollectionIntegrationTest.java b/src/test/java/io/floci/aws/services/rekognition/RekognitionCollectionIntegrationTest.java new file mode 100644 index 0000000000..3ce279e667 --- /dev/null +++ b/src/test/java/io/floci/aws/services/rekognition/RekognitionCollectionIntegrationTest.java @@ -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 allIds = new HashSet<>(); + client.listFacesPaginator(r -> r.collectionId(id).maxResults(1)).faces().forEach(f -> assertTrue(allIds.add(f.faceId()))); + assertEquals(3, allIds.size()); + List 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 getConfigOverrides() { + return Map.of("floci.storage.services.rekognition.mode", "persistent", + "floci.storage.persistent-path", STORAGE_PATH); + } + } +} diff --git a/src/test/java/io/floci/aws/services/rekognition/RekognitionCollectionServiceTest.java b/src/test/java/io/floci/aws/services/rekognition/RekognitionCollectionServiceTest.java new file mode 100644 index 0000000000..1f2ce462c4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/rekognition/RekognitionCollectionServiceTest.java @@ -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 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 expected = List.of("alpha", "bravo", "charlie", "delta", "echo", "foxtrot"); + for (String id : expected.reversed()) { + service.createCollection(request().put("CollectionId", id), REGION); + } + List 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 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 untouched = markFiles(path); + ObjectNode indexed = writer.indexFaces(imageRequest(), REGION, "photos/face.jpg"); + for (Map.Entry 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 unchanged = markFiles(path); + assertEquals(indexed, writer.indexFaces(imageRequest(), REGION, "photos/face.jpg")); + for (Map.Entry 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 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 markFiles(Path path) throws Exception { + Map result = new HashMap<>(); + try (Stream 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()); + } +} diff --git a/src/test/java/io/floci/aws/services/rekognition/RekognitionIntegrationTest.java b/src/test/java/io/floci/aws/services/rekognition/RekognitionIntegrationTest.java index 4be446dde7..4d1b310bbf 100644 --- a/src/test/java/io/floci/aws/services/rekognition/RekognitionIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rekognition/RekognitionIntegrationTest.java @@ -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() diff --git a/src/test/java/io/floci/aws/services/rekognition/RekognitionJsonHandlerTest.java b/src/test/java/io/floci/aws/services/rekognition/RekognitionJsonHandlerTest.java new file mode 100644 index 0000000000..d234bd496f --- /dev/null +++ b/src/test/java/io/floci/aws/services/rekognition/RekognitionJsonHandlerTest.java @@ -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 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); + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 52cb37b6b8..f798be4947 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -29,6 +29,8 @@ floci: wal: compaction-interval-ms: 60000 services: + rekognition: + flush-interval-ms: 60000 ssm: flush-interval-ms: 60000 dynamodb: diff --git a/src/test/resources/fixtures/ai-mock-config.json b/src/test/resources/fixtures/ai-mock-config.json index 7ea74ff3dc..f3d02cc9af 100644 --- a/src/test/resources/fixtures/ai-mock-config.json +++ b/src/test/resources/fixtures/ai-mock-config.json @@ -29,6 +29,14 @@ } }, "rekognition": { + "mock-bucket/collection-face.jpg": { + "DetectFaces": { + "FaceDetails": [ + { "Confidence": 99.9, "BoundingBox": { "Width": 0.4, "Height": 0.4, "Left": 0.1, "Top": 0.1 } }, + { "Confidence": 99.5, "BoundingBox": { "Width": 0.1, "Height": 0.1, "Left": 0.6, "Top": 0.6 } } + ] + } + }, "mock-bucket/cat.jpg": { "DetectLabels": { "Labels": [ diff --git a/tools/aws/regen_rekognition_shapes.py b/tools/aws/regen_rekognition_shapes.py new file mode 100644 index 0000000000..79b50d5118 --- /dev/null +++ b/tools/aws/regen_rekognition_shapes.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Vendor every Rekognition operation's request constraints for RequestConstraintCheck.""" +from __future__ import annotations + +from pathlib import Path + +import request_shapes + +MODEL = Path("rekognition/2016-06-27") +OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/rekognition-request-shapes.json" + + +def prepare(model: dict) -> dict: + # Image bytes keep RekognitionImageValidator's decoding, decoded-size checks and aggregated + # ValidationException. The generic request checker validates the remaining image members. + model["shapes"]["Image"]["members"].pop("Bytes") + return model + + +def main(argv: list[str] | None = None) -> int: + return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, + description=__doc__, constraints=True, prepare=prepare) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/aws/test_request_shapes.py b/tools/aws/test_request_shapes.py index e1c7c080b2..39989553ed 100644 --- a/tools/aws/test_request_shapes.py +++ b/tools/aws/test_request_shapes.py @@ -13,6 +13,7 @@ from __future__ import annotations import gzip import json import re +from copy import deepcopy from pathlib import Path import pytest @@ -28,6 +29,7 @@ import regen_iam_shapes import regen_payment_cryptography_shapes import regen_logs_delivery_shapes import regen_resource_groups_shapes +import regen_rekognition_shapes import regen_securityhub_shapes import regen_sesv2_shapes import regen_sts_shapes @@ -254,14 +256,21 @@ CONSTRAINED_MODEL = { } -def test_athena_generator_keeps_constraints_for_every_operation_and_detects_new_operations(tmp_path, monkeypatch): - output = tmp_path / "athena-request-shapes.json" +@pytest.mark.parametrize("script, model_path", [ + (regen_athena_shapes, "athena/2017-05-18"), + (regen_rekognition_shapes, "rekognition/2016-06-27"), +]) +def test_generators_keep_constraints_for_every_operation_and_detect_new_operations(script, model_path, tmp_path, monkeypatch): + output = tmp_path / "request-shapes.json" + model = deepcopy(CONSTRAINED_MODEL) + model["shapes"]["Image"] = {"type": "structure", "members": {"Bytes": {"shape": "Blob"}}} + model["shapes"]["Blob"] = {"type": "blob"} monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "botocore test")) - monkeypatch.setattr(r, "load_model", lambda data, model: CONSTRAINED_MODEL) + monkeypatch.setattr(r, "load_model", lambda data, model_path: deepcopy(model)) args = ["--output", str(output)] - assert regen_athena_shapes.MODEL == Path("athena/2017-05-18") - assert regen_athena_shapes.main(args) == 0 + assert script.MODEL == Path(model_path) + assert script.main(args) == 0 doc = json.loads(output.read_text()) assert doc["operations"] == {"Put": "PutRequest", "Unused": "UnusedRequest"} assert doc["shapes"]["Name"]["min"] == 1 @@ -270,13 +279,13 @@ def test_athena_generator_keeps_constraints_for_every_operation_and_detects_new_ assert doc["shapes"]["Kind"]["enum"] == ["A", "B"] assert doc["shapes"]["RuleList"]["max"] == 25 assert doc["shapes"]["TagMap"]["key"] == "Name" - assert regen_athena_shapes.main(["--check", *args]) == 0 + assert script.main(["--check", *args]) == 0 - changed = {**CONSTRAINED_MODEL, "operations": {**CONSTRAINED_MODEL["operations"], + changed = {**model, "operations": {**model["operations"], "NewOperation": {"input": {"shape": "PutRequest"}}}} - monkeypatch.setattr(r, "load_model", lambda data, model: changed) - assert regen_athena_shapes.main(["--check", *args]) == 1 - assert regen_athena_shapes.main(args) == 0 + monkeypatch.setattr(r, "load_model", lambda data, model_path: deepcopy(changed)) + assert script.main(["--check", *args]) == 1 + assert script.main(args) == 0 assert "NewOperation" in json.loads(output.read_text())["operations"] @@ -401,11 +410,14 @@ def vendored(script) -> tuple[str, ...]: regen_payment_cryptography_shapes, regen_resource_groups_shapes, regen_sts_shapes, regen_securityhub_shapes, + regen_rekognition_shapes, + regen_athena_shapes, ]) def test_each_vendored_constraints_file_carries_its_operations_and_resolves_its_shapes(script): doc = json.loads(script.OUTPUT.read_text(encoding="utf-8")) - assert sorted(doc["operations"]) == sorted(vendored(script)) + if hasattr(script, "OPERATIONS") or hasattr(script, "VENDORED"): + assert sorted(doc["operations"]) == sorted(vendored(script)) for operation, shape in doc["operations"].items(): assert shape in doc["shapes"], operation for name, shape in doc["shapes"].items(): @@ -435,6 +447,23 @@ def test_securityhub_shapes_keep_modelled_findings_and_filter_constraints(): assert "Double" not in shapes +def test_rekognition_shapes_keep_constraints_and_leave_image_bytes_to_the_image_validator(): + doc = json.loads(regen_rekognition_shapes.OUTPUT.read_text(encoding="utf-8")) + shapes = doc["shapes"] + + assert shapes["IndexFacesRequest"]["required"] == ["CollectionId", "Image"] + assert shapes["PageSize"]["min"] == 0 + assert shapes["PageSize"]["max"] == 4096 + assert shapes["Percent"] == {"type": "float", "min": 0, "max": 100} + assert shapes["Attributes"]["member"] == "Attribute" + assert "FACE_OCCLUDED" in shapes["Attribute"]["enum"] + assert shapes["TagKey"]["pattern"].startswith("^(?!aws:)") + assert shapes["FaceIdList"]["max"] == 4096 + assert shapes["MaxFacesToIndex"] == {"type": "integer", "min": 1} + assert shapes["Image"]["members"] == {"S3Object": "S3Object"} + assert "ImageBlob" not in shapes + + def test_securityhub_shapes_keep_required_findings_and_resource_strings(): doc = json.loads(regen_securityhub_shapes.OUTPUT.read_text(encoding="utf-8")) shapes = doc["shapes"]