mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cloudfront): add CloudFront KeyValueStore support (#8108)
This commit is contained in:
1 parent
2beb3b6c0d
commit
9831603f67
25 files changed
+2021
-17
No files matched your search
@@ -35,6 +35,8 @@
|
||||
# src/main/resources/aws/payment-cryptography-data-request-shapes.json, the Payment Cryptography
|
||||
# data plane request constraints, is generated from botocore's data plane model by
|
||||
# tools/aws/regen_payment_cryptography_data_shapes.py.
|
||||
# src/main/resources/aws/cloudfront-keyvaluestore-request-shapes.json, the CloudFront KeyValueStore data plane
|
||||
# request constraints, is generated from botocore's model by tools/aws/regen_cloudfront_keyvaluestore_shapes.py.
|
||||
# src/main/resources/aws/rds-ca-certificates.json, each Region's RDS certificate authorities, is
|
||||
# generated from the certificate bundles AWS publishes by tools/aws/regen_rds_ca_certificates.py.
|
||||
# src/main/resources/aws/iam-request-shapes.json, the IAM request constraints of the operations
|
||||
@@ -289,6 +291,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s
|
||||
$(PYTHON) tools/aws/regen_cur_shapes.py
|
||||
$(PYTHON) tools/aws/regen_payment_cryptography_shapes.py
|
||||
$(PYTHON) tools/aws/regen_payment_cryptography_data_shapes.py
|
||||
$(PYTHON) tools/aws/regen_cloudfront_keyvaluestore_shapes.py
|
||||
$(PYTHON) tools/aws/regen_securityhub_shapes.py
|
||||
$(PYTHON) tools/aws/regen_rekognition_shapes.py
|
||||
$(PYTHON) tools/aws/regen_kinesis_shapes.py
|
||||
@@ -405,6 +408,12 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres
|
||||
echo " Run 'make aws-data-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_cloudfront_keyvaluestore_shapes.py --check || { \
|
||||
echo ""; \
|
||||
echo "error: src/main/resources/aws/cloudfront-keyvaluestore-request-shapes.json is out of date."; \
|
||||
echo " Run 'make aws-data-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_securityhub_shapes.py --check || { \
|
||||
echo "error: Security Hub request shapes are out of date; run 'make aws-data-sync'."; \
|
||||
exit 1; \
|
||||
|
||||
@@ -389,7 +389,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
|
||||
| AWS Config | In-process | Config rules, evaluation-driven compliance (PutEvaluations, compliance details and summaries), configuration recorders, delivery channels, retention configuration, conformance packs, tagging |
|
||||
| Organizations | In-process | Organizations, roots, nested OUs, member accounts, all policy types with `FullAWSAccess` and effective-policy inheritance, trusted service access, delegated administrators, resource policy, and the full invitation/handshake flow; created accounts are usable Floci accounts and member accounts can read the organization they belong to |
|
||||
| CloudTrail | In-process | Trails, event selectors (S3 data events with bucket/prefix matching), `StartLogging`/`StopLogging`, scheduled gzipped log file emission to the destination bucket at AWS-shaped key paths, IAM-deny path emits `AccessDenied` records |
|
||||
| CloudFront | In-process | Distributions, origins, cache behaviors, invalidations, tagging |
|
||||
| CloudFront | In-process | Distributions, origins, cache behaviors, invalidations, functions, key value stores, tagging |
|
||||
| WAF v2 | In-process | Web ACLs, IP sets, regex pattern sets, rule groups, logging configs, resource associations, tagging (REGIONAL and CLOUDFRONT scopes) |
|
||||
| AWS Resource Groups | In-process | Five capacity-pool operations: stored groups, verified EC2 reservation membership, scoped pagination and group deletion; no dynamic queries or capacity allocation |
|
||||
| Resource Explorer 2 | In-process | All 32 management APIs: index and view lifecycle, multi-Region setup tasks, the full search query grammar, and tagging; 30 services expose their resources for search, gathered live rather than from an index |
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
CloudFront management-plane and local content-delivery emulation. Supports distribution lifecycle,
|
||||
cache policies, origin request policies, response headers policies, origin access controls, origin
|
||||
access identities, public keys, trusted key groups, CloudFront Functions, invalidations, tagging, and
|
||||
viewer delivery from S3 or custom origins for every CloudFront viewer method (GET, HEAD, OPTIONS, POST,
|
||||
PUT, PATCH and DELETE).
|
||||
access identities, public keys, trusted key groups, CloudFront Functions, key value stores, invalidations,
|
||||
tagging, and viewer delivery from S3 or custom origins for every CloudFront viewer method (GET, HEAD,
|
||||
OPTIONS, POST, PUT, PATCH and DELETE).
|
||||
|
||||
**Protocol:** REST XML
|
||||
**API version:** `2020-05-31`
|
||||
@@ -102,6 +102,31 @@ PUT, PATCH and DELETE).
|
||||
| `DeleteFunction` | DELETE | `/2020-05-31/function/{Name}` |
|
||||
| `ListFunctions` | GET | `/2020-05-31/function` |
|
||||
|
||||
### Key Value Stores
|
||||
|
||||
Control plane, served with the rest of CloudFront:
|
||||
|
||||
| Operation | Method | Path |
|
||||
|---|---|---|
|
||||
| `CreateKeyValueStore` | POST | `/2020-05-31/key-value-store` |
|
||||
| `DescribeKeyValueStore` | GET | `/2020-05-31/key-value-store/{Name}` |
|
||||
| `ListKeyValueStores` | GET | `/2020-05-31/key-value-store` |
|
||||
| `UpdateKeyValueStore` | PUT | `/2020-05-31/key-value-store/{Name}` |
|
||||
| `DeleteKeyValueStore` | DELETE | `/2020-05-31/key-value-store/{Name}` |
|
||||
|
||||
The keys of a store are read and written through the separate `cloudfront-keyvaluestore` data plane
|
||||
(REST JSON, signing name `cloudfront-keyvaluestore`). It names the store by its ARN, percent-encoded in
|
||||
the path:
|
||||
|
||||
| Operation | Method | Path |
|
||||
|---|---|---|
|
||||
| `DescribeKeyValueStore` | GET | `/key-value-stores/{KvsARN}` |
|
||||
| `ListKeys` | GET | `/key-value-stores/{KvsARN}/keys` |
|
||||
| `UpdateKeys` | POST | `/key-value-stores/{KvsARN}/keys` |
|
||||
| `GetKey` | GET | `/key-value-stores/{KvsARN}/keys/{Key}` |
|
||||
| `PutKey` | PUT | `/key-value-stores/{KvsARN}/keys/{Key}` |
|
||||
| `DeleteKey` | DELETE | `/key-value-stores/{KvsARN}/keys/{Key}` |
|
||||
|
||||
### Public Keys and Key Groups
|
||||
|
||||
| Operation | Method | Path |
|
||||
@@ -375,6 +400,43 @@ PUT, PATCH and DELETE).
|
||||
`ListResponseHeadersPolicies?Type=managed`; `Type` uses the AWS lowercase `managed` or `custom`
|
||||
values.
|
||||
|
||||
## Key Value Stores
|
||||
|
||||
A key value store holds the key value pairs a CloudFront Function reads at the edge. The store is created
|
||||
and described through the CloudFront control plane, and its keys are managed through the
|
||||
`cloudfront-keyvaluestore` data plane, which Floci serves on the same port.
|
||||
|
||||
- A store has a name (1 to 64 letters, digits, hyphens and underscores) and an ARN,
|
||||
`arn:aws:cloudfront::<account>:key-value-store/<uuid>`. Stores are `READY` as soon as they are created.
|
||||
- The data plane takes the store's ARN in the request path, percent-encoded. The AWS SDKs prepend the
|
||||
account id of that ARN to the endpoint host (`000000000000.localhost.floci.io`), which the embedded DNS
|
||||
and the generated TLS certificate already cover. The requests are signed with SigV4A; Floci reads the
|
||||
`cloudfront-keyvaluestore` signing name from its credential scope and does not verify the signature.
|
||||
With `floci.auth.validate-signatures` on, these requests are refused: signature validation does not accept
|
||||
SigV4A outside S3 yet, so leave it off when using the data plane.
|
||||
- With IAM enforcement on, the data plane is authorized as `cloudfront-keyvaluestore:<Operation>` on the store's ARN,
|
||||
and the control plane as `cloudfront:<Operation>`.
|
||||
- Keys are listed in key order, 10 per page by default and up to 50 (`MaxResults`).
|
||||
- Quotas: a key is at most 512 bytes, a value at most 1,024 bytes and a store at most 5 MiB, counting the
|
||||
UTF-8 bytes of every key and value. Exceeding the first two is a `ValidationException`, and exceeding the
|
||||
store size is a `ServiceQuotaExceededException`. `ItemCount` and `TotalSizeInBytes` follow the same count.
|
||||
- Every key write needs the store's current data plane ETag in `If-Match`, and rotates it. `UpdateKeys`
|
||||
applies its puts and deletes together (at most 50 entries and 3 MB per request), and changes nothing when any
|
||||
entry is invalid, including a put without a `Value`. A stale or missing ETag on the
|
||||
data plane is a `ValidationException` ("Pre-Condition failed during update of Key-Value-Store"), and on the
|
||||
control plane an `InvalidIfMatchVersion`.
|
||||
- The control plane and the data plane keep independent ETags: a comment update rotates only the control plane
|
||||
ETag, and a key write only the data plane ETag.
|
||||
- An account can hold at most 200 stores (`EntityLimitExceeded`), and a store can be associated with at most 100
|
||||
functions (`TooManyFunctionsAssociatedToKeyValueStore`). Deleting a store also drops its tags.
|
||||
- Deleting a key that is not in the store is a `ResourceNotFoundException`. In `UpdateKeys` the delete of an
|
||||
absent key is skipped.
|
||||
- A function can name at most one store in `FunctionConfig.KeyValueStoreAssociations`, and only with the
|
||||
`cloudfront-js-2.0` runtime. The store has to exist (`EntityNotFound`), and a store that a function
|
||||
uses cannot be deleted (`CannotDeleteEntityWhileInUse`).
|
||||
- Floci does not run CloudFront Functions. A function that reads the store with `cf.kvs()` is stored and
|
||||
associated, but nothing executes it, so the store is useful for testing the code that writes it.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Property | Env var | Default | Description |
|
||||
@@ -561,7 +623,13 @@ signatures must still return 403. Verify those cases through the proxy after con
|
||||
- Field-level encryption (`CreateFieldLevelEncryptionConfig`, etc.)
|
||||
- `TestFunction` execution (function is stored, not executed)
|
||||
- Streaming distributions (RTMP — deprecated by AWS)
|
||||
- VPC origins, Anycast IP lists, key value stores
|
||||
- VPC origins, Anycast IP lists
|
||||
- Importing keys into a key value store from S3: `CreateKeyValueStore` with an `ImportSource` is rejected with
|
||||
`InvalidArgument`
|
||||
- Running CloudFront Functions, so the key value store can only be read and written through its API, not
|
||||
from a function with `cf.kvs()`
|
||||
- CloudFormation provisioning of `AWS::CloudFront::KeyValueStore`, and `KeyValueStoreAssociations` on
|
||||
`AWS::CloudFront::Function`
|
||||
- Monitoring subscriptions
|
||||
- CloudFormation provisioning of custom `AWS::CloudFront::ResponseHeadersPolicy` resources
|
||||
(literal custom or managed policy IDs are supported on distributions)
|
||||
|
||||
@@ -132,7 +132,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [AWS FIS](fis.md) | `/experimentTemplates/*`, `/experiments/*`, `/actions/*`, `/targetResourceTypes/*`, `/safetyLevers/*`, `/tags/*` | REST JSON | 26 |
|
||||
| [CodeGuru Reviewer](codegurureviewer.md) | `/associations`, `/associations/{associationArn}`, `/tags/*` | REST JSON | 7 |
|
||||
| [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package`, `/v1/package/version*`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*`, `/codeartifact/npm/*`, `/codeartifact/pypi/*` | REST JSON | 37 |
|
||||
| [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*` | REST XML | 50 |
|
||||
| [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*`, `/2020-05-31/key-value-store/*`, `/key-value-stores/*` | REST XML, REST JSON | 61 |
|
||||
| [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*`, `/2013-04-01/delegationset/*` | REST XML | 31 |
|
||||
| [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 22 |
|
||||
| [Amazon SageMaker](sagemaker.md) | `POST /` + `X-Amz-Target: SageMaker.*` | JSON 1.1 | 20 |
|
||||
|
||||
@@ -26,6 +26,7 @@ import io.floci.aws.services.bedrockagentcorecontrol.BedrockAgentCoreResourcePol
|
||||
import io.floci.aws.services.bedrockagentcorecontrol.BedrockAgentCoreToolsController;
|
||||
import io.floci.aws.services.bedrockruntime.BedrockRuntimeController;
|
||||
import io.floci.aws.services.cloudfront.CloudFrontController;
|
||||
import io.floci.aws.services.cloudfront.CloudFrontKeyValueStoreController;
|
||||
import io.floci.aws.services.cloudfront.CloudFrontServingController;
|
||||
import io.floci.aws.services.cloudwatch.metrics.OtlpMetricsController;
|
||||
import io.floci.aws.services.codeartifact.CodeArtifactController;
|
||||
@@ -716,6 +717,12 @@ public class ResolvedServiceCatalog {
|
||||
protocols(ServiceProtocol.REST_XML),
|
||||
Set.of(), Set.of("cloudfront"), Set.of(),
|
||||
Set.of(CloudFrontController.class, CloudFrontServingController.class)),
|
||||
descriptor("cloudfront-keyvaluestore", "cloudfront-keyvaluestore",
|
||||
config.services().cloudfront().enabled(), true,
|
||||
null, null, 5000L, null, ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON),
|
||||
Set.of(), Set.of("cloudfront-keyvaluestore"), Set.of(),
|
||||
Set.of(CloudFrontKeyValueStoreController.class)),
|
||||
descriptor("appsync", "appsync", config.services().appsync().enabled(), true,
|
||||
"appsync", storageMode(config.storage().services().appsync().mode(), config.storage().mode()),
|
||||
config.storage().services().appsync().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
|
||||
|
||||
@@ -981,8 +981,9 @@ public class CloudFrontController {
|
||||
.elem("Status", fn.getStatus())
|
||||
.start("FunctionConfig")
|
||||
.elem("Comment", fn.getComment() != null ? fn.getComment() : "")
|
||||
.elem("Runtime", fn.getRuntime() != null ? fn.getRuntime() : "cloudfront-js-2.0")
|
||||
.end("FunctionConfig")
|
||||
.elem("Runtime", fn.getRuntime() != null ? fn.getRuntime() : "cloudfront-js-2.0");
|
||||
appendKeyValueStoreAssociations(xml, fn);
|
||||
xml.end("FunctionConfig")
|
||||
.start("FunctionMetadata")
|
||||
.elem("FunctionARN", service.arn("function/" + fn.getName()))
|
||||
.elem("Stage", fn.getStage())
|
||||
@@ -999,6 +1000,95 @@ public class CloudFrontController {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Key Value Stores ──────────────────────────────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/key-value-store")
|
||||
public Response createKeyValueStore(String body) {
|
||||
try {
|
||||
String name = XmlParser.extractFirst(body, "Name", null);
|
||||
String comment = XmlParser.extractFirst(body, "Comment", null);
|
||||
boolean hasImportSource = XmlParser.extractElementTree(body, "ImportSource") != null;
|
||||
KeyValueStore kvs = service.createKeyValueStore(name, comment, hasImportSource);
|
||||
Map<String, String> tags = parseTags(body);
|
||||
if (!tags.isEmpty()) {
|
||||
service.tagResource(kvs.getArn(), tags);
|
||||
}
|
||||
return Response.created(URI.create("/2020-05-31/key-value-store/" + kvs.getName()))
|
||||
.type(XML)
|
||||
.header("ETag", kvs.getEtag())
|
||||
.entity(xmlKeyValueStore(kvs))
|
||||
.build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/key-value-store/{Name}")
|
||||
public Response describeKeyValueStore(@PathParam("Name") String name) {
|
||||
try {
|
||||
KeyValueStore kvs = service.describeKeyValueStore(name);
|
||||
return Response.ok(xmlKeyValueStore(kvs), XML)
|
||||
.header("ETag", kvs.getEtag())
|
||||
.build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/key-value-store")
|
||||
public Response listKeyValueStores(@QueryParam("Marker") String marker,
|
||||
@QueryParam("Status") String status,
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
Page<KeyValueStore> page = page(
|
||||
service.listKeyValueStores(marker, paginationFetchLimit(maxItems), status),
|
||||
maxItems, KeyValueStore::getName);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("KeyValueStoreList", NS)
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("Quantity", page.items().size())
|
||||
.start("Items");
|
||||
for (KeyValueStore kvs : page.items()) {
|
||||
appendKeyValueStoreFields(xml.start("KeyValueStore"), kvs).end("KeyValueStore");
|
||||
}
|
||||
xml.end("Items").end("KeyValueStoreList");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/key-value-store/{Name}")
|
||||
public Response updateKeyValueStore(@PathParam("Name") String name,
|
||||
@HeaderParam("If-Match") String ifMatch,
|
||||
String body) {
|
||||
try {
|
||||
KeyValueStore kvs = service.updateKeyValueStore(name, ifMatch, XmlParser.extractFirst(body, "Comment", null));
|
||||
return Response.ok(xmlKeyValueStore(kvs), XML)
|
||||
.header("ETag", kvs.getEtag())
|
||||
.build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/key-value-store/{Name}")
|
||||
public Response deleteKeyValueStore(@PathParam("Name") String name,
|
||||
@HeaderParam("If-Match") String ifMatch) {
|
||||
try {
|
||||
service.deleteKeyValueStore(name, ifMatch);
|
||||
return Response.noContent().build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Tagging ───────────────────────────────────────────────────────────────
|
||||
|
||||
@GET
|
||||
@@ -2433,14 +2523,15 @@ public class CloudFrontController {
|
||||
}
|
||||
|
||||
private String xmlFunctionResponse(CloudFrontFunction fn) {
|
||||
return new XmlBuilder()
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("FunctionSummary")
|
||||
.elem("Name", fn.getName())
|
||||
.elem("Status", fn.getStatus())
|
||||
.start("FunctionConfig")
|
||||
.elem("Comment", fn.getComment() != null ? fn.getComment() : "")
|
||||
.elem("Runtime", fn.getRuntime() != null ? fn.getRuntime() : "cloudfront-js-2.0")
|
||||
.end("FunctionConfig")
|
||||
.elem("Runtime", fn.getRuntime() != null ? fn.getRuntime() : "cloudfront-js-2.0");
|
||||
appendKeyValueStoreAssociations(xml, fn);
|
||||
return xml.end("FunctionConfig")
|
||||
.start("FunctionMetadata")
|
||||
.elem("FunctionARN", service.arn("function/" + fn.getName()))
|
||||
.elem("Stage", fn.getStage())
|
||||
@@ -2452,6 +2543,34 @@ public class CloudFrontController {
|
||||
.build();
|
||||
}
|
||||
|
||||
private static void appendKeyValueStoreAssociations(XmlBuilder xml, CloudFrontFunction fn) {
|
||||
List<String> arns = fn.getKeyValueStoreArns();
|
||||
if (arns == null || arns.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
xml.start("KeyValueStoreAssociations").elem("Quantity", arns.size()).start("Items");
|
||||
for (String arn : arns) {
|
||||
xml.start("KeyValueStoreAssociation").elem("KeyValueStoreARN", arn).end("KeyValueStoreAssociation");
|
||||
}
|
||||
xml.end("Items").end("KeyValueStoreAssociations");
|
||||
}
|
||||
|
||||
private String xmlKeyValueStore(KeyValueStore kvs) {
|
||||
return appendKeyValueStoreFields(new XmlBuilder().start("KeyValueStore", NS), kvs)
|
||||
.end("KeyValueStore")
|
||||
.build();
|
||||
}
|
||||
|
||||
private static XmlBuilder appendKeyValueStoreFields(XmlBuilder xml, KeyValueStore kvs) {
|
||||
return xml.elem("Name", kvs.getName())
|
||||
.elem("Id", kvs.getId())
|
||||
.elem("Comment", kvs.getComment() != null ? kvs.getComment() : "")
|
||||
.elem("ARN", kvs.getArn())
|
||||
.elem("Status", kvs.getStatus())
|
||||
.elem("LastModifiedTime",
|
||||
kvs.getLastModifiedTime() != null ? kvs.getLastModifiedTime().toString() : "");
|
||||
}
|
||||
|
||||
/** Renders a possibly-null value as a string, using the empty string for {@code null}. */
|
||||
private static String str(Object value) {
|
||||
return value != null ? value.toString() : "";
|
||||
@@ -3598,6 +3717,7 @@ public class CloudFrontController {
|
||||
fn.setComment(XmlParser.extractFirst(body, "Comment", null));
|
||||
fn.setRuntime(XmlParser.extractFirst(body, "Runtime", "cloudfront-js-2.0"));
|
||||
fn.setFunctionCode(XmlParser.extractFirst(body, "FunctionCode", null));
|
||||
fn.setKeyValueStoreArns(new ArrayList<>(XmlParser.extractAll(body, "KeyValueStoreARN")));
|
||||
return fn;
|
||||
}
|
||||
|
||||
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
package io.floci.aws.services.cloudfront;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
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.AwsErrorResponse;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.Pagination;
|
||||
import io.floci.aws.services.cloudfront.model.KeyValueStore;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.DELETE;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.PUT;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The {@code cloudfront-keyvaluestore} data plane: reads and writes the keys of a key value store
|
||||
* that was created through the CloudFront control plane. Requests name the store by its ARN in the path.
|
||||
*/
|
||||
@Path("/key-value-stores")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.WILDCARD)
|
||||
public class CloudFrontKeyValueStoreController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudFrontKeyValueStoreController.class);
|
||||
|
||||
private static final String ETAG = "ETag";
|
||||
private static final String KVS_ARN = "KvsARN";
|
||||
private static final String KEY = "Key";
|
||||
private static final String VALUE = "Value";
|
||||
private static final String ITEM_COUNT = "ItemCount";
|
||||
private static final String TOTAL_SIZE_IN_BYTES = "TotalSizeInBytes";
|
||||
|
||||
private final CloudFrontKeyValueStoreService service;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public CloudFrontKeyValueStoreController(CloudFrontKeyValueStoreService service, ObjectMapper objectMapper) {
|
||||
this.service = service;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/{kvsArn}")
|
||||
public Response describeKeyValueStore(@PathParam("kvsArn") String kvsArn) {
|
||||
return handle(() -> {
|
||||
ObjectNode request = objectMapper.createObjectNode().put(KVS_ARN, kvsArn);
|
||||
CloudFrontKeyValueStoreRequestShapes.check("DescribeKeyValueStore", request);
|
||||
KeyValueStore kvs = service.describeByArn(kvsArn);
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put(ITEM_COUNT, CloudFrontKeyValueStoreService.itemCount(kvs));
|
||||
body.put(TOTAL_SIZE_IN_BYTES, CloudFrontKeyValueStoreService.totalSizeInBytes(kvs));
|
||||
body.put("KvsARN", kvs.getArn());
|
||||
body.put("Created", epochSeconds(kvs.getCreated()));
|
||||
body.put("LastModified", epochSeconds(kvs.getLastModifiedTime()));
|
||||
body.put("Status", kvs.getStatus());
|
||||
return Response.ok(body).header(ETAG, kvs.getDataEtag()).build();
|
||||
});
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/{kvsArn}/keys")
|
||||
public Response listKeys(@PathParam("kvsArn") String kvsArn,
|
||||
@QueryParam("NextToken") String nextToken,
|
||||
@QueryParam("MaxResults") String maxResults) {
|
||||
return handle(() -> {
|
||||
Integer pageSize = Pagination.parseMaxResults(maxResults, "ValidationException");
|
||||
ObjectNode request = objectMapper.createObjectNode().put(KVS_ARN, kvsArn);
|
||||
if (nextToken != null) {
|
||||
request.put("NextToken", nextToken);
|
||||
}
|
||||
if (pageSize != null) {
|
||||
request.put("MaxResults", pageSize);
|
||||
}
|
||||
CloudFrontKeyValueStoreRequestShapes.check("ListKeys", request);
|
||||
CloudFrontKeyValueStoreService.KeyPage page = service.listKeys(kvsArn, nextToken, pageSize);
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
ArrayNode items = body.putArray("Items");
|
||||
for (Map.Entry<String, String> entry : page.items()) {
|
||||
items.addObject().put(KEY, entry.getKey()).put(VALUE, entry.getValue());
|
||||
}
|
||||
if (page.nextToken() != null) {
|
||||
body.put("NextToken", page.nextToken());
|
||||
}
|
||||
return Response.ok(body).build();
|
||||
});
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/{kvsArn}/keys")
|
||||
public Response updateKeys(@PathParam("kvsArn") String kvsArn,
|
||||
@HeaderParam("If-Match") String ifMatch,
|
||||
String requestBody) {
|
||||
return handle(() -> {
|
||||
if (requestBody != null && requestBody.getBytes(StandardCharsets.UTF_8).length
|
||||
> CloudFrontKeyValueStoreService.MAX_UPDATE_PAYLOAD_BYTES) {
|
||||
throw new AwsException("ValidationException", "The request payload is too large.", 400);
|
||||
}
|
||||
ObjectNode request = operationRequest(requestBody, kvsArn, null, ifMatch);
|
||||
CloudFrontKeyValueStoreRequestShapes.check("UpdateKeys", request);
|
||||
if (request.path("Puts").size() + request.path("Deletes").size()
|
||||
> CloudFrontKeyValueStoreService.MAX_KEY_UPDATES) {
|
||||
throw new AwsException("ValidationException",
|
||||
"At most " + CloudFrontKeyValueStoreService.MAX_KEY_UPDATES
|
||||
+ " keys can be updated in one request.", 400);
|
||||
}
|
||||
Map<String, String> puts = new LinkedHashMap<>();
|
||||
for (JsonNode put : request.path("Puts")) {
|
||||
puts.put(put.get(KEY).textValue(), put.get(VALUE).textValue());
|
||||
}
|
||||
List<String> deletes = new ArrayList<>();
|
||||
for (JsonNode delete : request.path("Deletes")) {
|
||||
deletes.add(delete.get(KEY).textValue());
|
||||
}
|
||||
return sizeResponse(service.updateKeys(kvsArn, ifMatch, puts, deletes));
|
||||
});
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/{kvsArn}/keys/{key}")
|
||||
public Response getKey(@PathParam("kvsArn") String kvsArn, @PathParam("key") String key) {
|
||||
return handle(() -> {
|
||||
ObjectNode request = objectMapper.createObjectNode().put(KVS_ARN, kvsArn).put(KEY, key);
|
||||
CloudFrontKeyValueStoreRequestShapes.check("GetKey", request);
|
||||
CloudFrontKeyValueStoreService.KeyLookup lookup = service.getKey(kvsArn, key);
|
||||
KeyValueStore kvs = lookup.store();
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put(KEY, lookup.key());
|
||||
body.put(VALUE, lookup.value());
|
||||
body.put(ITEM_COUNT, CloudFrontKeyValueStoreService.itemCount(kvs));
|
||||
body.put(TOTAL_SIZE_IN_BYTES, CloudFrontKeyValueStoreService.totalSizeInBytes(kvs));
|
||||
return Response.ok(body).build();
|
||||
});
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/{kvsArn}/keys/{key}")
|
||||
public Response putKey(@PathParam("kvsArn") String kvsArn,
|
||||
@PathParam("key") String key,
|
||||
@HeaderParam("If-Match") String ifMatch,
|
||||
String requestBody) {
|
||||
return handle(() -> {
|
||||
ObjectNode request = operationRequest(requestBody, kvsArn, key, ifMatch);
|
||||
CloudFrontKeyValueStoreRequestShapes.check("PutKey", request);
|
||||
return sizeResponse(service.putKey(kvsArn, ifMatch, key, request.get(VALUE).textValue()));
|
||||
});
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/{kvsArn}/keys/{key}")
|
||||
public Response deleteKey(@PathParam("kvsArn") String kvsArn,
|
||||
@PathParam("key") String key,
|
||||
@HeaderParam("If-Match") String ifMatch) {
|
||||
return handle(() -> {
|
||||
ObjectNode request = operationRequest(null, kvsArn, key, ifMatch);
|
||||
CloudFrontKeyValueStoreRequestShapes.check("DeleteKey", request);
|
||||
return sizeResponse(service.deleteKey(kvsArn, ifMatch, key));
|
||||
});
|
||||
}
|
||||
|
||||
private Response sizeResponse(KeyValueStore kvs) {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put(ITEM_COUNT, CloudFrontKeyValueStoreService.itemCount(kvs));
|
||||
body.put(TOTAL_SIZE_IN_BYTES, CloudFrontKeyValueStoreService.totalSizeInBytes(kvs));
|
||||
return Response.ok(body).header(ETAG, kvs.getDataEtag()).build();
|
||||
}
|
||||
|
||||
private ObjectNode readBody(String requestBody) {
|
||||
try {
|
||||
JsonNode body = requestBody == null || requestBody.isBlank()
|
||||
? objectMapper.createObjectNode()
|
||||
: objectMapper.readTree(requestBody);
|
||||
if (!body.isObject()) {
|
||||
throw new AwsException("ValidationException", "The request body must be a JSON object.", 400);
|
||||
}
|
||||
return (ObjectNode) body;
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AwsException("ValidationException", "Malformed JSON request body.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The request as the model reads it: the members of the body, then those the path and the {@code If-Match}
|
||||
* header carry, which a body cannot override.
|
||||
*/
|
||||
private ObjectNode operationRequest(String requestBody, String kvsArn, String key, String ifMatch) {
|
||||
ObjectNode request = readBody(requestBody).deepCopy();
|
||||
request.remove("IfMatch");
|
||||
request.put(KVS_ARN, kvsArn);
|
||||
if (key != null) {
|
||||
request.put(KEY, key);
|
||||
}
|
||||
if (ifMatch != null) {
|
||||
request.put("IfMatch", ifMatch);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
private static BigDecimal epochSeconds(Instant instant) {
|
||||
return BigDecimal.valueOf(instant == null ? 0 : instant.toEpochMilli(), 3);
|
||||
}
|
||||
|
||||
private Response handle(Handler handler) {
|
||||
try {
|
||||
return handler.handle();
|
||||
} catch (AwsException e) {
|
||||
return error(e.getHttpStatus(), e.getErrorCode(), e.getMessage());
|
||||
} catch (RuntimeException e) {
|
||||
LOG.error("Error processing CloudFront key value store request", e);
|
||||
return error(500, "InternalServerException", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static Response error(int status, String code, String message) {
|
||||
return Response.status(status)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.header("X-Amzn-Errortype", code)
|
||||
.entity(new AwsErrorResponse(code, message))
|
||||
.build();
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface Handler {
|
||||
Response handle();
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package io.floci.aws.services.cloudfront;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.aws.core.common.RequestConstraintCheck;
|
||||
|
||||
/**
|
||||
* Checks a {@code cloudfront-keyvaluestore} request against the constraints vendored in
|
||||
* {@code aws/cloudfront-keyvaluestore-request-shapes.json} by
|
||||
* {@code tools/aws/regen_cloudfront_keyvaluestore_shapes.py}. The request is the members the path, the
|
||||
* {@code If-Match} header, the query and the body carry, under the names the model gives them. A violation is a
|
||||
* {@code ValidationException}.
|
||||
*/
|
||||
final class CloudFrontKeyValueStoreRequestShapes {
|
||||
|
||||
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load(
|
||||
"aws/cloudfront-keyvaluestore-request-shapes.json",
|
||||
"CloudFront KeyValueStore request shapes",
|
||||
RequestConstraintCheck.standardMessages("ValidationException"));
|
||||
|
||||
private CloudFrontKeyValueStoreRequestShapes() {
|
||||
}
|
||||
|
||||
static void check(String operation, JsonNode request) {
|
||||
CHECK.check(operation, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
package io.floci.aws.services.cloudfront;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
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.StoredResourceArns;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.cloudfront.model.KeyValueStore;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* CloudFront key value stores. The stores are created and described through the CloudFront
|
||||
* control plane, and their keys are read and written through the separate
|
||||
* {@code cloudfront-keyvaluestore} data plane. Both planes share this service but keep an independent
|
||||
* ETag per store: a control plane update rotates only the control plane ETag, and a key write only the
|
||||
* data plane ETag.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CloudFrontKeyValueStoreService implements StoredResourceArns {
|
||||
|
||||
static final int MAX_KEY_BYTES = 512;
|
||||
static final int MAX_VALUE_BYTES = 1024;
|
||||
static final long MAX_STORE_BYTES = 5L * 1024 * 1024;
|
||||
static final int DEFAULT_LIST_KEYS = 10;
|
||||
static final int MAX_LIST_KEYS = 50;
|
||||
static final int MAX_KEY_UPDATES = 50;
|
||||
static final int MAX_UPDATE_PAYLOAD_BYTES = 3 * 1024 * 1024;
|
||||
static final int MAX_STORES = 200;
|
||||
|
||||
private static final Pattern STORE_NAME = Pattern.compile("[a-zA-Z0-9_-]{1,64}");
|
||||
private static final int MAX_COMMENT_LENGTH = 128;
|
||||
private static final String STATUS_READY = "READY";
|
||||
|
||||
private final StorageBackend<String, KeyValueStore> store;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public CloudFrontKeyValueStoreService(StorageFactory factory, RegionResolver regionResolver) {
|
||||
this.store = factory.create("cloudfront", "cloudfront-key-value-stores.json",
|
||||
new TypeReference<Map<String, KeyValueStore>>() {});
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
// ── Control plane ─────────────────────────────────────────────────────────
|
||||
|
||||
public synchronized KeyValueStore create(String name, String comment) {
|
||||
validateName(name);
|
||||
String effectiveComment = comment == null ? "" : comment;
|
||||
validateComment(effectiveComment);
|
||||
if (store.get(name).isPresent()) {
|
||||
throw new AwsException("EntityAlreadyExists", "The Key Value Store already exists.", 409);
|
||||
}
|
||||
if (store.scan(key -> true).size() >= MAX_STORES) {
|
||||
throw new AwsException("EntityLimitExceeded",
|
||||
"The maximum number of Key Value Stores for this account has been reached.", 400);
|
||||
}
|
||||
Instant now = Instant.now();
|
||||
KeyValueStore created = new KeyValueStore();
|
||||
created.setName(name);
|
||||
created.setId(UUID.randomUUID().toString());
|
||||
created.setComment(effectiveComment);
|
||||
created.setArn(regionResolver.buildGlobalArn("cloudfront", "key-value-store/" + created.getId()));
|
||||
created.setStatus(STATUS_READY);
|
||||
created.setEtag(newEtag());
|
||||
created.setDataEtag(newEtag());
|
||||
created.setCreated(now);
|
||||
created.setLastModifiedTime(now);
|
||||
store.put(name, created);
|
||||
return created;
|
||||
}
|
||||
|
||||
public KeyValueStore describe(String name) {
|
||||
return store.get(name).orElseThrow(() ->
|
||||
new AwsException("EntityNotFound", "The specified KeyValueStore does not exist.", 404));
|
||||
}
|
||||
|
||||
public List<KeyValueStore> list(String marker, int maxItems, String status) {
|
||||
List<KeyValueStore> all = new ArrayList<>(store.scan(key -> true));
|
||||
if (status != null && !status.isEmpty()) {
|
||||
all.removeIf(kvs -> !status.equals(kvs.getStatus()));
|
||||
}
|
||||
all.sort(Comparator.comparing(KeyValueStore::getName));
|
||||
if (marker != null && !marker.isEmpty()) {
|
||||
all = new ArrayList<>(all.stream().filter(kvs -> kvs.getName().compareTo(marker) > 0).toList());
|
||||
}
|
||||
if (maxItems > 0 && all.size() > maxItems) {
|
||||
return new ArrayList<>(all.subList(0, maxItems));
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
public synchronized KeyValueStore update(String name, String ifMatch, String comment) {
|
||||
KeyValueStore existing = describe(name);
|
||||
requireControlPlaneEtag(existing, ifMatch);
|
||||
if (comment == null) {
|
||||
throw new AwsException("InvalidArgument", "The Comment is required.", 400);
|
||||
}
|
||||
String effectiveComment = comment;
|
||||
validateComment(effectiveComment);
|
||||
KeyValueStore updated = copyOf(existing);
|
||||
updated.setComment(effectiveComment);
|
||||
updated.setEtag(newEtag());
|
||||
updated.setLastModifiedTime(Instant.now());
|
||||
store.put(name, updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the store. The caller has already checked that no function is associated with it,
|
||||
* since functions are owned by {@link CloudFrontService}.
|
||||
*/
|
||||
public synchronized void delete(String name, String ifMatch) {
|
||||
KeyValueStore existing = describe(name);
|
||||
requireControlPlaneEtag(existing, ifMatch);
|
||||
store.delete(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "cloudfront";
|
||||
}
|
||||
|
||||
/** The ARN a store named by the request is stored under, which ends in the id CloudFront minted for it. */
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
if (!"key-value-store".equals(type) || names.size() != 1) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return store.get(names.getFirst()).map(KeyValueStore::getArn);
|
||||
}
|
||||
public Optional<KeyValueStore> findByArn(String arn) {
|
||||
if (arn == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return store.scan(key -> true).stream().filter(kvs -> arn.equals(kvs.getArn())).findFirst();
|
||||
}
|
||||
|
||||
// ── Data plane ────────────────────────────────────────────────────────────
|
||||
|
||||
public KeyValueStore describeByArn(String arn) {
|
||||
return findByArn(arn).orElseThrow(() ->
|
||||
new AwsException("ResourceNotFoundException", "The Key Value Store was not found.", 404));
|
||||
}
|
||||
|
||||
/** One read of the store, so the value and the counts that go with it come from the same state. */
|
||||
public KeyLookup getKey(String arn, String key) {
|
||||
KeyValueStore kvs = describeByArn(arn);
|
||||
String value = kvs.getItems().get(key);
|
||||
if (value == null) {
|
||||
throw new AwsException("ResourceNotFoundException", "The Key was not found.", 404);
|
||||
}
|
||||
return new KeyLookup(key, value, kvs);
|
||||
}
|
||||
|
||||
public record KeyLookup(String key, String value, KeyValueStore store) {}
|
||||
|
||||
public synchronized KeyValueStore putKey(String arn, String ifMatch, String key, String value) {
|
||||
Map<String, String> puts = new LinkedHashMap<>();
|
||||
puts.put(key, value == null ? "" : value);
|
||||
return apply(arn, ifMatch, puts, List.of(), false);
|
||||
}
|
||||
|
||||
public synchronized KeyValueStore deleteKey(String arn, String ifMatch, String key) {
|
||||
return apply(arn, ifMatch, Map.of(), List.of(key), true);
|
||||
}
|
||||
|
||||
/** Batch update. A delete of a key that is not in the store is skipped. */
|
||||
public synchronized KeyValueStore updateKeys(String arn, String ifMatch, Map<String, String> puts,
|
||||
List<String> deletes) {
|
||||
return apply(arn, ifMatch, puts, deletes, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies puts and then deletes in one step and rotates the ETag once. Nothing is written when
|
||||
* any entry fails validation or the result would exceed the store size quota.
|
||||
*/
|
||||
private KeyValueStore apply(String arn, String ifMatch, Map<String, String> puts, List<String> deletes,
|
||||
boolean failOnMissingDelete) {
|
||||
KeyValueStore kvs = describeByArn(arn);
|
||||
requireDataPlaneEtag(kvs, ifMatch);
|
||||
for (Map.Entry<String, String> put : puts.entrySet()) {
|
||||
validateKey(put.getKey());
|
||||
validateValue(put.getValue());
|
||||
}
|
||||
for (String key : deletes) {
|
||||
validateKey(key);
|
||||
}
|
||||
|
||||
Map<String, String> updated = new LinkedHashMap<>(kvs.getItems());
|
||||
updated.putAll(puts);
|
||||
for (String key : deletes) {
|
||||
if (updated.remove(key) == null && failOnMissingDelete) {
|
||||
throw new AwsException("ResourceNotFoundException", "The Key was not found.", 404);
|
||||
}
|
||||
}
|
||||
if (totalSizeInBytes(updated) > MAX_STORE_BYTES) {
|
||||
throw new AwsException("ServiceQuotaExceededException", "Limit exceeded.", 402);
|
||||
}
|
||||
|
||||
KeyValueStore result = copyOf(kvs);
|
||||
result.setItems(updated);
|
||||
result.setDataEtag(newEtag());
|
||||
result.setLastModifiedTime(Instant.now());
|
||||
store.put(result.getName(), result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** A page of keys in key order, and the token for the next page when there is one. */
|
||||
public KeyPage listKeys(String arn, String nextToken, Integer maxResults) {
|
||||
KeyValueStore kvs = describeByArn(arn);
|
||||
PaginatedResult<Map.Entry<String, String>> page = Pagination.paginate(
|
||||
new ArrayList<>(kvs.getItems().entrySet()), Map.Entry::getKey, maxResults, nextToken,
|
||||
DEFAULT_LIST_KEYS, MAX_LIST_KEYS, "ValidationException");
|
||||
return new KeyPage(page.items(), page.nextToken());
|
||||
}
|
||||
public record KeyPage(List<Map.Entry<String, String>> items, String nextToken) {}
|
||||
|
||||
public static int itemCount(KeyValueStore kvs) {
|
||||
return kvs.getItems().size();
|
||||
}
|
||||
|
||||
public static long totalSizeInBytes(KeyValueStore kvs) {
|
||||
return totalSizeInBytes(kvs.getItems());
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static long totalSizeInBytes(Map<String, String> items) {
|
||||
long total = 0;
|
||||
for (Map.Entry<String, String> entry : items.entrySet()) {
|
||||
total += utf8Length(entry.getKey()) + utf8Length(entry.getValue());
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
private static int utf8Length(String value) {
|
||||
return value.getBytes(StandardCharsets.UTF_8).length;
|
||||
}
|
||||
|
||||
private static String newEtag() {
|
||||
return UUID.randomUUID().toString();
|
||||
}
|
||||
|
||||
/** A stored store is never changed in place: the in-memory backend would show the change to earlier readers. */
|
||||
private static KeyValueStore copyOf(KeyValueStore source) {
|
||||
KeyValueStore copy = new KeyValueStore();
|
||||
copy.setName(source.getName());
|
||||
copy.setId(source.getId());
|
||||
copy.setComment(source.getComment());
|
||||
copy.setArn(source.getArn());
|
||||
copy.setStatus(source.getStatus());
|
||||
copy.setEtag(source.getEtag());
|
||||
copy.setDataEtag(source.getDataEtag());
|
||||
copy.setCreated(source.getCreated());
|
||||
copy.setLastModifiedTime(source.getLastModifiedTime());
|
||||
copy.setItems(new LinkedHashMap<>(source.getItems()));
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static void requireControlPlaneEtag(KeyValueStore kvs, String ifMatch) {
|
||||
if (ifMatch == null || !kvs.getEtag().equals(ifMatch)) {
|
||||
throw new AwsException("InvalidIfMatchVersion",
|
||||
"The If-Match version is missing or not valid for the resource.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireDataPlaneEtag(KeyValueStore kvs, String ifMatch) {
|
||||
if (ifMatch == null || !kvs.getDataEtag().equals(ifMatch)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Pre-Condition failed during update of Key-Value-Store", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateName(String name) {
|
||||
if (name == null || !STORE_NAME.matcher(name).matches()) {
|
||||
throw new AwsException("InvalidArgument",
|
||||
"The Key Value Store name must be 1 to 64 characters of letters, digits, hyphens and underscores.",
|
||||
400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateComment(String comment) {
|
||||
if (comment.length() > MAX_COMMENT_LENGTH) {
|
||||
throw new AwsException("InvalidArgument",
|
||||
"The Key Value Store comment must be at most " + MAX_COMMENT_LENGTH + " characters.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateKey(String key) {
|
||||
if (key == null || key.isEmpty() || utf8Length(key) > MAX_KEY_BYTES) {
|
||||
throw new AwsException("ValidationException",
|
||||
"A key must be 1 to " + MAX_KEY_BYTES + " bytes.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateValue(String value) {
|
||||
if (value != null && utf8Length(value) > MAX_VALUE_BYTES) {
|
||||
throw new AwsException("ValidationException",
|
||||
"A value must be at most " + MAX_VALUE_BYTES + " bytes.", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import io.floci.aws.services.cloudfront.model.FieldLevelEncryptionConfig;
|
||||
import io.floci.aws.services.cloudfront.model.FieldLevelEncryptionProfile;
|
||||
import io.floci.aws.services.cloudfront.model.Invalidation;
|
||||
import io.floci.aws.services.cloudfront.model.KeyGroup;
|
||||
import io.floci.aws.services.cloudfront.model.KeyValueStore;
|
||||
import io.floci.aws.services.cloudfront.model.MonitoringSubscription;
|
||||
import io.floci.aws.services.cloudfront.model.Origin;
|
||||
import io.floci.aws.services.cloudfront.model.OriginAccessControl;
|
||||
@@ -75,6 +76,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
|
||||
private static final List<String> OAC_SIGNING_BEHAVIORS =
|
||||
List.of("always-amz-auth", "never", "always", "no-override");
|
||||
private static final Set<String> FUNCTION_RUNTIMES = Set.of("cloudfront-js-1.0", "cloudfront-js-2.0");
|
||||
private static final int MAX_FUNCTIONS_PER_KEY_VALUE_STORE = 100;
|
||||
/**
|
||||
* The security policies {@code MinimumProtocolVersion} admits, the enumeration its shape
|
||||
* declares. {@code SSLv3} is the only one below {@code TLSv1}, which is why the floor the
|
||||
@@ -165,6 +167,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
|
||||
private final RegionResolver regionResolver;
|
||||
private final IamService iamService;
|
||||
private final CertificateReferenceResolver certificates;
|
||||
private final CloudFrontKeyValueStoreService keyValueStores;
|
||||
private final String configuredDomainSuffix;
|
||||
/**
|
||||
* Host suffixes under which every distribution is served as {@code <id><suffix>}, whatever
|
||||
@@ -179,14 +182,17 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
|
||||
private final Pattern lambdaOriginHost;
|
||||
|
||||
public CloudFrontService(StorageFactory factory, EmulatorConfig config, RegionResolver regionResolver) {
|
||||
this(factory, config, regionResolver, null, null);
|
||||
this(factory, config, regionResolver, null, null,
|
||||
new CloudFrontKeyValueStoreService(factory, regionResolver));
|
||||
}
|
||||
|
||||
@Inject
|
||||
public CloudFrontService(StorageFactory factory, EmulatorConfig config, RegionResolver regionResolver,
|
||||
IamService iamService, CertificateReferenceResolver certificates) {
|
||||
IamService iamService, CertificateReferenceResolver certificates,
|
||||
CloudFrontKeyValueStoreService keyValueStores) {
|
||||
this.iamService = iamService;
|
||||
this.certificates = certificates;
|
||||
this.keyValueStores = keyValueStores;
|
||||
this.distStore = factory.create("cloudfront", "cloudfront-distributions.json",
|
||||
new TypeReference<Map<String, Distribution>>() {});
|
||||
this.invalidationStore = factory.create("cloudfront", "cloudfront-invalidations.json",
|
||||
@@ -1858,6 +1864,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
|
||||
|
||||
public synchronized CloudFrontFunction createFunction(CloudFrontFunction fn) {
|
||||
validateFunctionRuntime(fn.getRuntime());
|
||||
validateKeyValueStoreAssociations(fn);
|
||||
// The bare name holds the DEVELOPMENT stage, and the LIVE stage of releases before
|
||||
// stage-aware keys.
|
||||
if (functionStore.get(fn.getName()).isPresent()
|
||||
@@ -1890,6 +1897,8 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
|
||||
public synchronized CloudFrontFunction updateFunction(String name, String ifMatch,
|
||||
CloudFrontFunction updated) {
|
||||
validateFunctionRuntime(updated.getRuntime());
|
||||
updated.setName(name);
|
||||
validateKeyValueStoreAssociations(updated);
|
||||
CloudFrontFunction existing = describeFunction(name, null);
|
||||
if (!existing.getEtag().equals(ifMatch)) {
|
||||
throw new AwsException("InvalidIfMatchVersion",
|
||||
@@ -1969,6 +1978,72 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private void validateKeyValueStoreAssociations(CloudFrontFunction fn) {
|
||||
List<String> arns = fn.getKeyValueStoreArns();
|
||||
if (arns == null || arns.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
if (arns.size() > 1) {
|
||||
throw new AwsException("InvalidArgument",
|
||||
"A function can be associated with at most one key value store.", 400);
|
||||
}
|
||||
if ("cloudfront-js-1.0".equals(fn.getRuntime())) {
|
||||
throw new AwsException("InvalidArgument",
|
||||
"A key value store can only be associated with a cloudfront-js-2.0 function.", 400);
|
||||
}
|
||||
for (String arn : arns) {
|
||||
if (keyValueStores.findByArn(arn).isEmpty()) {
|
||||
throw new AwsException("EntityNotFound", "The specified KeyValueStore does not exist.", 404);
|
||||
}
|
||||
long otherFunctions = functionStore.scan(key -> true).stream()
|
||||
.filter(other -> !other.getName().equals(fn.getName())
|
||||
&& other.getKeyValueStoreArns() != null
|
||||
&& other.getKeyValueStoreArns().contains(arn))
|
||||
.map(CloudFrontFunction::getName)
|
||||
.distinct()
|
||||
.count();
|
||||
if (otherFunctions >= MAX_FUNCTIONS_PER_KEY_VALUE_STORE) {
|
||||
throw new AwsException("TooManyFunctionsAssociatedToKeyValueStore",
|
||||
"A key value store can be associated with at most " + MAX_FUNCTIONS_PER_KEY_VALUE_STORE
|
||||
+ " functions.", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Key value stores ──────────────────────────────────────────────────────
|
||||
|
||||
public KeyValueStore createKeyValueStore(String name, String comment, boolean hasImportSource) {
|
||||
if (hasImportSource) {
|
||||
throw new AwsException("InvalidArgument", "ImportSource is not supported.", 400);
|
||||
}
|
||||
return keyValueStores.create(name, comment);
|
||||
}
|
||||
|
||||
public KeyValueStore describeKeyValueStore(String name) {
|
||||
return keyValueStores.describe(name);
|
||||
}
|
||||
|
||||
public List<KeyValueStore> listKeyValueStores(String marker, int maxItems, String status) {
|
||||
return keyValueStores.list(marker, maxItems, status);
|
||||
}
|
||||
|
||||
public KeyValueStore updateKeyValueStore(String name, String ifMatch, String comment) {
|
||||
return keyValueStores.update(name, ifMatch, comment);
|
||||
}
|
||||
|
||||
public synchronized void deleteKeyValueStore(String name, String ifMatch) {
|
||||
KeyValueStore existing = keyValueStores.describe(name);
|
||||
boolean inUse = functionStore.scan(key -> true).stream()
|
||||
.anyMatch(fn -> fn.getKeyValueStoreArns() != null
|
||||
&& fn.getKeyValueStoreArns().contains(existing.getArn()));
|
||||
if (inUse) {
|
||||
throw new AwsException("CannotDeleteEntityWhileInUse",
|
||||
"Cannot delete KeyValueStore " + name + " because it is associated with a function", 409);
|
||||
}
|
||||
keyValueStores.delete(name, ifMatch);
|
||||
tagStore.delete(existing.getArn());
|
||||
}
|
||||
|
||||
private static AwsException invalidFunctionStage(String stage) {
|
||||
return new AwsException("InvalidArgument",
|
||||
"The parameter Stage must be DEVELOPMENT or LIVE: " + stage, 400);
|
||||
@@ -1982,6 +2057,8 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
|
||||
copy.setFunctionCode(source.getFunctionCode());
|
||||
copy.setRuntime(source.getRuntime());
|
||||
copy.setComment(source.getComment());
|
||||
copy.setKeyValueStoreArns(source.getKeyValueStoreArns() == null
|
||||
? new ArrayList<>() : new ArrayList<>(source.getKeyValueStoreArns()));
|
||||
copy.setEtag(source.getEtag());
|
||||
copy.setCreatedTime(source.getCreatedTime());
|
||||
copy.setLastModifiedTime(source.getLastModifiedTime());
|
||||
|
||||
@@ -3,6 +3,8 @@ package io.floci.aws.services.cloudfront.model;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
public class CloudFrontFunction {
|
||||
@@ -16,9 +18,13 @@ public class CloudFrontFunction {
|
||||
private String etag;
|
||||
private Instant createdTime;
|
||||
private Instant lastModifiedTime;
|
||||
private List<String> keyValueStoreArns = new ArrayList<>();
|
||||
|
||||
public CloudFrontFunction() {}
|
||||
|
||||
public List<String> getKeyValueStoreArns() { return keyValueStoreArns; }
|
||||
public void setKeyValueStoreArns(List<String> keyValueStoreArns) { this.keyValueStoreArns = keyValueStoreArns; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package io.floci.aws.services.cloudfront.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
public class KeyValueStore {
|
||||
|
||||
private String name;
|
||||
private String id;
|
||||
private String comment;
|
||||
private String arn;
|
||||
private String status;
|
||||
private String etag;
|
||||
private String dataEtag;
|
||||
private Instant created;
|
||||
private Instant lastModifiedTime;
|
||||
private Map<String, String> items = new LinkedHashMap<>();
|
||||
|
||||
public KeyValueStore() {}
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
|
||||
public String getComment() { return comment; }
|
||||
public void setComment(String comment) { this.comment = comment; }
|
||||
|
||||
public String getArn() { return arn; }
|
||||
public void setArn(String arn) { this.arn = arn; }
|
||||
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
|
||||
public String getEtag() { return etag; }
|
||||
public void setEtag(String etag) { this.etag = etag; }
|
||||
|
||||
public String getDataEtag() { return dataEtag; }
|
||||
public void setDataEtag(String dataEtag) { this.dataEtag = dataEtag; }
|
||||
|
||||
public Instant getCreated() { return created; }
|
||||
public void setCreated(Instant created) { this.created = created; }
|
||||
|
||||
public Instant getLastModifiedTime() { return lastModifiedTime; }
|
||||
public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; }
|
||||
|
||||
public Map<String, String> getItems() { return items; }
|
||||
public void setItems(Map<String, String> items) { this.items = items; }
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
{
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_cloudfront_keyvaluestore_shapes.py",
|
||||
"botocore": "botocore 1.43.118 (installed package)"
|
||||
},
|
||||
"operations": {
|
||||
"DeleteKey": "DeleteKeyRequest",
|
||||
"DescribeKeyValueStore": "DescribeKeyValueStoreRequest",
|
||||
"GetKey": "GetKeyRequest",
|
||||
"ListKeys": "ListKeysRequest",
|
||||
"PutKey": "PutKeyRequest",
|
||||
"UpdateKeys": "UpdateKeysRequest"
|
||||
},
|
||||
"shapes": {
|
||||
"DeleteKeyRequest": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"KvsARN",
|
||||
"Key",
|
||||
"IfMatch"
|
||||
],
|
||||
"members": {
|
||||
"KvsARN": "KvsARN",
|
||||
"Key": "Key",
|
||||
"IfMatch": "Etag"
|
||||
}
|
||||
},
|
||||
"DeleteKeyRequestListItem": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"Key"
|
||||
],
|
||||
"members": {
|
||||
"Key": "Key"
|
||||
}
|
||||
},
|
||||
"DeleteKeyRequestsList": {
|
||||
"type": "list",
|
||||
"member": "DeleteKeyRequestListItem"
|
||||
},
|
||||
"DescribeKeyValueStoreRequest": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"KvsARN"
|
||||
],
|
||||
"members": {
|
||||
"KvsARN": "KvsARN"
|
||||
}
|
||||
},
|
||||
"Etag": {
|
||||
"type": "string"
|
||||
},
|
||||
"GetKeyRequest": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"KvsARN",
|
||||
"Key"
|
||||
],
|
||||
"members": {
|
||||
"KvsARN": "KvsARN",
|
||||
"Key": "Key"
|
||||
}
|
||||
},
|
||||
"Key": {
|
||||
"type": "string",
|
||||
"min": 1,
|
||||
"max": 1024
|
||||
},
|
||||
"KvsARN": {
|
||||
"type": "string",
|
||||
"min": 1,
|
||||
"max": 2048
|
||||
},
|
||||
"ListKeysRequest": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"KvsARN"
|
||||
],
|
||||
"members": {
|
||||
"KvsARN": "KvsARN",
|
||||
"NextToken": "String",
|
||||
"MaxResults": "ListKeysRequestMaxResultsInteger"
|
||||
}
|
||||
},
|
||||
"ListKeysRequestMaxResultsInteger": {
|
||||
"type": "integer",
|
||||
"min": 1,
|
||||
"max": 50
|
||||
},
|
||||
"PutKeyRequest": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"Key",
|
||||
"Value",
|
||||
"KvsARN",
|
||||
"IfMatch"
|
||||
],
|
||||
"members": {
|
||||
"Key": "Key",
|
||||
"Value": "Value",
|
||||
"KvsARN": "KvsARN",
|
||||
"IfMatch": "Etag"
|
||||
}
|
||||
},
|
||||
"PutKeyRequestListItem": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"Key",
|
||||
"Value"
|
||||
],
|
||||
"members": {
|
||||
"Key": "Key",
|
||||
"Value": "Value"
|
||||
}
|
||||
},
|
||||
"PutKeyRequestsList": {
|
||||
"type": "list",
|
||||
"member": "PutKeyRequestListItem"
|
||||
},
|
||||
"String": {
|
||||
"type": "string"
|
||||
},
|
||||
"UpdateKeysRequest": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"KvsARN",
|
||||
"IfMatch"
|
||||
],
|
||||
"members": {
|
||||
"KvsARN": "KvsARN",
|
||||
"IfMatch": "Etag",
|
||||
"Puts": "PutKeyRequestsList",
|
||||
"Deletes": "DeleteKeyRequestsList"
|
||||
}
|
||||
},
|
||||
"Value": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -426,6 +426,7 @@
|
||||
"UpdatePublicKey",
|
||||
"UpdateSavingsPlan"
|
||||
],
|
||||
"cloudfront-keyvaluestore": [],
|
||||
"controltower": [
|
||||
"CreateLandingZone",
|
||||
"CreateManagedAccount",
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-11", "note": "make iam-request-resources-check re-derives every operation's resources from botocore; make iam-request-resources-verify checks every action, type and format against AWS."},
|
||||
"namespaces": {"access-analyzer": ["accessanalyzer"], "acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudfront": ["cloudfront"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "controltower": ["controltower"], "cur": ["cur"], "datasync": ["datasync"], "dynamodb": ["dynamodb"], "ec2": ["ec2"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "globalaccelerator": ["globalaccelerator"], "guardduty": ["guardduty"], "inspector2": ["inspector2"], "kinesisanalytics": ["kinesisanalyticsv2"], "logs": ["logs"], "macie2": ["macie2"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "quicksight": ["quicksight"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "securityhub": ["securityhub"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "signer": ["signer", "signer-data"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"], "xray": ["xray"]},
|
||||
"namespaces": {"access-analyzer": ["accessanalyzer"], "acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudfront": ["cloudfront"], "cloudfront-keyvaluestore": ["cloudfront-keyvaluestore"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "controltower": ["controltower"], "cur": ["cur"], "datasync": ["datasync"], "dynamodb": ["dynamodb"], "ec2": ["ec2"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "globalaccelerator": ["globalaccelerator"], "guardduty": ["guardduty"], "inspector2": ["inspector2"], "kinesisanalytics": ["kinesisanalyticsv2"], "logs": ["logs"], "macie2": ["macie2"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "quicksight": ["quicksight"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "securityhub": ["securityhub"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "signer": ["signer", "signer-data"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"], "xray": ["xray"]},
|
||||
"clientsNotRead": {"kinesisanalytics": "Kinesis Data Analytics v1, SQL applications on the KinesisAnalytics_20150814 target, which Floci does not serve (it serves v2, kinesisanalyticsv2); its operations share v2's names and name their resources by other members"},
|
||||
"handBuilt": ["apigateway", "bedrock", "dsql", "dynamodb", "eks", "iam", "kinesis", "kms", "lambda", "logs", "pipes", "resource-groups", "s3", "scheduler", "secretsmanager", "sns", "sqs", "ssm", "sts"],
|
||||
"notCovered": {"account": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "airflow": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appsync": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "aps": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "autoscaling": "not read yet: AWS's group and launch configuration ARNs carry an id the service mints, `autoScalingGroup:<id>:autoScalingGroupName/<name>`, while Floci mints `autoScalingGroup:<name>`, which other services (ECS capacity providers) read back; the mint is fixed first", "aws-marketplace": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "backup": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "batch": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudformation": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rule does not fill a name from, so nearly every operation needs a correction", "cloudwatch": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codeartifact": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "codedeploy": "not read yet: the Service Reference gives an on-premises instance's ARN as `instance:${InstanceName}`, while the CodeDeploy permissions reference gives arn:aws:codedeploy:region:account-id:instance/instance-ID and AWS's GetOnPremisesInstance example answers instance/<name>_<id>, an id the service mints after the name; reading it needs that format corrected", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "comprehend": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "config": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "connect": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "controlcatalog": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "detective": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "dlm": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "dms": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ec2-instance-connect": "not read yet: a later batch, with the tests that show its ARNs are the ones itsLine truncated
|
||||
"otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifyuibuilder", "aoss", "appfabric", "appflow", "application-signals", "application-signals-mcp", "appmesh", "appmesh-preview", "apprunner", "appstream", "apptest", "arc-region-switch", "arc-zonal-shift", "artifact", "assurance", "auditmanager", "aws-external-anthropic", "b2bi", "backup-gateway", "backup-search", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudfront-keyvaluestore", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "codewhisperer", "cognito-sync", "connect-campaigns", "consoleapp", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ecr-public", "eks-auth", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "emr-containers", "end-user-messaging", "entityresolution", "evs", "finspace", "finspace-api", "fms", "forecast", "frauddetector", "freertos", "fsx", "gamelift", "gameliftstreams", "geo", "geo-maps", "geo-places", "geo-routes", "glacier", "grafana", "greengrass", "groundstation", "health", "health-agent", "healthlake", "honeycode", "identity-sync", "imagebuilder", "interconnect", "internetmonitor", "invoicing", "iotanalytics", "iotdeviceadvisor", "iotfleethub", "iotfleetwise", "iotjobsdata", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "iq", "iq-permission", "ivs", "ivschat", "kafka-cluster", "kafkaconnect", "kendra", "kendra-ranking", "kinesisvideo", "launchwizard", "lex", "license-manager", "license-manager-linux-subscriptions", "license-manager-user-subscriptions", "lookoutequipment", "lookoutmetrics", "lookoutvision", "m2", "machinelearning", "managedblockchain", "mapcredits", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "mediatailor", "medical-imaging", "mgh", "mgn", "migrationhub-orchestrator", "mobiletargeting", "monitron", "mpa", "neptune-db", "neptune-graph", "network-security-manager", "networkflowmonitor", "networkmanager", "networkmonitor", "nimble", "notifications", "notifications-contacts", "nova-act", "observabilityadmin", "odb", "omics", "one", "opensearch", "opsworks", "osis", "outposts", "panorama", "partnercentral", "payments", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "private-networks", "profile", "proton", "purchase-orders", "q", "qapps", "qbusiness", "qdeveloper", "qldb", "rbin", "rds-db", "refactor-spaces", "repostspace", "resiliencehub", "robomaker", "rolesanywhere", "route53-recovery-cluster", "route53-recovery-control-config", "route53-recovery-readiness", "route53globalresolver", "route53profiles", "rtbfabric", "s3-object-lambda", "s3-outposts", "s3express", "s3files", "sagemaker-geospatial", "sagemaker-mlflow", "savingsplans", "schemas", "scn", "sdb", "security-ir", "securityagent", "securitylake", "serverlessrepo", "shield", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "ssmmessages", "storagegateway", "supportauthz", "synthetics", "thinclient", "timestream", "tnb", "transform", "transform-custom", "trustedadvisor", "ts", "vendor-insights", "voiceid", "vpc-lattice", "vpc-lattice-svcs", "vpce", "waf", "waf-regional", "wellarchitected", "wickr", "wisdom", "workdocs", "worklink", "workmail", "workmailmessageflow", "workspaces", "workspaces-instances", "workspaces-web"],
|
||||
"arnFormats": {"access-analyzer": {"Analyzer": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}", "ArchiveRule": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}/archive-rule/${RuleName}"}, "acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "system-table": "arn:${Partition}:athena:${Region}:${Account}:system-table/${TableName}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudfront": {"anycast-ip-list": "arn:${Partition}:cloudfront::${Account}:anycast-ip-list/${Id}", "cache-policy": "arn:${Partition}:cloudfront::${Account}:cache-policy/${Id}", "connection-function": "arn:${Partition}:cloudfront::${Account}:connection-function/${Id}", "connection-group": "arn:${Partition}:cloudfront::${Account}:connection-group/${Id}", "continuous-deployment-policy": "arn:${Partition}:cloudfront::${Account}:continuous-deployment-policy/${Id}", "distribution": "arn:${Partition}:cloudfront::${Account}:distribution/${DistributionId}", "distribution-tenant": "arn:${Partition}:cloudfront::${Account}:distribution-tenant/${Id}", "field-level-encryption-config": "arn:${Partition}:cloudfront::${Account}:field-level-encryption-config/${Id}", "field-level-encryption-profile": "arn:${Partition}:cloudfront::${Account}:field-level-encryption-profile/${Id}", "function": "arn:${Partition}:cloudfront::${Account}:function/${Name}", "key-value-store": "arn:${Partition}:cloudfront::${Account}:key-value-store/${Name}", "origin-access-control": "arn:${Partition}:cloudfront::${Account}:origin-access-control/${Id}", "origin-access-identity": "arn:${Partition}:cloudfront::${Account}:origin-access-identity/${Id}", "origin-request-policy": "arn:${Partition}:cloudfront::${Account}:origin-request-policy/${Id}", "realtime-log-config": "arn:${Partition}:cloudfront::${Account}:realtime-log-config/${Name}", "response-headers-policy": "arn:${Partition}:cloudfront::${Account}:response-headers-policy/${Id}", "streaming-distribution": "arn:${Partition}:cloudfront::${Account}:streaming-distribution/${DistributionId}", "trust-store": "arn:${Partition}:cloudfront::${Account}:trust-store/${Id}", "vpcorigin": "arn:${Partition}:cloudfront::${Account}:vpcorigin/${Id}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Region}:${Account}:trail/${TrailName}"}, "codebuild": {"build": "arn:${Partition}:codebuild:${Region}:${Account}:build/${BuildId}", "build-batch": "arn:${Partition}:codebuild:${Region}:${Account}:build-batch/${BuildBatchId}", "fleet": "arn:${Partition}:codebuild:${Region}:${Account}:fleet/${FleetName}:${FleetId}", "pLine truncated
|
||||
"otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifyuibuilder", "aoss", "appfabric", "appflow", "application-signals", "application-signals-mcp", "appmesh", "appmesh-preview", "apprunner", "appstream", "apptest", "arc-region-switch", "arc-zonal-shift", "artifact", "assurance", "auditmanager", "aws-external-anthropic", "b2bi", "backup-gateway", "backup-search", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "codewhisperer", "cognito-sync", "connect-campaigns", "consoleapp", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ecr-public", "eks-auth", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "emr-containers", "end-user-messaging", "entityresolution", "evs", "finspace", "finspace-api", "fms", "forecast", "frauddetector", "freertos", "fsx", "gamelift", "gameliftstreams", "geo", "geo-maps", "geo-places", "geo-routes", "glacier", "grafana", "greengrass", "groundstation", "health", "health-agent", "healthlake", "honeycode", "identity-sync", "imagebuilder", "interconnect", "internetmonitor", "invoicing", "iotanalytics", "iotdeviceadvisor", "iotfleethub", "iotfleetwise", "iotjobsdata", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "iq", "iq-permission", "ivs", "ivschat", "kafka-cluster", "kafkaconnect", "kendra", "kendra-ranking", "kinesisvideo", "launchwizard", "lex", "license-manager", "license-manager-linux-subscriptions", "license-manager-user-subscriptions", "lookoutequipment", "lookoutmetrics", "lookoutvision", "m2", "machinelearning", "managedblockchain", "mapcredits", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "mediatailor", "medical-imaging", "mgh", "mgn", "migrationhub-orchestrator", "mobiletargeting", "monitron", "mpa", "neptune-db", "neptune-graph", "network-security-manager", "networkflowmonitor", "networkmanager", "networkmonitor", "nimble", "notifications", "notifications-contacts", "nova-act", "observabilityadmin", "odb", "omics", "one", "opensearch", "opsworks", "osis", "outposts", "panorama", "partnercentral", "payments", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "private-networks", "profile", "proton", "purchase-orders", "q", "qapps", "qbusiness", "qdeveloper", "qldb", "rbin", "rds-db", "refactor-spaces", "repostspace", "resiliencehub", "robomaker", "rolesanywhere", "route53-recovery-cluster", "route53-recovery-control-config", "route53-recovery-readiness", "route53globalresolver", "route53profiles", "rtbfabric", "s3-object-lambda", "s3-outposts", "s3express", "s3files", "sagemaker-geospatial", "sagemaker-mlflow", "savingsplans", "schemas", "scn", "sdb", "security-ir", "securityagent", "securitylake", "serverlessrepo", "shield", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "ssmmessages", "storagegateway", "supportauthz", "synthetics", "thinclient", "timestream", "tnb", "transform", "transform-custom", "trustedadvisor", "ts", "vendor-insights", "voiceid", "vpc-lattice", "vpc-lattice-svcs", "vpce", "waf", "waf-regional", "wellarchitected", "wickr", "wisdom", "workdocs", "worklink", "workmail", "workmailmessageflow", "workspaces", "workspaces-instances", "workspaces-web"],
|
||||
"arnFormats": {"access-analyzer": {"Analyzer": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}", "ArchiveRule": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}/archive-rule/${RuleName}"}, "acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "system-table": "arn:${Partition}:athena:${Region}:${Account}:system-table/${TableName}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudfront": {"anycast-ip-list": "arn:${Partition}:cloudfront::${Account}:anycast-ip-list/${Id}", "cache-policy": "arn:${Partition}:cloudfront::${Account}:cache-policy/${Id}", "connection-function": "arn:${Partition}:cloudfront::${Account}:connection-function/${Id}", "connection-group": "arn:${Partition}:cloudfront::${Account}:connection-group/${Id}", "continuous-deployment-policy": "arn:${Partition}:cloudfront::${Account}:continuous-deployment-policy/${Id}", "distribution": "arn:${Partition}:cloudfront::${Account}:distribution/${DistributionId}", "distribution-tenant": "arn:${Partition}:cloudfront::${Account}:distribution-tenant/${Id}", "field-level-encryption-config": "arn:${Partition}:cloudfront::${Account}:field-level-encryption-config/${Id}", "field-level-encryption-profile": "arn:${Partition}:cloudfront::${Account}:field-level-encryption-profile/${Id}", "function": "arn:${Partition}:cloudfront::${Account}:function/${Name}", "key-value-store": "arn:${Partition}:cloudfront::${Account}:key-value-store/${Name}", "origin-access-control": "arn:${Partition}:cloudfront::${Account}:origin-access-control/${Id}", "origin-access-identity": "arn:${Partition}:cloudfront::${Account}:origin-access-identity/${Id}", "origin-request-policy": "arn:${Partition}:cloudfront::${Account}:origin-request-policy/${Id}", "realtime-log-config": "arn:${Partition}:cloudfront::${Account}:realtime-log-config/${Name}", "response-headers-policy": "arn:${Partition}:cloudfront::${Account}:response-headers-policy/${Id}", "streaming-distribution": "arn:${Partition}:cloudfront::${Account}:streaming-distribution/${DistributionId}", "trust-store": "arn:${Partition}:cloudfront::${Account}:trust-store/${Id}", "vpcorigin": "arn:${Partition}:cloudfront::${Account}:vpcorigin/${Id}"}, "cloudfront-keyvaluestore": {"key-value-store": "arn:${Partition}:cloudfront::${Account}:key-value-store/${ResourceId}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Region}:${Account}:trail/${TrailName}"}, "codebuild": {"build": "arn:${Partition}:codebuild:${Region}:${Account}:build/${BuildId}", "build-batch": "arn:${Partition}:codebuild:${Region}:${Account}:Line truncated
|
||||
"unqualified": {"states": ["statemachine"]},
|
||||
"mintedIds": {"events": ["api-destination", "connection"]},
|
||||
"operations": {
|
||||
@@ -298,6 +298,12 @@
|
||||
"ce:UpdateAnomalySubscription": {"action": "ce:UpdateAnomalySubscription", "types": ["anomalysubscription"], "resources": [{"types": ["anomalysubscription"], "arn": "SubscriptionArn"}]},
|
||||
"ce:UpdateCostAllocationTagsStatus": {"action": "ce:UpdateCostAllocationTagsStatus", "types": [], "resources": []},
|
||||
"ce:UpdateCostCategoryDefinition": {"action": "ce:UpdateCostCategoryDefinition", "types": ["costcategory"], "resources": [{"types": ["costcategory"], "arn": "CostCategoryArn"}]},
|
||||
"cloudfront-keyvaluestore:DeleteKey": {"action": "cloudfront-keyvaluestore:DeleteKey", "types": ["key-value-store"], "resources": [{"types": ["key-value-store"], "arn": "KvsARN"}], "located": {"KvsARN": "{KvsARN}"}},
|
||||
"cloudfront-keyvaluestore:DescribeKeyValueStore": {"action": "cloudfront-keyvaluestore:DescribeKeyValueStore", "types": ["key-value-store"], "resources": [{"types": ["key-value-store"], "arn": "KvsARN"}], "located": {"KvsARN": "{KvsARN}"}},
|
||||
"cloudfront-keyvaluestore:GetKey": {"action": "cloudfront-keyvaluestore:GetKey", "types": ["key-value-store"], "resources": [{"types": ["key-value-store"], "arn": "KvsARN"}], "located": {"KvsARN": "{KvsARN}"}},
|
||||
"cloudfront-keyvaluestore:ListKeys": {"action": "cloudfront-keyvaluestore:ListKeys", "types": ["key-value-store"], "resources": [{"types": ["key-value-store"], "arn": "KvsARN"}], "located": {"KvsARN": "{KvsARN}"}},
|
||||
"cloudfront-keyvaluestore:PutKey": {"action": "cloudfront-keyvaluestore:PutKey", "types": ["key-value-store"], "resources": [{"types": ["key-value-store"], "arn": "KvsARN"}], "located": {"KvsARN": "{KvsARN}"}},
|
||||
"cloudfront-keyvaluestore:UpdateKeys": {"action": "cloudfront-keyvaluestore:UpdateKeys", "types": ["key-value-store"], "resources": [{"types": ["key-value-store"], "arn": "KvsARN"}], "located": {"KvsARN": "{KvsARN}"}},
|
||||
"cloudfront:AssociateAlias": {"action": "cloudfront:AssociateAlias", "types": ["distribution"], "resources": [{"type": "distribution", "fill": {"DistributionId": "TargetDistributionId"}}], "located": {"TargetDistributionId": "{TargetDistributionId}"}},
|
||||
"cloudfront:AssociateDistributionTenantWebACL": {"action": "cloudfront:AssociateDistributionTenantWebACL", "types": ["distribution-tenant"], "resources": []},
|
||||
"cloudfront:AssociateDistributionWebACL": {"action": "cloudfront:AssociateDistributionWebACL", "types": ["distribution"], "resources": []},
|
||||
|
||||
@@ -465,6 +465,19 @@
|
||||
"VerifyDnsConfiguration": {"method": "POST", "requestUri": "/2020-05-31/verify-dns-configuration"}
|
||||
}
|
||||
},
|
||||
"cloudfront-keyvaluestore": {
|
||||
"credentialScope": "cloudfront-keyvaluestore",
|
||||
"apiVersion": "2022-07-26",
|
||||
"accessDeniedStatus": 403,
|
||||
"operations": {
|
||||
"DeleteKey": {"method": "DELETE", "requestUri": "/key-value-stores/{KvsARN}/keys/{Key}"},
|
||||
"DescribeKeyValueStore": {"method": "GET", "requestUri": "/key-value-stores/{KvsARN}"},
|
||||
"GetKey": {"method": "GET", "requestUri": "/key-value-stores/{KvsARN}/keys/{Key}"},
|
||||
"ListKeys": {"method": "GET", "requestUri": "/key-value-stores/{KvsARN}/keys"},
|
||||
"PutKey": {"method": "PUT", "requestUri": "/key-value-stores/{KvsARN}/keys/{Key}"},
|
||||
"UpdateKeys": {"method": "POST", "requestUri": "/key-value-stores/{KvsARN}/keys"}
|
||||
}
|
||||
},
|
||||
"controltower": {
|
||||
"credentialScope": "controltower",
|
||||
"apiVersion": "2018-05-10",
|
||||
|
||||
@@ -854,6 +854,27 @@ class PartitionCrossServiceSmokeIntegrationTest {
|
||||
created.xmlPath().getString("FunctionSummary.FunctionMetadata.FunctionARN"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
|
||||
void cloudFrontKeyValueStoreArn(PartitionCase partitionCase) {
|
||||
String region = offered(partitionCase, "cloudfront");
|
||||
String name = unique("smoke-kvs", partitionCase);
|
||||
String body = """
|
||||
<CreateKeyValueStoreRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
||||
<Name>%s</Name>
|
||||
</CreateKeyValueStoreRequest>
|
||||
""".formatted(name);
|
||||
Response created = signed(region, "cloudfront")
|
||||
.contentType("application/xml")
|
||||
.body(body)
|
||||
.when().post("/2020-05-31/key-value-store").then().statusCode(201).extract().response();
|
||||
String etag = created.header("ETag");
|
||||
cleanup.register(() -> signed(region, "cloudfront")
|
||||
.header("If-Match", etag)
|
||||
.when().delete("/2020-05-31/key-value-store/" + name));
|
||||
PartitionMatrix.assertGlobalArnIn(partitionCase, created.xmlPath().getString("KeyValueStore.ARN"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
|
||||
void ramResourceShareArn(PartitionCase partitionCase) {
|
||||
|
||||
+463
@@ -0,0 +1,463 @@
|
||||
package io.floci.aws.services.cloudfront;
|
||||
|
||||
import io.floci.aws.core.common.XmlParser;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.hamcrest.xml.HasXPath.hasXPath;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
/** CloudFront key value stores: the control plane under /2020-05-31 and the cloudfront-keyvaluestore data plane. */
|
||||
@QuarkusTest
|
||||
class CloudFrontKeyValueStoreIntegrationTest {
|
||||
|
||||
private static final String CLOUDFRONT = "/2020-05-31/";
|
||||
private static final String DATA_PLANE = "/key-value-stores/";
|
||||
private static final String XML = "application/xml";
|
||||
private static final String NS = "http://cloudfront.amazonaws.com/doc/2020-05-31/";
|
||||
private static final String FUNCTION_CODE = "function handler(event) { return event.request; }";
|
||||
private static final String SIGV4A_AUTHORIZATION = "AWS4-ECDSA-P256-SHA256 "
|
||||
+ "Credential=000000000000/20260101/cloudfront-keyvaluestore/aws4_request, "
|
||||
+ "SignedHeaders=host;x-amz-date, Signature=00";
|
||||
|
||||
private record Store(String name, String arn, String etag, String dataEtag) {}
|
||||
|
||||
private static String uniqueName() {
|
||||
return "kvs-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
private static Store createStore(String name, String comment) {
|
||||
Response created = given().contentType(XML)
|
||||
.body("<CreateKeyValueStoreRequest xmlns=\"%s\"><Name>%s</Name><Comment>%s</Comment></CreateKeyValueStoreRequest>"
|
||||
.formatted(NS, name, comment))
|
||||
.when().post(CLOUDFRONT + "key-value-store");
|
||||
created.then().statusCode(201);
|
||||
String xml = created.asString();
|
||||
String arn = XmlParser.extractFirst(xml, "ARN", null);
|
||||
Response described = given().urlEncodingEnabled(false).header("Authorization", SIGV4A_AUTHORIZATION)
|
||||
.when().get(DATA_PLANE + encoded(arn));
|
||||
described.then().statusCode(200);
|
||||
return new Store(name, arn, created.header("ETag"), described.header("ETag"));
|
||||
}
|
||||
|
||||
private static String encoded(String value) {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
|
||||
}
|
||||
|
||||
private static String storePath(Store store) {
|
||||
return DATA_PLANE + encoded(store.arn());
|
||||
}
|
||||
|
||||
private static RequestSpecification dataPlane() {
|
||||
return given().urlEncodingEnabled(false).header("Authorization", SIGV4A_AUTHORIZATION);
|
||||
}
|
||||
|
||||
private static Response putKey(Store store, String etag, String key, String value) {
|
||||
return dataPlane().header("If-Match", etag).contentType("application/json")
|
||||
.body("{\"Value\":\"%s\"}".formatted(value))
|
||||
.when().put(storePath(store) + "/keys/" + encoded(key));
|
||||
}
|
||||
|
||||
private static String createFunction(String name, String runtime, String kvsArn) {
|
||||
String associations = kvsArn == null ? ""
|
||||
: "<KeyValueStoreAssociations><Quantity>1</Quantity><Items><KeyValueStoreAssociation>"
|
||||
+ "<KeyValueStoreARN>" + kvsArn + "</KeyValueStoreARN>"
|
||||
+ "</KeyValueStoreAssociation></Items></KeyValueStoreAssociations>";
|
||||
return """
|
||||
<CreateFunctionRequest xmlns="%s">
|
||||
<Name>%s</Name>
|
||||
<FunctionConfig><Comment>kvs</Comment><Runtime>%s</Runtime>%s</FunctionConfig>
|
||||
<FunctionCode>%s</FunctionCode>
|
||||
</CreateFunctionRequest>
|
||||
""".formatted(NS, name, runtime, associations,
|
||||
Base64.getEncoder().encodeToString(FUNCTION_CODE.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
// ── Control plane ─────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void controlPlaneCreatesDescribesListsUpdatesAndDeletes() {
|
||||
String name = uniqueName();
|
||||
|
||||
Response created = given().contentType(XML)
|
||||
.body("<CreateKeyValueStoreRequest xmlns=\"%s\"><Name>%s</Name><Comment>first</Comment></CreateKeyValueStoreRequest>"
|
||||
.formatted(NS, name))
|
||||
.when().post(CLOUDFRONT + "key-value-store");
|
||||
created.then()
|
||||
.statusCode(201)
|
||||
.header("ETag", notNullValue())
|
||||
.header("Location", containsString("/key-value-store/" + name))
|
||||
.body(hasXPath("local-name(/*)", equalTo("KeyValueStore")))
|
||||
.body(hasXPath("namespace-uri(/*)", equalTo(NS)))
|
||||
.body(hasXPath("/*[local-name()='KeyValueStore']/*[local-name()='Status']", equalTo("READY")));
|
||||
String arn = XmlParser.extractFirst(created.asString(), "ARN", null);
|
||||
assertNotNull(arn);
|
||||
assertEquals(true, arn.matches("arn:aws:cloudfront::\\d{12}:key-value-store/[0-9a-f-]{36}"));
|
||||
|
||||
Response described = given().when().get(CLOUDFRONT + "key-value-store/" + name);
|
||||
described.then().statusCode(200).header("ETag", equalTo(created.header("ETag")));
|
||||
assertEquals(arn, XmlParser.extractFirst(described.asString(), "ARN", null));
|
||||
|
||||
given().when().get(CLOUDFRONT + "key-value-store")
|
||||
.then().statusCode(200)
|
||||
.body(hasXPath("local-name(/*)", equalTo("KeyValueStoreList")))
|
||||
.body(hasXPath("//*[local-name()='KeyValueStore']/*[local-name()='Name'][text()='" + name + "']"));
|
||||
|
||||
Response updated = given().contentType(XML).header("If-Match", created.header("ETag"))
|
||||
.body("<UpdateKeyValueStoreRequest xmlns=\"%s\"><Comment>second</Comment></UpdateKeyValueStoreRequest>"
|
||||
.formatted(NS))
|
||||
.when().put(CLOUDFRONT + "key-value-store/" + name);
|
||||
updated.then().statusCode(200);
|
||||
assertNotEquals(created.header("ETag"), updated.header("ETag"));
|
||||
assertEquals("second", XmlParser.extractFirst(updated.asString(), "Comment", null));
|
||||
|
||||
given().header("If-Match", updated.header("ETag"))
|
||||
.when().delete(CLOUDFRONT + "key-value-store/" + name)
|
||||
.then().statusCode(204);
|
||||
given().when().get(CLOUDFRONT + "key-value-store/" + name).then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void controlPlaneErrorsUseTheModeledCodes() {
|
||||
Store store = createStore(uniqueName(), "errors");
|
||||
|
||||
given().contentType(XML)
|
||||
.body("<CreateKeyValueStoreRequest xmlns=\"%s\"><Name>%s</Name></CreateKeyValueStoreRequest>"
|
||||
.formatted(NS, store.name()))
|
||||
.when().post(CLOUDFRONT + "key-value-store")
|
||||
.then().statusCode(409).body(hasXPath("//*[local-name()='Code']", equalTo("EntityAlreadyExists")));
|
||||
given().when().get(CLOUDFRONT + "key-value-store/does-not-exist")
|
||||
.then().statusCode(404).body(hasXPath("//*[local-name()='Code']", equalTo("EntityNotFound")));
|
||||
given().contentType(XML)
|
||||
.body("<CreateKeyValueStoreRequest xmlns=\"%s\"><Name>not valid!</Name></CreateKeyValueStoreRequest>"
|
||||
.formatted(NS))
|
||||
.when().post(CLOUDFRONT + "key-value-store")
|
||||
.then().statusCode(400).body(hasXPath("//*[local-name()='Code']", equalTo("InvalidArgument")));
|
||||
given().header("If-Match", "stale")
|
||||
.when().delete(CLOUDFRONT + "key-value-store/" + store.name())
|
||||
.then().statusCode(400).body(hasXPath("//*[local-name()='Code']", equalTo("InvalidIfMatchVersion")));
|
||||
}
|
||||
|
||||
// ── Data plane ────────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void dataPlaneRoundTripsKeysThroughAPercentEncodedArn() {
|
||||
Store store = createStore(uniqueName(), "data plane");
|
||||
|
||||
Response put = putKey(store, store.dataEtag(), "demo.example.com", "3-5-19-1234");
|
||||
put.then().statusCode(200)
|
||||
.body("ItemCount", equalTo(1))
|
||||
.body("TotalSizeInBytes", equalTo("demo.example.com".length() + "3-5-19-1234".length()))
|
||||
.header("ETag", notNullValue());
|
||||
assertNotEquals(store.dataEtag(), put.header("ETag"));
|
||||
|
||||
dataPlane().when().get(storePath(store) + "/keys/" + encoded("demo.example.com"))
|
||||
.then().statusCode(200)
|
||||
.body("Key", equalTo("demo.example.com"))
|
||||
.body("Value", equalTo("3-5-19-1234"))
|
||||
.body("ItemCount", equalTo(1));
|
||||
|
||||
dataPlane().when().get(storePath(store))
|
||||
.then().statusCode(200)
|
||||
.body("KvsARN", equalTo(store.arn()))
|
||||
.body("ItemCount", equalTo(1))
|
||||
.body("Status", equalTo("READY"))
|
||||
.body("Created", notNullValue())
|
||||
.header("ETag", equalTo(put.header("ETag")));
|
||||
|
||||
dataPlane().header("If-Match", put.header("ETag"))
|
||||
.when().delete(storePath(store) + "/keys/" + encoded("demo.example.com"))
|
||||
.then().statusCode(200).body("ItemCount", equalTo(0));
|
||||
dataPlane().when().get(storePath(store) + "/keys/" + encoded("demo.example.com"))
|
||||
.then().statusCode(404)
|
||||
.header("X-Amzn-Errortype", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyMayContainSlashesAndSpaces() {
|
||||
Store store = createStore(uniqueName(), "odd keys");
|
||||
String key = "tenant/a b?c";
|
||||
|
||||
putKey(store, store.dataEtag(), key, "v1").then().statusCode(200);
|
||||
|
||||
dataPlane().when().get(storePath(store) + "/keys/" + encoded(key))
|
||||
.then().statusCode(200).body("Key", equalTo(key)).body("Value", equalTo("v1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dataPlaneWritesNeedTheCurrentEtag() {
|
||||
Store store = createStore(uniqueName(), "etag");
|
||||
Response first = putKey(store, store.dataEtag(), "a", "1");
|
||||
first.then().statusCode(200);
|
||||
|
||||
putKey(store, store.dataEtag(), "b", "2").then()
|
||||
.statusCode(400)
|
||||
.header("X-Amzn-Errortype", equalTo("ValidationException"));
|
||||
dataPlane().contentType("application/json").body("{\"Value\":\"2\"}")
|
||||
.when().put(storePath(store) + "/keys/b")
|
||||
.then().statusCode(400)
|
||||
.header("X-Amzn-Errortype", equalTo("ValidationException"));
|
||||
putKey(store, first.header("ETag"), "b", "2").then().statusCode(200).body("ItemCount", equalTo(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateKeysRejectsMoreThanFiftyEntriesAndAPutWithoutAValue() {
|
||||
Store store = createStore(uniqueName(), "limits");
|
||||
|
||||
StringBuilder puts = new StringBuilder();
|
||||
for (int i = 0; i < 51; i++) {
|
||||
puts.append(i == 0 ? "" : ",").append("{\"Key\":\"k").append(i).append("\",\"Value\":\"v\"}");
|
||||
}
|
||||
dataPlane().header("If-Match", store.dataEtag()).contentType("application/json")
|
||||
.body("{\"Puts\":[" + puts + "]}")
|
||||
.when().post(storePath(store) + "/keys")
|
||||
.then().statusCode(400).header("X-Amzn-Errortype", equalTo("ValidationException"));
|
||||
|
||||
dataPlane().header("If-Match", store.dataEtag()).contentType("application/json")
|
||||
.body("{\"Puts\":[{\"Key\":\"a\",\"Value\":\"1\"},{\"Key\":\"b\"}]}")
|
||||
.when().post(storePath(store) + "/keys")
|
||||
.then().statusCode(400).header("X-Amzn-Errortype", equalTo("ValidationException"));
|
||||
|
||||
dataPlane().when().get(storePath(store))
|
||||
.then().statusCode(200).body("ItemCount", equalTo(0)).header("ETag", equalTo(store.dataEtag()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void controlPlaneAndDataPlaneEtagsAreIndependent() {
|
||||
Store store = createStore(uniqueName(), "etags");
|
||||
|
||||
putKey(store, store.dataEtag(), "a", "1").then().statusCode(200);
|
||||
Response updated = given().contentType(XML).header("If-Match", store.etag())
|
||||
.body("<UpdateKeyValueStoreRequest xmlns=\"%s\"><Comment>changed</Comment></UpdateKeyValueStoreRequest>"
|
||||
.formatted(NS))
|
||||
.when().put(CLOUDFRONT + "key-value-store/" + store.name());
|
||||
updated.then().statusCode(200);
|
||||
|
||||
Response written = dataPlane().when().get(storePath(store));
|
||||
putKey(store, written.header("ETag"), "b", "2").then().statusCode(200).body("ItemCount", equalTo(2));
|
||||
given().header("If-Match", updated.header("ETag"))
|
||||
.when().delete(CLOUDFRONT + "key-value-store/" + store.name())
|
||||
.then().statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWithAnImportSourceIsRejectedInsteadOfCreatingAnEmptyStore() {
|
||||
String name = uniqueName();
|
||||
given().contentType(XML)
|
||||
.body(("<CreateKeyValueStoreRequest xmlns=\"%s\"><Name>%s</Name><ImportSource><SourceType>S3</SourceType>"
|
||||
+ "<SourceARN>arn:aws:s3:::bucket/keys.json</SourceARN></ImportSource></CreateKeyValueStoreRequest>")
|
||||
.formatted(NS, name))
|
||||
.when().post(CLOUDFRONT + "key-value-store")
|
||||
.then().statusCode(400).body(hasXPath("//*[local-name()='Code']", equalTo("InvalidArgument")));
|
||||
given().when().get(CLOUDFRONT + "key-value-store/" + name).then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAStoreDropsItsTags() {
|
||||
String name = uniqueName();
|
||||
Response created = given().contentType(XML)
|
||||
.body(("<CreateKeyValueStoreRequest xmlns=\"%s\"><Name>%s</Name></CreateKeyValueStoreRequest>")
|
||||
.formatted(NS, name))
|
||||
.when().post(CLOUDFRONT + "key-value-store");
|
||||
created.then().statusCode(201);
|
||||
String arn = XmlParser.extractFirst(created.asString(), "ARN", null);
|
||||
given().contentType(XML).queryParam("Operation", "Tag").queryParam("Resource", arn)
|
||||
.body("<Tags xmlns=\"%s\"><Items><Tag><Key>team</Key><Value>a</Value></Tag></Items></Tags>".formatted(NS))
|
||||
.when().post(CLOUDFRONT + "tagging").then().statusCode(204);
|
||||
|
||||
given().header("If-Match", created.header("ETag"))
|
||||
.when().delete(CLOUDFRONT + "key-value-store/" + name).then().statusCode(204);
|
||||
|
||||
given().queryParam("Resource", arn).when().get(CLOUDFRONT + "tagging")
|
||||
.then().statusCode(200).body(not(containsString("team")));
|
||||
}
|
||||
@Test
|
||||
void malformedKeyWritesAreValidationErrorsAndChangeNothing() {
|
||||
Store store = createStore(uniqueName(), "shapes");
|
||||
Response seeded = putKey(store, store.dataEtag(), "a", "1");
|
||||
seeded.then().statusCode(200);
|
||||
String etag = seeded.header("ETag");
|
||||
|
||||
String[] bodies = {"{\"Value\":{}}", "{\"Value\":5}"};
|
||||
for (String body : bodies) {
|
||||
dataPlane().header("If-Match", etag).contentType("application/json").body(body)
|
||||
.when().put(storePath(store) + "/keys/a")
|
||||
.then().statusCode(400).header("X-Amzn-Errortype", equalTo("ValidationException"));
|
||||
}
|
||||
String[] batches = {"{\"Puts\":[{\"Key\":\"a\",\"Value\":5}]}", "{\"Puts\":[{\"Key\":7,\"Value\":\"v\"}]}",
|
||||
"{\"Deletes\":\"a\"}", "{\"Puts\":{\"Key\":\"a\",\"Value\":\"v\"}}", "[]"};
|
||||
for (String body : batches) {
|
||||
dataPlane().header("If-Match", etag).contentType("application/json").body(body)
|
||||
.when().post(storePath(store) + "/keys")
|
||||
.then().statusCode(400).header("X-Amzn-Errortype", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
dataPlane().when().get(storePath(store) + "/keys/a").then().statusCode(200).body("Value", equalTo("1"));
|
||||
dataPlane().when().get(storePath(store)).then().statusCode(200).header("ETag", equalTo(etag));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listKeyValueStoresHonoursTheStatusFilter() {
|
||||
Store store = createStore(uniqueName(), "status");
|
||||
|
||||
given().queryParam("Status", "READY").when().get(CLOUDFRONT + "key-value-store")
|
||||
.then().statusCode(200).body(containsString(store.name()));
|
||||
given().queryParam("Status", "PENDING").when().get(CLOUDFRONT + "key-value-store")
|
||||
.then().statusCode(200).body(not(containsString(store.name())));
|
||||
}
|
||||
@Test
|
||||
void aMalformedMaxResultsIsAValidationError() {
|
||||
Store store = createStore(uniqueName(), "page");
|
||||
|
||||
dataPlane().queryParam("MaxResults", "abc").when().get(storePath(store) + "/keys")
|
||||
.then().statusCode(400).header("X-Amzn-Errortype", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImportSourceWithoutASourceArnIsRejectedToo() {
|
||||
String name = uniqueName();
|
||||
given().contentType(XML)
|
||||
.body(("<CreateKeyValueStoreRequest xmlns=\"%s\"><Name>%s</Name><ImportSource><SourceType>S3"
|
||||
+ "</SourceType></ImportSource></CreateKeyValueStoreRequest>").formatted(NS, name))
|
||||
.when().post(CLOUDFRONT + "key-value-store")
|
||||
.then().statusCode(400).body(hasXPath("//*[local-name()='Code']", equalTo("InvalidArgument")));
|
||||
given().when().get(CLOUDFRONT + "key-value-store/" + name).then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateKeyValueStoreWithoutACommentIsRejected() {
|
||||
Store store = createStore(uniqueName(), "kept");
|
||||
|
||||
given().contentType(XML).header("If-Match", store.etag())
|
||||
.body("<UpdateKeyValueStoreRequest xmlns=\"%s\"></UpdateKeyValueStoreRequest>".formatted(NS))
|
||||
.when().put(CLOUDFRONT + "key-value-store/" + store.name())
|
||||
.then().statusCode(400);
|
||||
given().when().get(CLOUDFRONT + "key-value-store/" + store.name())
|
||||
.then().statusCode(200).body(hasXPath("//*[local-name()='Comment']", equalTo("kept")));
|
||||
}
|
||||
@Test
|
||||
void updateKeysAppliesPutsAndDeletesAtOnce() {
|
||||
Store store = createStore(uniqueName(), "batch");
|
||||
Response seeded = dataPlane().header("If-Match", store.dataEtag()).contentType("application/json")
|
||||
.body("{\"Puts\":[{\"Key\":\"a\",\"Value\":\"1\"},{\"Key\":\"b\",\"Value\":\"2\"}]}")
|
||||
.when().post(storePath(store) + "/keys");
|
||||
seeded.then().statusCode(200).body("ItemCount", equalTo(2));
|
||||
|
||||
dataPlane().header("If-Match", seeded.header("ETag")).contentType("application/json")
|
||||
.body("{\"Puts\":[{\"Key\":\"c\",\"Value\":\"3\"}],\"Deletes\":[{\"Key\":\"a\"}]}")
|
||||
.when().post(storePath(store) + "/keys")
|
||||
.then().statusCode(200).body("ItemCount", equalTo(2));
|
||||
|
||||
dataPlane().when().get(storePath(store) + "/keys")
|
||||
.then().statusCode(200)
|
||||
.body("Items.Key", contains("b", "c"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listKeysPagesInKeyOrder() {
|
||||
Store store = createStore(uniqueName(), "paging");
|
||||
Response seeded = dataPlane().header("If-Match", store.dataEtag()).contentType("application/json")
|
||||
.body("{\"Puts\":[{\"Key\":\"c\",\"Value\":\"3\"},{\"Key\":\"a\",\"Value\":\"1\"},"
|
||||
+ "{\"Key\":\"b\",\"Value\":\"2\"}]}")
|
||||
.when().post(storePath(store) + "/keys");
|
||||
seeded.then().statusCode(200);
|
||||
|
||||
Response first = dataPlane().queryParam("MaxResults", 2).when().get(storePath(store) + "/keys");
|
||||
first.then().statusCode(200).body("Items", hasSize(2)).body("Items.Key", contains("a", "b"));
|
||||
String token = first.jsonPath().getString("NextToken");
|
||||
assertNotNull(token);
|
||||
|
||||
dataPlane().queryParam("MaxResults", 2).queryParam("NextToken", token)
|
||||
.when().get(storePath(store) + "/keys")
|
||||
.then().statusCode(200)
|
||||
.body("Items.Key", contains("c"))
|
||||
.body("NextToken", nullValue());
|
||||
|
||||
dataPlane().queryParam("MaxResults", 51).when().get(storePath(store) + "/keys")
|
||||
.then().statusCode(400).header("X-Amzn-Errortype", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void keyAndValueSizeLimitsAreValidationErrors() {
|
||||
Store store = createStore(uniqueName(), "limits");
|
||||
|
||||
putKey(store, store.dataEtag(), "k".repeat(513), "v").then().statusCode(400)
|
||||
.header("X-Amzn-Errortype", equalTo("ValidationException"));
|
||||
putKey(store, store.dataEtag(), "k", "v".repeat(1025)).then().statusCode(400)
|
||||
.header("X-Amzn-Errortype", equalTo("ValidationException"));
|
||||
putKey(store, store.dataEtag(), "k".repeat(512), "v".repeat(1024)).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownStoreArnIsResourceNotFound() {
|
||||
String arn = "arn:aws:cloudfront::000000000000:key-value-store/00000000-0000-0000-0000-000000000000";
|
||||
|
||||
dataPlane().when().get(DATA_PLANE + encoded(arn))
|
||||
.then().statusCode(404).header("X-Amzn-Errortype", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
// ── Functions ─────────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void aFunctionCanBeAssociatedWithAStoreAndTheStoreIsProtectedWhileInUse() {
|
||||
Store store = createStore(uniqueName(), "in use");
|
||||
String functionName = "fn-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
|
||||
Response function = given().contentType(XML).body(createFunction(functionName, "cloudfront-js-2.0", store.arn()))
|
||||
.when().post(CLOUDFRONT + "function");
|
||||
function.then().statusCode(201);
|
||||
assertEquals(store.arn(), XmlParser.extractFirst(function.asString(), "KeyValueStoreARN", null));
|
||||
|
||||
given().when().get(CLOUDFRONT + "function/" + functionName + "/describe")
|
||||
.then().statusCode(200)
|
||||
.body(hasXPath("//*[local-name()='KeyValueStoreAssociation']/*[local-name()='KeyValueStoreARN']",
|
||||
equalTo(store.arn())));
|
||||
given().when().get(CLOUDFRONT + "function")
|
||||
.then().statusCode(200)
|
||||
.body(hasXPath("//*[local-name()='KeyValueStoreARN'][text()='" + store.arn() + "']"));
|
||||
|
||||
given().header("If-Match", store.etag())
|
||||
.when().delete(CLOUDFRONT + "key-value-store/" + store.name())
|
||||
.then().statusCode(409)
|
||||
.body(hasXPath("//*[local-name()='Code']", equalTo("CannotDeleteEntityWhileInUse")));
|
||||
|
||||
given().header("If-Match", function.header("ETag"))
|
||||
.when().delete(CLOUDFRONT + "function/" + functionName)
|
||||
.then().statusCode(204);
|
||||
given().header("If-Match", store.etag())
|
||||
.when().delete(CLOUDFRONT + "key-value-store/" + store.name())
|
||||
.then().statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFunctionCannotUseAnUnknownStoreOrTheFirstRuntime() {
|
||||
Store store = createStore(uniqueName(), "runtime");
|
||||
String unknownArn = "arn:aws:cloudfront::000000000000:key-value-store/00000000-0000-0000-0000-000000000000";
|
||||
|
||||
given().contentType(XML)
|
||||
.body(createFunction("fn-" + UUID.randomUUID().toString().substring(0, 8), "cloudfront-js-2.0", unknownArn))
|
||||
.when().post(CLOUDFRONT + "function")
|
||||
.then().statusCode(404).body(hasXPath("//*[local-name()='Code']", equalTo("EntityNotFound")));
|
||||
given().contentType(XML)
|
||||
.body(createFunction("fn-" + UUID.randomUUID().toString().substring(0, 8), "cloudfront-js-1.0", store.arn()))
|
||||
.when().post(CLOUDFRONT + "function")
|
||||
.then().statusCode(400).body(hasXPath("//*[local-name()='Code']", equalTo("InvalidArgument")));
|
||||
}
|
||||
}
|
||||
+344
@@ -0,0 +1,344 @@
|
||||
package io.floci.aws.services.cloudfront;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.cloudfront.model.KeyValueStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class CloudFrontKeyValueStoreServiceTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
private CloudFrontKeyValueStoreService newService() {
|
||||
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
|
||||
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
|
||||
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory(ACCOUNT));
|
||||
return new CloudFrontKeyValueStoreService(storageFactory, new RegionResolver("us-east-1", ACCOUNT));
|
||||
}
|
||||
|
||||
private static void assertError(String code, int status, Runnable action) {
|
||||
AwsException e = assertThrows(AwsException.class, action::run);
|
||||
assertEquals(code, e.getErrorCode());
|
||||
assertEquals(status, e.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStoresAReadyStoreWithAnArnAndAnEtag() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
|
||||
KeyValueStore created = service.create("tenants", "tenant to version");
|
||||
|
||||
assertEquals("tenants", created.getName());
|
||||
assertEquals("READY", created.getStatus());
|
||||
assertEquals("tenant to version", created.getComment());
|
||||
assertEquals("arn:aws:cloudfront::" + ACCOUNT + ":key-value-store/" + created.getId(), created.getArn());
|
||||
assertTrue(created.getItems().isEmpty());
|
||||
assertEquals(created.getArn(), service.findByArn(created.getArn()).orElseThrow().getArn());
|
||||
assertEquals(created.getEtag(), service.describe("tenants").getEtag());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRejectsAnInvalidNameADuplicateAndAnOverlongComment() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
service.create("tenants", null);
|
||||
|
||||
assertError("EntityAlreadyExists", 409, () -> service.create("tenants", null));
|
||||
assertError("InvalidArgument", 400, () -> service.create("bad name!", null));
|
||||
assertError("InvalidArgument", 400, () -> service.create("", null));
|
||||
assertError("InvalidArgument", 400, () -> service.create("a".repeat(65), null));
|
||||
assertError("InvalidArgument", 400, () -> service.create("commented", "c".repeat(129)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeOfAnUnknownStoreIsEntityNotFound() {
|
||||
assertError("EntityNotFound", 404, () -> newService().describe("missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateNeedsTheCurrentEtagAndRotatesIt() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", "one");
|
||||
String firstEtag = created.getEtag();
|
||||
|
||||
assertError("InvalidIfMatchVersion", 400, () -> service.update("tenants", "stale", "two"));
|
||||
assertError("InvalidIfMatchVersion", 400, () -> service.update("tenants", null, "two"));
|
||||
|
||||
KeyValueStore updated = service.update("tenants", firstEtag, "two");
|
||||
|
||||
assertEquals("two", updated.getComment());
|
||||
assertNotEquals(firstEtag, updated.getEtag());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteNeedsTheCurrentEtag() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", null);
|
||||
|
||||
assertError("InvalidIfMatchVersion", 400, () -> service.delete("tenants", "stale"));
|
||||
service.delete("tenants", created.getEtag());
|
||||
|
||||
assertError("EntityNotFound", 404, () -> service.describe("tenants"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listIsOrderedByNameAndPagesWithAMarker() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
service.create("gamma", null);
|
||||
service.create("alpha", null);
|
||||
service.create("beta", null);
|
||||
|
||||
List<KeyValueStore> firstPage = service.list(null, 2, null);
|
||||
List<KeyValueStore> secondPage = service.list("beta", 2, null);
|
||||
|
||||
assertEquals(List.of("alpha", "beta"), firstPage.stream().map(KeyValueStore::getName).toList());
|
||||
assertEquals(List.of("gamma"), secondPage.stream().map(KeyValueStore::getName).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putKeyThenGetKeyRoundTripsAndCountsBytes() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", null);
|
||||
|
||||
KeyValueStore written = service.putKey(created.getArn(), created.getDataEtag(), "demo.example.com", "3-5-19-1234");
|
||||
|
||||
assertEquals("3-5-19-1234", service.getKey(created.getArn(), "demo.example.com").value());
|
||||
assertEquals(1, CloudFrontKeyValueStoreService.itemCount(written));
|
||||
assertEquals("demo.example.com".length() + "3-5-19-1234".length(),
|
||||
CloudFrontKeyValueStoreService.totalSizeInBytes(written));
|
||||
assertNotEquals(created.getDataEtag(), written.getDataEtag());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sizeIsCountedInUtf8Bytes() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", null);
|
||||
|
||||
KeyValueStore written = service.putKey(created.getArn(), created.getDataEtag(), "k", "é");
|
||||
|
||||
assertEquals(1 + 2, CloudFrontKeyValueStoreService.totalSizeInBytes(written));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDataPlaneWriteWithAStaleOrMissingEtagIsRejected() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", null);
|
||||
String arn = created.getArn();
|
||||
service.putKey(arn, created.getDataEtag(), "a", "1");
|
||||
|
||||
assertError("ValidationException", 400, () -> service.putKey(arn, created.getDataEtag(), "b", "2"));
|
||||
assertError("ValidationException", 400, () -> service.putKey(arn, null, "b", "2"));
|
||||
assertNull(service.describeByArn(arn).getItems().get("b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theControlPlaneAndDataPlaneKeepIndependentEtags() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", "one");
|
||||
|
||||
KeyValueStore updated = service.update("tenants", created.getEtag(), "two");
|
||||
assertNotEquals(created.getEtag(), updated.getEtag());
|
||||
assertEquals(created.getDataEtag(), updated.getDataEtag());
|
||||
KeyValueStore written = service.putKey(created.getArn(), created.getDataEtag(), "a", "1");
|
||||
assertEquals(updated.getEtag(), written.getEtag());
|
||||
assertNotEquals(created.getDataEtag(), written.getDataEtag());
|
||||
|
||||
service.delete("tenants", updated.getEtag());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUsesTheRequestAccountInTheArn() {
|
||||
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
|
||||
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
|
||||
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory(ACCOUNT));
|
||||
RegionResolver resolver = Mockito.spy(new RegionResolver("us-east-1", ACCOUNT));
|
||||
when(resolver.getAccountId()).thenReturn("111122223333");
|
||||
CloudFrontKeyValueStoreService service = new CloudFrontKeyValueStoreService(storageFactory, resolver);
|
||||
|
||||
KeyValueStore created = service.create("tenants", null);
|
||||
|
||||
assertTrue(created.getArn().startsWith("arn:aws:cloudfront::111122223333:key-value-store/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRejectsPunctuationAndStopsAtTwoHundredStores() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
assertError("InvalidArgument", 400, () -> service.create("a?b", null));
|
||||
assertError("InvalidArgument", 400, () -> service.create("a\\b", null));
|
||||
assertError("InvalidArgument", 400, () -> service.create("a:b", null));
|
||||
|
||||
for (int i = 0; i < CloudFrontKeyValueStoreService.MAX_STORES; i++) {
|
||||
service.create("store-" + i, null);
|
||||
}
|
||||
|
||||
assertError("EntityLimitExceeded", 400, () -> service.create("one-too-many", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownStoreArnIsResourceNotFoundOnTheDataPlane() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
String arn = "arn:aws:cloudfront::" + ACCOUNT + ":key-value-store/00000000-0000-0000-0000-000000000000";
|
||||
|
||||
assertError("ResourceNotFoundException", 404, () -> service.describeByArn(arn));
|
||||
assertError("ResourceNotFoundException", 404, () -> service.getKey(arn, "a"));
|
||||
assertError("ResourceNotFoundException", 404, () -> service.putKey(arn, "etag", "a", "1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMissingKeyIsResourceNotFound() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", null);
|
||||
|
||||
assertError("ResourceNotFoundException", 404, () -> service.getKey(created.getArn(), "missing"));
|
||||
assertError("ResourceNotFoundException", 404,
|
||||
() -> service.deleteKey(created.getArn(), created.getDataEtag(), "missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void keyAndValueLimitsAreEnforcedInBytes() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", null);
|
||||
String arn = created.getArn();
|
||||
String etag = created.getDataEtag();
|
||||
|
||||
assertError("ValidationException", 400, () -> service.putKey(arn, etag, "k".repeat(513), "v"));
|
||||
assertError("ValidationException", 400, () -> service.putKey(arn, etag, "k", "v".repeat(1025)));
|
||||
assertError("ValidationException", 400, () -> service.putKey(arn, etag, "", "v"));
|
||||
|
||||
KeyValueStore atTheLimit = service.putKey(arn, etag, "k".repeat(512), "v".repeat(1024));
|
||||
assertEquals(1, CloudFrontKeyValueStoreService.itemCount(atTheLimit));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStoreCannotGrowPastFiveMebibytes() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", null);
|
||||
Map<String, String> puts = new LinkedHashMap<>();
|
||||
for (int i = 0; i < 5200; i++) {
|
||||
puts.put("key-%05d".formatted(i), "v".repeat(1024));
|
||||
}
|
||||
|
||||
assertError("ServiceQuotaExceededException", 402,
|
||||
() -> service.updateKeys(created.getArn(), created.getDataEtag(), puts, List.of()));
|
||||
assertTrue(service.describeByArn(created.getArn()).getItems().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBatchIsAtomicWhenOneEntryIsInvalid() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", null);
|
||||
Map<String, String> puts = new LinkedHashMap<>();
|
||||
puts.put("good", "1");
|
||||
puts.put("bad", "v".repeat(1025));
|
||||
|
||||
assertError("ValidationException", 400,
|
||||
() -> service.updateKeys(created.getArn(), created.getDataEtag(), puts, List.of()));
|
||||
|
||||
KeyValueStore unchanged = service.describeByArn(created.getArn());
|
||||
assertTrue(unchanged.getItems().isEmpty());
|
||||
assertEquals(created.getDataEtag(), unchanged.getDataEtag());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBatchAppliesPutsAndDeletesTogetherAndSkipsDeletesOfAbsentKeys() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", null);
|
||||
KeyValueStore first = service.updateKeys(created.getArn(), created.getDataEtag(),
|
||||
Map.of("a", "1", "b", "2"), List.of());
|
||||
|
||||
KeyValueStore second = service.updateKeys(created.getArn(), first.getDataEtag(),
|
||||
Map.of("c", "3"), List.of("a", "never-existed"));
|
||||
|
||||
assertEquals(List.of("b", "c"), new ArrayList<>(new TreeMap<>(second.getItems()).keySet()));
|
||||
assertNotEquals(first.getDataEtag(), second.getDataEtag());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listKeysIsSortedAndPagesWithAToken() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", null);
|
||||
Map<String, String> puts = new LinkedHashMap<>();
|
||||
for (String key : List.of("echo", "alpha", "delta", "bravo", "charlie")) {
|
||||
puts.put(key, key.toUpperCase());
|
||||
}
|
||||
service.updateKeys(created.getArn(), created.getDataEtag(), puts, List.of());
|
||||
|
||||
CloudFrontKeyValueStoreService.KeyPage first = service.listKeys(created.getArn(), null, 2);
|
||||
CloudFrontKeyValueStoreService.KeyPage second = service.listKeys(created.getArn(), first.nextToken(), 2);
|
||||
CloudFrontKeyValueStoreService.KeyPage third = service.listKeys(created.getArn(), second.nextToken(), 2);
|
||||
|
||||
assertEquals(List.of("alpha", "bravo"), first.items().stream().map(Map.Entry::getKey).toList());
|
||||
assertEquals(List.of("charlie", "delta"), second.items().stream().map(Map.Entry::getKey).toList());
|
||||
assertEquals(List.of("echo"), third.items().stream().map(Map.Entry::getKey).toList());
|
||||
assertNull(third.nextToken());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listKeysValidatesMaxResultsAndTheToken() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", null);
|
||||
|
||||
assertError("ValidationException", 400, () -> service.listKeys(created.getArn(), null, 0));
|
||||
assertError("ValidationException", 400, () -> service.listKeys(created.getArn(), null, 51));
|
||||
assertError("ValidationException", 400, () -> service.listKeys(created.getArn(), "!!not base64!!", 10));
|
||||
assertEquals(10, CloudFrontKeyValueStoreService.DEFAULT_LIST_KEYS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listResumesAfterAMarkerStoreThatWasDeleted() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
service.create("a", null);
|
||||
KeyValueStore b = service.create("b", null);
|
||||
service.create("c", null);
|
||||
service.delete("b", b.getEtag());
|
||||
|
||||
List<KeyValueStore> page = service.list("b", 10, null);
|
||||
|
||||
assertEquals(List.of("c"), page.stream().map(KeyValueStore::getName).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWithoutACommentIsRejectedAndKeepsTheStore() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", "keep me");
|
||||
|
||||
assertError("InvalidArgument", 400, () -> service.update("tenants", created.getEtag(), null));
|
||||
|
||||
KeyValueStore unchanged = service.describe("tenants");
|
||||
assertEquals("keep me", unchanged.getComment());
|
||||
assertEquals(created.getEtag(), unchanged.getEtag());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findResolvesAStoreNameToItsStoredArn() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
KeyValueStore created = service.create("tenants", null);
|
||||
|
||||
assertEquals(created.getArn(), service.find("key-value-store", List.of("tenants"), "us-east-1").orElseThrow());
|
||||
assertTrue(service.find("key-value-store", List.of("missing"), "us-east-1").isEmpty());
|
||||
assertTrue(service.find("distribution", List.of("tenants"), "us-east-1").isEmpty());
|
||||
}
|
||||
@Test
|
||||
void listFiltersByStatus() {
|
||||
CloudFrontKeyValueStoreService service = newService();
|
||||
service.create("a", null);
|
||||
service.create("b", null);
|
||||
|
||||
assertEquals(2, service.list(null, 10, "READY").size());
|
||||
assertTrue(service.list(null, 10, "PENDING").isEmpty());
|
||||
}}
|
||||
@@ -1,11 +1,13 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.core.common.XmlParser;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -16,6 +18,7 @@ import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
@@ -71,6 +74,49 @@ class IamRestRouteEnforcementIntegrationTest {
|
||||
.get("/2018-10-31/layers").then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cloudFrontKeyValueStoreDataPlaneRoutesAreCheckedByOperation() {
|
||||
String user = user("route-kvs");
|
||||
String arn = "arn:aws:cloudfront::" + ACCOUNT + ":key-value-store/" + UUID.randomUUID();
|
||||
String path = "/key-value-stores/" + URLEncoder.encode(arn, StandardCharsets.UTF_8);
|
||||
|
||||
policy(user, allow("cloudfront-keyvaluestore:ListKeys", "*"));
|
||||
refused(as(user, "cloudfront-keyvaluestore").urlEncodingEnabled(false).get(path).then(),
|
||||
"cloudfront-keyvaluestore:DescribeKeyValueStore");
|
||||
refused(as(user, "cloudfront-keyvaluestore").urlEncodingEnabled(false).header("If-Match", "etag")
|
||||
.body("{\"Value\":\"v\"}").put(path + "/keys/k").then(), "cloudfront-keyvaluestore:PutKey");
|
||||
|
||||
policy(user, allow("cloudfront-keyvaluestore:DescribeKeyValueStore", arn));
|
||||
// Allowed on that store, the request reaches the data plane, which has no such store.
|
||||
as(user, "cloudfront-keyvaluestore").urlEncodingEnabled(false).get(path).then().statusCode(404);
|
||||
}
|
||||
@Test
|
||||
void cloudFrontKeyValueStoreControlPlaneIsCheckedAgainstTheStoresReturnedArn() {
|
||||
String user = user("route-kvs-control");
|
||||
String name = "kvs-" + suffix();
|
||||
String namespace = "http://cloudfront.amazonaws.com/doc/2020-05-31/";
|
||||
Response created = given().header("Authorization", auth(ADMIN, "cloudfront"))
|
||||
.contentType("application/xml")
|
||||
.body("<CreateKeyValueStoreRequest xmlns=\"" + namespace + "\"><Name>" + name
|
||||
+ "</Name></CreateKeyValueStoreRequest>")
|
||||
.post("/2020-05-31/key-value-store");
|
||||
created.then().statusCode(201);
|
||||
String arn = XmlParser.extractFirst(created.asString(), "ARN", null);
|
||||
String etag = created.header("ETag");
|
||||
|
||||
policy(user, allow("cloudfront:*", "*") + "," +
|
||||
"{\"Effect\":\"Deny\",\"Action\":\"cloudfront:DeleteKeyValueStore\",\"Resource\":\"" + arn + "\"}");
|
||||
refused(as(user, "cloudfront").header("If-Match", etag).delete("/2020-05-31/key-value-store/" + name).then(),
|
||||
"cloudfront:DeleteKeyValueStore");
|
||||
as(user, "cloudfront").get("/2020-05-31/key-value-store/" + name).then().statusCode(200);
|
||||
|
||||
policy(user, allow("cloudfront:DescribeKeyValueStore", "arn:aws:cloudfront::" + ACCOUNT
|
||||
+ ":key-value-store/not-this-one"));
|
||||
refused(as(user, "cloudfront").get("/2020-05-31/key-value-store/" + name).then(),
|
||||
"cloudfront:DescribeKeyValueStore");
|
||||
policy(user, allow("cloudfront:DescribeKeyValueStore", arn));
|
||||
as(user, "cloudfront").get("/2020-05-31/key-value-store/" + name).then().statusCode(200);
|
||||
}
|
||||
@Test
|
||||
void aScheduleRequestSignedForAnotherServiceIsStillCheckedAsScheduler() {
|
||||
// Checked by the route it reached, not by the credential scope it was signed with: an S3
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Vendor the CloudFront KeyValueStore data plane request constraints from botocore's Apache-2.0 service model.
|
||||
|
||||
`CloudFrontKeyValueStoreRequestShapes` checks the data plane's actions against the vendored file
|
||||
through the shared `RequestConstraintCheck`: member types, required members, lengths and counts,
|
||||
patterns and enum values, as the model states them. The request it checks is the whole request as
|
||||
the model reads it: the members the path, the `If-Match` header, the query and the body carry.
|
||||
The quotas the model does not state (the size of a key in bytes, of a store, of an update) stay
|
||||
in `CloudFrontKeyValueStoreService`.
|
||||
|
||||
The data plane is a service of its own, so its constraints are vendored in a file of their own.
|
||||
|
||||
Run from anywhere in the repo:
|
||||
python3 tools/aws/regen_cloudfront_keyvaluestore_shapes.py # rewrite the vendored file in place
|
||||
python3 tools/aws/regen_cloudfront_keyvaluestore_shapes.py --check # exit 1 when the vendored file is stale
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import request_shapes
|
||||
|
||||
OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/cloudfront-keyvaluestore-request-shapes.json"
|
||||
MODEL = Path("cloudfront-keyvaluestore/2022-07-26")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT,
|
||||
description=__doc__,
|
||||
constraints=True,
|
||||
prepare=request_shapes.widen_partition_and_region)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -171,7 +171,7 @@ OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-request-resources.json"
|
||||
# The namespaces read, in batches: each moves here from NOT_COVERED with the tests that show its ARNs
|
||||
# are the ones its handlers mint.
|
||||
NAMESPACES = ("access-analyzer", "acm", "application-autoscaling", "athena", "bcm-data-exports",
|
||||
"bcm-pricing-calculator", "budgets", "ce", "cloudfront", "cloudtrail", "codebuild", "codepipeline", "cognito-identity",
|
||||
"bcm-pricing-calculator", "budgets", "ce", "cloudfront", "cloudfront-keyvaluestore", "cloudtrail", "codebuild", "codepipeline", "cognito-identity",
|
||||
"cognito-idp", "controltower", "cur", "datasync", "ec2", "ecr", "elasticloadbalancing", "elasticmapreduce", "es", "events",
|
||||
"firehose", "globalaccelerator", "inspector2", "kinesisanalytics", "macie2", "payment-cryptography",
|
||||
"quicksight", "redshift", "redshift-data", "redshift-serverless", "rekognition", "servicediscovery",
|
||||
|
||||
@@ -55,6 +55,7 @@ MODELS: dict[str, str] = {
|
||||
"apigateway": "apigateway",
|
||||
"apigatewayv2": "apigateway",
|
||||
"cloudfront": "cloudfront",
|
||||
"cloudfront-keyvaluestore": "cloudfront-keyvaluestore",
|
||||
"controltower": "controltower",
|
||||
"dsql": "dsql",
|
||||
"eks": "eks",
|
||||
|
||||
@@ -27,6 +27,7 @@ import regen_ecr_shapes
|
||||
import regen_ecs_shapes
|
||||
import regen_emr_serverless_shapes
|
||||
import regen_iam_shapes
|
||||
import regen_cloudfront_keyvaluestore_shapes
|
||||
import regen_kinesis_shapes
|
||||
import regen_lambda_microvm_shapes
|
||||
import regen_payment_cryptography_data_shapes
|
||||
@@ -410,6 +411,8 @@ def test_each_constraints_script_runs_the_shared_main_with_its_operations(script
|
||||
"payment-cryptography-request-shapes.json"),
|
||||
(regen_payment_cryptography_data_shapes, "payment-cryptography-data/2022-02-03",
|
||||
"payment-cryptography-data-request-shapes.json"),
|
||||
(regen_cloudfront_keyvaluestore_shapes, "cloudfront-keyvaluestore/2022-07-26",
|
||||
"cloudfront-keyvaluestore-request-shapes.json"),
|
||||
])
|
||||
def test_each_payment_cryptography_script_runs_the_shared_main_with_every_operation(script, model, output,
|
||||
monkeypatch):
|
||||
@@ -456,6 +459,7 @@ def test_each_vendored_constraints_file_carries_its_operations_and_resolves_its_
|
||||
|
||||
@pytest.mark.parametrize("script", [
|
||||
regen_payment_cryptography_shapes, regen_payment_cryptography_data_shapes,
|
||||
regen_cloudfront_keyvaluestore_shapes,
|
||||
])
|
||||
def test_each_payment_cryptography_file_carries_every_operation_the_model_names(script):
|
||||
# The generator names no operation, so the file carries every operation the model names:
|
||||
|
||||
@@ -53,6 +53,7 @@ aliases:
|
||||
iotdata: iot # IoT Data row shares iot.md with IoT Core
|
||||
resource-explorer-2: resource-explorer # API version suffix; the page is resource-explorer.md
|
||||
bedrock-agentcore-control: bedrock-agentcore # control plane owns the page; the data-plane row is the facet
|
||||
cloudfront-keyvaluestore: cloudfront # data-plane facet, at cloudfront.md#key-value-stores
|
||||
|
||||
# A NEW switch/REST descriptor not listed here and not resolvable via an alias fails
|
||||
# `--strict`. Every entry MUST carry a `by:` expiry date (ISO, YYYY-MM-DD): once that
|
||||
|
||||
Reference in new issue
Block a user