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

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

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

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

No files matched your search

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