feat(cloudfront): add CloudFront KeyValueStore support (#8108)

This commit is contained in:
Roger Far authored and GitHub committed 2026-11-12 14:19:52 -04:00
1 parent 2beb3b6c0d
commit 9831603f67
25 files changed
+2021 -17

No files matched your search

@@ -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;
}
@@ -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();
}
}
@@ -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; }
}