fix(cloudfront): separate DEVELOPMENT and LIVE function stages (#2622)

This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-08-29 14:33:00 -04:00
1 parent 67f75c7e1d
commit 0dfec3cf3c
5 files changed
+251 -19

No files matched your search

+2 -1
View File
@@ -94,7 +94,8 @@ GET/HEAD/OPTIONS delivery from S3 or custom origins.
| Operation | Method | Path |
|---|---|---|
| `CreateFunction` | POST | `/2020-05-31/function` |
| `DescribeFunction` | GET | `/2020-05-31/function/{Name}` |
| `GetFunction` | GET | `/2020-05-31/function/{Name}` |
| `DescribeFunction` | GET | `/2020-05-31/function/{Name}/describe` |
| `UpdateFunction` | PUT | `/2020-05-31/function/{Name}` |
| `PublishFunction` | POST | `/2020-05-31/function/{Name}/publish` |
| `DeleteFunction` | DELETE | `/2020-05-31/function/{Name}` |
@@ -29,6 +29,7 @@ public class CloudFrontController {
private static final String NS = AwsNamespaces.CLOUDFRONT;
private static final String XML = "application/xml";
private static final String OCTET_STREAM = "application/octet-stream";
private static final String GEO_RESTRICTION = "GeoRestriction";
private static final String ORIGIN_GROUPS = "OriginGroups";
private static final String ITEMS = "Items";
@@ -854,6 +855,20 @@ public class CloudFrontController {
@GET
@Path("/function/{Name}")
public Response getFunction(@PathParam("Name") String name,
@QueryParam("Stage") String stage) {
try {
CloudFrontFunction fn = service.describeFunction(name, stage);
return Response.ok(fn.getFunctionCode() != null ? fn.getFunctionCode() : "", OCTET_STREAM)
.header("ETag", fn.getEtag())
.build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@GET
@Path("/function/{Name}/describe")
public Response describeFunction(@PathParam("Name") String name,
@QueryParam("Stage") String stage) {
try {
@@ -32,6 +32,7 @@ import jakarta.inject.Inject;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
@@ -39,6 +40,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
@@ -1068,14 +1070,16 @@ public class CloudFrontService {
}
public CloudFrontFunction describeFunction(String name, String stage) {
CloudFrontFunction fn = functionStore.get(name).orElseThrow(() ->
String effectiveStage = normalizeFunctionStage(stage);
Optional<CloudFrontFunction> function = functionStore.get(functionKey(name, effectiveStage));
if (function.isEmpty() && "LIVE".equals(effectiveStage)) {
// Releases before stage-aware keys stored a published LIVE function under
// the bare name. Keep that state readable without exposing it as DEVELOPMENT.
function = functionStore.get(name).filter(fn -> "LIVE".equals(fn.getStage()));
}
return function.filter(fn -> effectiveStage.equals(fn.getStage())).orElseThrow(() ->
new AwsException("NoSuchFunctionExists",
"The specified function does not exist.", 404));
if (stage != null && !stage.isEmpty() && !fn.getStage().equals(stage)) {
throw new AwsException("NoSuchFunctionExists",
"The specified function does not exist.", 404);
}
return fn;
}
public synchronized CloudFrontFunction updateFunction(String name, String ifMatch,
@@ -1096,38 +1100,81 @@ public class CloudFrontService {
}
public synchronized CloudFrontFunction publishFunction(String name, String ifMatch) {
CloudFrontFunction fn = describeFunction(name, null);
if (!fn.getEtag().equals(ifMatch)) {
CloudFrontFunction development = describeFunction(name, "DEVELOPMENT");
if (!development.getEtag().equals(ifMatch)) {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
}
fn.setStage("LIVE");
fn.setStatus("DEPLOYED");
fn.setEtag(UUID.randomUUID().toString());
fn.setLastModifiedTime(Instant.now());
functionStore.put(name, fn);
return fn;
CloudFrontFunction live = copyFunction(development);
live.setStage("LIVE");
live.setStatus("DEPLOYED");
live.setEtag(UUID.randomUUID().toString());
live.setLastModifiedTime(Instant.now());
functionStore.put(functionKey(name, "LIVE"), live);
return live;
}
public synchronized void deleteFunction(String name, String ifMatch) {
CloudFrontFunction existing = describeFunction(name, null);
CloudFrontFunction existing = functionStore.get(name)
.or(() -> functionStore.get(functionKey(name, "LIVE")))
.orElseThrow(() -> new AwsException("NoSuchFunctionExists",
"The specified function does not exist.", 404));
if (!existing.getEtag().equals(ifMatch)) {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
}
functionStore.delete(name);
functionStore.delete(functionKey(name, "LIVE"));
}
public List<CloudFrontFunction> listFunctions(String stage, String marker, int maxItems) {
List<CloudFrontFunction> all = new ArrayList<>(functionStore.scan(k -> true));
if (stage != null && !stage.isEmpty()) {
all = all.stream().filter(f -> stage.equals(f.getStage())).toList();
all = new ArrayList<>(all);
String effectiveStage = normalizeFunctionStage(stage);
all = new ArrayList<>(all.stream()
.filter(f -> effectiveStage.equals(f.getStage()))
.toList());
}
all.sort((a, b) -> a.getName().compareTo(b.getName()));
all.sort(Comparator.comparing(CloudFrontFunction::getName)
.thenComparing(CloudFrontFunction::getStage));
return paginate(all, marker, maxItems, CloudFrontFunction::getName);
}
private static String functionKey(String name, String stage) {
return switch (stage) {
case "DEVELOPMENT" -> name;
case "LIVE" -> name + "::LIVE";
default -> throw invalidFunctionStage(stage);
};
}
private static String normalizeFunctionStage(String stage) {
String effectiveStage = stage == null || stage.isEmpty() ? "DEVELOPMENT" : stage;
if (!"DEVELOPMENT".equals(effectiveStage) && !"LIVE".equals(effectiveStage)) {
throw invalidFunctionStage(effectiveStage);
}
return effectiveStage;
}
private static AwsException invalidFunctionStage(String stage) {
return new AwsException("InvalidArgument",
"The parameter Stage must be DEVELOPMENT or LIVE: " + stage, 400);
}
private static CloudFrontFunction copyFunction(CloudFrontFunction source) {
CloudFrontFunction copy = new CloudFrontFunction();
copy.setName(source.getName());
copy.setStage(source.getStage());
copy.setStatus(source.getStatus());
copy.setFunctionCode(source.getFunctionCode());
copy.setRuntime(source.getRuntime());
copy.setComment(source.getComment());
copy.setEtag(source.getEtag());
copy.setCreatedTime(source.getCreatedTime());
copy.setLastModifiedTime(source.getLastModifiedTime());
return copy;
}
// ── Tags ──────────────────────────────────────────────────────────────────
public Map<String, String> listTagsForResource(String arn) {
@@ -6,6 +6,8 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
@@ -105,6 +107,87 @@ class CloudFrontManagementProtocolTest {
equalTo("InvalidArgument")));
}
@Test
void describeAndPublishFunctionPreserveBothStages() {
String name = "describe-test-" + UUID.randomUUID();
String createBody = """
<CreateFunctionRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
<Name>%s</Name>
<FunctionConfig>
<Comment>routing function</Comment>
<Runtime>cloudfront-js-2.0</Runtime>
</FunctionConfig>
<FunctionCode>function handler(event) { return event.request; }</FunctionCode>
</CreateFunctionRequest>
""".formatted(name);
String developmentEtag = given()
.contentType("application/xml")
.body(createBody)
.when()
.post(API + "function")
.then()
.statusCode(201)
.extract().header("ETag");
given()
.queryParam("Stage", "DEVELOPMENT")
.when()
.get(API + "function/" + name + "/describe")
.then()
.statusCode(200)
.header("ETag", equalTo(developmentEtag))
.body(hasXPath("//*[local-name()='Stage']/text()", equalTo("DEVELOPMENT")));
given()
.header("If-Match", developmentEtag)
.when()
.post(API + "function/" + name + "/publish")
.then()
.statusCode(200)
.body(hasXPath("//*[local-name()='Stage']/text()", equalTo("LIVE")));
given()
.queryParam("Stage", "DEVELOPMENT")
.when()
.get(API + "function/" + name + "/describe")
.then()
.statusCode(200)
.header("ETag", equalTo(developmentEtag));
given()
.queryParam("Stage", "LIVE")
.when()
.get(API + "function/" + name + "/describe")
.then()
.statusCode(200)
.body(hasXPath("//*[local-name()='Stage']/text()", equalTo("LIVE")));
given()
.queryParam("Stage", "TESTING")
.when()
.get(API + "function/" + name + "/describe")
.then()
.statusCode(400)
.body(hasXPath("//*[local-name()='Code']/text()", equalTo("InvalidArgument")));
given()
.queryParam("Stage", "DEVELOPMENT")
.when()
.get(API + "function/" + name)
.then()
.statusCode(200)
.contentType("application/octet-stream")
.body(equalTo("function handler(event) { return event.request; }"));
given()
.header("If-Match", developmentEtag)
.when()
.delete(API + "function/" + name)
.then()
.statusCode(204);
}
@Test
void createOriginAccessControlDoesNotDefaultRequiredConfiguration() {
String body = """
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudfront.model.CacheBehavior;
import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontFunction;
import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontOriginAccessIdentity;
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
@@ -32,6 +33,7 @@ import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
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;
@@ -133,6 +135,90 @@ class CloudFrontServiceTest {
return new CloudFrontService(storageFactory, config);
}
@Test
void publishFunctionCopiesDevelopmentToLive() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
CloudFrontFunction function = new CloudFrontFunction();
function.setName("routing");
function.setFunctionCode("function handler(event) { return event.request; }");
function.setRuntime("cloudfront-js-2.0");
function.setComment("routing function");
CloudFrontFunction development = service.createFunction(function);
CloudFrontFunction live = service.publishFunction(function.getName(), development.getEtag());
CloudFrontFunction describedDevelopment = service.describeFunction(function.getName(), "DEVELOPMENT");
CloudFrontFunction describedLive = service.describeFunction(function.getName(), "LIVE");
assertEquals("DEVELOPMENT", describedDevelopment.getStage());
assertEquals("LIVE", describedLive.getStage());
assertEquals(development.getFunctionCode(), describedLive.getFunctionCode());
assertEquals(development.getEtag(), describedDevelopment.getEtag());
assertNotEquals(development.getEtag(), live.getEtag());
}
@Test
void listFunctionsWithoutStageReturnsDevelopmentAndLive() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
CloudFrontFunction function = new CloudFrontFunction();
function.setName("routing");
CloudFrontFunction development = service.createFunction(function);
service.publishFunction(function.getName(), development.getEtag());
assertEquals(List.of("DEVELOPMENT", "LIVE"), service.listFunctions(null, null, LIST_MAX_ITEMS)
.stream()
.map(CloudFrontFunction::getStage)
.toList());
}
@Test
void functionStageLookupRejectsUnsupportedValues() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
CloudFrontFunction function = new CloudFrontFunction();
function.setName("routing");
service.createFunction(function);
AwsException error = assertThrows(AwsException.class,
() -> service.describeFunction(function.getName(), "TESTING"));
assertEquals("InvalidArgument", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void legacyLiveFunctionIsNeverReturnedAsDevelopment() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
CloudFrontFunction function = new CloudFrontFunction();
function.setName("legacy-routing");
CloudFrontFunction legacyLive = service.createFunction(function);
legacyLive.setStage("LIVE");
legacyLive.setStatus("DEPLOYED");
AwsException developmentError = assertThrows(AwsException.class,
() -> service.describeFunction(function.getName(), "DEVELOPMENT"));
assertEquals("NoSuchFunctionExists", developmentError.getErrorCode());
assertEquals(legacyLive, service.describeFunction(function.getName(), "LIVE"));
AwsException publishError = assertThrows(AwsException.class,
() -> service.publishFunction(function.getName(), legacyLive.getEtag()));
assertEquals("NoSuchFunctionExists", publishError.getErrorCode());
}
@Test
void legacyLiveFunctionCanBeDeleted() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
CloudFrontFunction function = new CloudFrontFunction();
function.setName("legacy-routing");
CloudFrontFunction legacyLive = service.createFunction(function);
legacyLive.setStage("LIVE");
legacyLive.setStatus("DEPLOYED");
service.deleteFunction(function.getName(), legacyLive.getEtag());
AwsException error = assertThrows(AwsException.class,
() -> service.describeFunction(function.getName(), "LIVE"));
assertEquals("NoSuchFunctionExists", error.getErrorCode());
}
@Test
void createDistributionUsesDefaultDomainSuffix() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");