fix(cloudfront): return the decoded function code from GetFunction (#6798)

* fix(cloudfront): return the decoded function code from GetFunction

GetFunction wrote the stored base64 text into the response body where
AWS returns the code the request carried, so reading back what you sent
gave different bytes. The body is the decoded code now, with the
octet-stream content type and the ETag header unchanged; the
CloudFormation provisioner base64-encodes the template's plain code so
the stored form stays the wire form, and GetFunction is the single
decode point.

Closes #6749

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(cloudfront): read a plain-code record persisted by an older Floci version

GetFunction served a 400 for a stored code that was not base64, and an
upgrade over persistent storage kept the records older Floci writes
wrote the CloudFormation provisioner as plain text, so those functions
stopped serving their code. A non-base64 record now reads back as its
stored bytes, and the next UpdateFunction rewrites it into the uniform
base64 form. The compat round-trip test captures the updated etag
before asserting so a failed assertion cannot hijack the cleanup's
delete.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* test(cloudfront): read the ETag update header the model names and rebase the decoded-code management tests

The decoded-code round trip asserts UpdateFunction answers the version
in the ETag header the SDK models name, so it reads the value it was
extracted from instead of null. The compat round-trip test uses AssertJ
like the rest of the compatibility module.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-10-30 14:57:30 -04:00
1 parent 3d455d02ad
commit 955a935bad
7 files changed
+270 -14

No files matched your search

@@ -0,0 +1,68 @@
package com.floci.test;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.CreateFunctionResponse;
import software.amazon.awssdk.services.cloudfront.model.FunctionStage;
import software.amazon.awssdk.services.cloudfront.model.GetFunctionResponse;
import java.nio.charset.StandardCharsets;
import static org.assertj.core.api.Assertions.assertThat;
class CloudFrontFunctionTest {
@Test
void getFunctionReturnsTheDecodedFunctionCode() {
String name = "compat-function-" + TestFixtures.uniqueName();
byte[] code = "function handler(event) { return event.request; }"
.getBytes(StandardCharsets.UTF_8);
byte[] updatedCode = "function handler(event) { return event.response; }"
.getBytes(StandardCharsets.UTF_8);
String etag = null;
String updatedEtag = null;
try (CloudFrontClient cloudFront = TestFixtures.cloudFrontClient()) {
CreateFunctionResponse created = cloudFront.createFunction(request -> request
.name(name)
.functionConfig(config -> config
.comment("compat round trip")
.runtime("cloudfront-js-2.0"))
.functionCode(SdkBytes.fromByteArray(code)));
String createEtag = created.eTag();
etag = createEtag;
GetFunctionResponse function = cloudFront.getFunction(request -> request
.name(name)
.stage(FunctionStage.DEVELOPMENT));
assertThat(function.functionCode().asByteArray()).isEqualTo(code);
assertThat(function.eTag()).isEqualTo(createEtag);
assertThat(function.contentType()).isEqualTo("application/octet-stream");
cloudFront.updateFunction(request -> request
.name(name)
.ifMatch(createEtag)
.functionConfig(config -> config
.comment("compat round trip")
.runtime("cloudfront-js-2.0"))
.functionCode(SdkBytes.fromByteArray(updatedCode)));
GetFunctionResponse afterUpdate = cloudFront.getFunction(request -> request
.name(name)
.stage(FunctionStage.DEVELOPMENT));
updatedEtag = afterUpdate.eTag();
assertThat(afterUpdate.functionCode().asByteArray()).isEqualTo(updatedCode);
assertThat(afterUpdate.contentType()).isEqualTo("application/octet-stream");
} finally {
try (CloudFrontClient cloudFront = TestFixtures.cloudFrontClient()) {
String currentEtag = updatedEtag != null ? updatedEtag : etag;
if (currentEtag != null) {
cloudFront.deleteFunction(request -> request
.name(name)
.ifMatch(currentEtag));
}
}
}
}
}
@@ -21,8 +21,10 @@ import io.github.hectorvent.floci.services.cloudfront.model.ResponseHeadersPolic
import jakarta.enterprise.context.ApplicationScoped;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
@@ -286,6 +288,9 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
* one after the update. Any other change updates the DEVELOPMENT stage in place, and
* {@code AutoPublish: true} then publishes it to LIVE, which {@code Fn::GetAtt Stage} reports.
* Floci has no Key Value Store, so {@code FunctionConfig.KeyValueStoreAssociations} is ignored.
* The template's {@code FunctionCode} is the raw code text, as in the CloudFormation example
* templates, and it is stored in the base64 form the CreateFunction API carries on the wire, so
* {@code GetFunction} serves the template text back.
*
* <p>When publishing or tagging fails, a function this call created is deleted again. An
* in-place update is not reverted, the same limit as the policy types above.
@@ -305,7 +310,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
Map<String, String> tags = ctx.resolveTags(props, "Tags");
CloudFrontFunction fn = new CloudFrontFunction();
fn.setName(name);
fn.setFunctionCode(code);
fn.setFunctionCode(Base64.getEncoder().encodeToString(code.getBytes(StandardCharsets.UTF_8)));
fn.setComment(text(config, "Comment"));
fn.setRuntime(runtime);
@@ -14,7 +14,9 @@ import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -862,7 +864,7 @@ public class CloudFrontController {
@QueryParam("Stage") String stage) {
try {
CloudFrontFunction fn = service.describeFunction(name, stage);
return Response.ok(fn.getFunctionCode() != null ? fn.getFunctionCode() : "", OCTET_STREAM)
return Response.ok(functionCodeBytes(fn), OCTET_STREAM)
.header("ETag", fn.getEtag())
.build();
} catch (AwsException e) {
@@ -870,6 +872,32 @@ public class CloudFrontController {
}
}
/**
* GetFunction serves the function code as the response body. The code reached this emulator
* as the base64 text of the CreateFunction or UpdateFunction FunctionCode element, so it is
* decoded back to the bytes the caller originally encoded. The ETag header carries the
* function's version identifier, and the media type is application/octet-stream, matching
* the GetFunction response contract in the CloudFront API reference.
*
* <p>Records persisted by older Floci versions may hold plain code instead: the
* CloudFormation provisioner once wrote the template's raw body. Those still read back
* as their stored bytes rather than failing, and the next UpdateFunction rewrites them
* into the uniform base64 form.
*/
private byte[] functionCodeBytes(CloudFrontFunction fn) {
String encoded = fn.getFunctionCode();
if (encoded == null || encoded.isBlank()) {
return new byte[0];
}
try {
return Base64.getDecoder().decode(encoded.trim());
} catch (IllegalArgumentException e) {
LOG.warnv("Function {0} holds non-base64 code persisted by an older Floci version; serving it as stored",
fn.getName());
return encoded.getBytes(StandardCharsets.UTF_8);
}
}
@GET
@Path("/function/{Name}/describe")
public Response describeFunction(@PathParam("Name") String name,
@@ -17,6 +17,7 @@ import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -65,15 +66,14 @@ class CloudFormationCloudFrontKeysAndFunctionsIntegrationTest {
assertEquals(functionArn, output(describe, "FunctionArn"));
assertEquals(functionArn, output(describe, "FunctionMetadataArn"));
assertEquals("LIVE", output(describe, "FunctionStage"));
assertEquals("v1", cloudFrontService.describeFunction(functionName, "LIVE").getFunctionCode());
assertFunctionCode(functionName, "LIVE", "v1");
assertEquals(Map.of("Env", "test"), cloudFrontService.listTagsForResource(functionArn));
String otherStack = stackName + "-other";
stackCall("CreateStack", otherStack, template(suffix + "-other", rsaPublicKeyPem(), "other",
functionName, "other code"));
assertStatus(otherStack, "ROLLBACK_COMPLETE");
assertEquals("v1", cloudFrontService.describeFunction(functionName, null).getFunctionCode(),
"a second stack cannot take the name, and its rollback keeps the first function");
assertFunctionCode(functionName, "DEVELOPMENT", "v1");
stackCall("UpdateStack", stackName, template(suffix, pem, "second", functionName, "v2"));
assertStatus(stackName, "UPDATE_COMPLETE");
@@ -82,8 +82,8 @@ class CloudFormationCloudFrontKeysAndFunctionsIntegrationTest {
assertEquals("second", cloudFrontService.getPublicKey(publicKeyId).getComment());
assertEquals(keyGroupId, output(describe, "KeyGroupRef"));
assertEquals(functionArn, output(describe, "FunctionRef"), "a code change keeps the function");
assertEquals("v2", cloudFrontService.describeFunction(functionName, null).getFunctionCode());
assertEquals("v2", cloudFrontService.describeFunction(functionName, "LIVE").getFunctionCode());
assertFunctionCode(functionName, "DEVELOPMENT", "v2");
assertFunctionCode(functionName, "LIVE", "v2");
String renamed = functionName + "-renamed";
stackCall("UpdateStack", stackName, template(suffix, pem, "second", renamed, "v2"));
@@ -107,6 +107,16 @@ class CloudFormationCloudFrontKeysAndFunctionsIntegrationTest {
assertEquals("NoSuchFunctionExists", e.getErrorCode());
}
private void assertFunctionCode(String name, String stage, String expected) {
given()
.queryParam("Stage", stage)
.when()
.get("/2020-05-31/function/" + name)
.then()
.statusCode(200)
.body(equalTo(expected));
}
private static String rsaPublicKeyPem() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
@@ -20,7 +20,9 @@ import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -96,6 +98,10 @@ class CloudFrontCfnProvisionerTest {
return mapper.readTree(json);
}
private static String wireCode(String code) {
return Base64.getEncoder().encodeToString(code.getBytes(StandardCharsets.UTF_8));
}
private static ResponseHeadersPolicy responseHeadersPolicy(String id, String etag) {
ResponseHeadersPolicy p = new ResponseHeadersPolicy();
p.setId(id);
@@ -831,7 +837,8 @@ class CloudFrontCfnProvisionerTest {
ArgumentCaptor<CloudFrontFunction> captor = ArgumentCaptor.forClass(CloudFrontFunction.class);
verify(cloudFront).createFunction(captor.capture());
assertEquals("my-function", captor.getValue().getName());
assertEquals("function handler(event) { return event.request; }", captor.getValue().getFunctionCode());
assertEquals(wireCode("function handler(event) { return event.request; }"),
captor.getValue().getFunctionCode());
assertEquals("example", captor.getValue().getComment());
assertEquals("cloudfront-js-2.0", captor.getValue().getRuntime());
verify(cloudFront).publishFunction("my-function", ETAG);
@@ -875,7 +882,7 @@ class CloudFrontCfnProvisionerTest {
ArgumentCaptor<CloudFrontFunction> captor = ArgumentCaptor.forClass(CloudFrontFunction.class);
verify(cloudFront).updateFunction(eq("my-function"), eq(ETAG), captor.capture());
assertEquals("new code", captor.getValue().getFunctionCode());
assertEquals(wireCode("new code"), captor.getValue().getFunctionCode());
verify(cloudFront, never()).createFunction(any());
verify(cloudFront).publishFunction("my-function", NEW_ETAG);
verify(cloudFront).untagResource(FUNCTION_ARN, List.of("Old"));
@@ -8,9 +8,12 @@ import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -83,6 +86,54 @@ class CloudFrontControllerTest {
}
}
@Test
void getFunctionReturnsTheDecodedFunctionCode() {
CloudFrontService service = mock(CloudFrontService.class);
CloudFrontController controller = new CloudFrontController(service);
byte[] code = "function handler(event) { return event.request; }"
.getBytes(StandardCharsets.UTF_8);
CloudFrontFunction fn = function("routing");
fn.setFunctionCode(Base64.getEncoder().encodeToString(code));
fn.setEtag("etag-code");
when(service.describeFunction("routing", "DEVELOPMENT")).thenReturn(fn);
try (Response response = controller.getFunction("routing", "DEVELOPMENT")) {
assertEquals(200, response.getStatus());
assertEquals("application/octet-stream", response.getHeaderString("Content-Type"));
assertEquals("etag-code", response.getHeaderString("ETag"));
assertArrayEquals(code, (byte[]) response.getEntity());
}
}
@Test
void getFunctionReturnsAnEmptyBodyWhenTheCodeIsMissing() {
CloudFrontService service = mock(CloudFrontService.class);
CloudFrontController controller = new CloudFrontController(service);
CloudFrontFunction fn = function("routing");
fn.setEtag("etag-empty");
when(service.describeFunction("routing", null)).thenReturn(fn);
try (Response response = controller.getFunction("routing", null)) {
assertEquals(200, response.getStatus());
assertArrayEquals(new byte[0], (byte[]) response.getEntity());
}
}
@Test
void getFunctionServesAPlainTextCodePersistedByAnOlderFlociVersion() {
CloudFrontService service = mock(CloudFrontService.class);
CloudFrontController controller = new CloudFrontController(service);
String legacyCode = "function handler(event) { return event.request; }";
CloudFrontFunction fn = function("routing");
fn.setFunctionCode(legacyCode);
when(service.describeFunction("routing", null)).thenReturn(fn);
try (Response response = controller.getFunction("routing", null)) {
assertEquals(200, response.getStatus());
assertArrayEquals(legacyCode.getBytes(StandardCharsets.UTF_8), (byte[]) response.getEntity());
}
}
@Test
void continuousDeploymentPolicyQuantityReportsTheAccountTotal() {
CloudFrontService service = mock(CloudFrontService.class);
@@ -8,6 +8,8 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;
import static io.restassured.RestAssured.given;
@@ -15,6 +17,7 @@ import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.xml.HasXPath.hasXPath;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
/** Verifies CloudFront REST XML payload roots against the AWS service model. */
@QuarkusTest
@@ -22,6 +25,12 @@ class CloudFrontManagementProtocolTest {
private static final String API = "/2020-05-31/";
private static final String FUNCTION_CODE = "function handler(event) { return event.request; }";
private static String encodedFunctionCode() {
return Base64.getEncoder().encodeToString(FUNCTION_CODE.getBytes(StandardCharsets.UTF_8));
}
@ParameterizedTest(name = "{0} returns {1}")
@CsvSource({
"distribution, DistributionList",
@@ -163,9 +172,9 @@ class CloudFrontManagementProtocolTest {
<Comment>routing function</Comment>
<Runtime>python3</Runtime>
</FunctionConfig>
<FunctionCode>function handler(event) { return event.request; }</FunctionCode>
<FunctionCode>%s</FunctionCode>
</CreateFunctionRequest>
""".formatted(name);
""".formatted(name, encodedFunctionCode());
given()
.contentType("application/xml")
@@ -195,9 +204,9 @@ class CloudFrontManagementProtocolTest {
<Comment>routing function</Comment>
<Runtime>cloudfront-js-2.0</Runtime>
</FunctionConfig>
<FunctionCode>function handler(event) { return event.request; }</FunctionCode>
<FunctionCode>%s</FunctionCode>
</CreateFunctionRequest>
""".formatted(name);
""".formatted(name, encodedFunctionCode());
String developmentEtag = given()
.contentType("application/xml")
@@ -256,7 +265,8 @@ class CloudFrontManagementProtocolTest {
.then()
.statusCode(200)
.contentType("application/octet-stream")
.body(equalTo("function handler(event) { return event.request; }"));
.header("ETag", equalTo(developmentEtag))
.body(equalTo(FUNCTION_CODE));
given()
.header("If-Match", developmentEtag)
@@ -302,6 +312,83 @@ class CloudFrontManagementProtocolTest {
.then().statusCode(204);
}
@Test
void getFunctionReturnsTheDecodedFunctionCodeAfterAnUpdate() {
String name = "get-code-" + UUID.randomUUID();
byte[] updatedCode = "function handler(event) { return event.response; }"
.getBytes(StandardCharsets.UTF_8);
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>%s</FunctionCode>
</CreateFunctionRequest>
""".formatted(name, encodedFunctionCode());
String etag = given()
.contentType("application/xml")
.body(createBody)
.when()
.post(API + "function")
.then()
.statusCode(201)
.extract().header("ETag");
byte[] createdCode = given()
.queryParam("Stage", "DEVELOPMENT")
.when()
.get(API + "function/" + name)
.then()
.statusCode(200)
.contentType("application/octet-stream")
.header("ETag", equalTo(etag))
.extract().asByteArray();
assertArrayEquals(FUNCTION_CODE.getBytes(StandardCharsets.UTF_8), createdCode);
String updateBody = """
<UpdateFunctionRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
<FunctionConfig>
<Comment>routing function</Comment>
<Runtime>cloudfront-js-2.0</Runtime>
</FunctionConfig>
<FunctionCode>%s</FunctionCode>
</UpdateFunctionRequest>
""".formatted(Base64.getEncoder().encodeToString(updatedCode));
String updatedEtag = given()
.contentType("application/xml")
.header("If-Match", etag)
.body(updateBody)
.when()
.put(API + "function/" + name)
.then()
.statusCode(200)
.extract().header("ETtag");
byte[] served = given()
.queryParam("Stage", "DEVELOPMENT")
.when()
.get(API + "function/" + name)
.then()
.statusCode(200)
.contentType("application/octet-stream")
.header("ETag", equalTo(updatedEtag))
.extract().asByteArray();
assertArrayEquals(updatedCode, served);
given()
.header("If-Match", updatedEtag)
.when()
.delete(API + "function/" + name)
.then()
.statusCode(204);
}
@Test
void createOriginAccessControlDoesNotDefaultRequiredConfiguration() {
String body = """