diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFrontFunctionTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFrontFunctionTest.java new file mode 100644 index 0000000000..f9264edfd8 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFrontFunctionTest.java @@ -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)); + } + } + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java index 87914f0309..eff54d7225 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java @@ -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. * *

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 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); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java index 458bf0fcc4..630b5e3ff1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java @@ -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. + * + *

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, diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontKeysAndFunctionsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontKeysAndFunctionsIntegrationTest.java index 9d0a3af44f..7a63c7c38a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontKeysAndFunctionsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontKeysAndFunctionsIntegrationTest.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java index b602acba30..0d5e437682 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java @@ -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 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 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")); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontControllerTest.java index c878859762..d13ef2af1c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontControllerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontControllerTest.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontManagementProtocolTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontManagementProtocolTest.java index 9b08ac1047..042fd0fa8a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontManagementProtocolTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontManagementProtocolTest.java @@ -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 { routing function python3 - function handler(event) { return event.request; } + %s - """.formatted(name); + """.formatted(name, encodedFunctionCode()); given() .contentType("application/xml") @@ -195,9 +204,9 @@ class CloudFrontManagementProtocolTest { routing function cloudfront-js-2.0 - function handler(event) { return event.request; } + %s - """.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 = """ + + %s + + routing function + cloudfront-js-2.0 + + %s + + """.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 = """ + + + routing function + cloudfront-js-2.0 + + %s + + """.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 = """