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 0380250075..e6e2450456 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 @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.function.Function; @Path("/2020-05-31") @@ -1977,8 +1978,8 @@ public class CloudFrontController { xml.raw(xmlQuantityItems("AllowedMethods", "Method", allowed.size(), allowed.stream().map(m -> "" + XmlBuilder.escape(m) + "").toList())); - xml.start("FunctionAssociations").elem("Quantity", 0).end("FunctionAssociations"); - xml.start("LambdaFunctionAssociations").elem("Quantity", 0).end("LambdaFunctionAssociations"); + xml.raw(xmlFunctionAssociations(dcb.getFunctionAssociations())); + xml.raw(xmlLambdaFunctionAssociations(dcb.getLambdaFunctionAssociations())); xml.end("DefaultCacheBehavior"); return xml.build(); @@ -2006,13 +2007,50 @@ public class CloudFrontController { xml.raw(xmlQuantityItems("AllowedMethods", "Method", allowed.size(), allowed.stream().map(m -> "" + XmlBuilder.escape(m) + "").toList())); - xml.start("FunctionAssociations").elem("Quantity", 0).end("FunctionAssociations"); - xml.start("LambdaFunctionAssociations").elem("Quantity", 0).end("LambdaFunctionAssociations"); + xml.raw(xmlFunctionAssociations(cb.getFunctionAssociations())); + xml.raw(xmlLambdaFunctionAssociations(cb.getLambdaFunctionAssociations())); xml.end("CacheBehavior"); return xml.build(); } + private String xmlLambdaFunctionAssociations(List> associations) { + List> list = associations != null ? associations : List.of(); + XmlBuilder xml = new XmlBuilder() + .start("LambdaFunctionAssociations") + .elem("Quantity", list.size()); + if (!list.isEmpty()) { + xml.start("Items"); + for (Map a : list) { + xml.start("LambdaFunctionAssociation") + .elem("LambdaFunctionARN", str(a.get("LambdaFunctionARN"))) + .elem("EventType", str(a.get("EventType"))) + .elem("IncludeBody", Boolean.TRUE.equals(a.get("IncludeBody"))) + .end("LambdaFunctionAssociation"); + } + xml.end("Items"); + } + return xml.end("LambdaFunctionAssociations").build(); + } + + private String xmlFunctionAssociations(List> associations) { + List> list = associations != null ? associations : List.of(); + XmlBuilder xml = new XmlBuilder() + .start("FunctionAssociations") + .elem("Quantity", list.size()); + if (!list.isEmpty()) { + xml.start("Items"); + for (Map a : list) { + xml.start("FunctionAssociation") + .elem("FunctionARN", str(a.get("FunctionARN"))) + .elem("EventType", str(a.get("EventType"))) + .end("FunctionAssociation"); + } + xml.end("Items"); + } + return xml.end("FunctionAssociations").build(); + } + private String xmlTrustedKeyGroups( boolean enabled, List trustedKeyGroups) { List keyGroups = trustedKeyGroups != null ? trustedKeyGroups : List.of(); @@ -2731,6 +2769,58 @@ public class CloudFrontController { 400); } + // Event types accepted by AWS for each association kind. Lambda@Edge runs at all + // four points; CloudFront Functions only at the viewer edge. + private static final Set LAMBDA_EVENT_TYPES = Set.of( + "viewer-request", "viewer-response", "origin-request", "origin-response"); + private static final Set FUNCTION_EVENT_TYPES = Set.of( + "viewer-request", "viewer-response"); + + private void validateLambdaFunctionAssociations(List> associations) { + for (Map a : associations) { + if (str(a.get("LambdaFunctionARN")).isEmpty()) { + throw new AwsException("InvalidArgument", + "The Lambda function association must include a LambdaFunctionARN.", 400); + } + if (!LAMBDA_EVENT_TYPES.contains(str(a.get("EventType")))) { + throw new AwsException("InvalidArgument", + "The event type for the Lambda function association is not valid.", 400); + } + } + } + + private void validateFunctionAssociations(List> associations) { + for (Map a : associations) { + if (str(a.get("FunctionARN")).isEmpty()) { + throw new AwsException("InvalidArgument", + "The CloudFront function association must include a FunctionARN.", 400); + } + if (!FUNCTION_EVENT_TYPES.contains(str(a.get("EventType")))) { + throw new AwsException("InvalidArgument", + "The event type for the CloudFront function association is not valid.", 400); + } + } + } + + private static int parseAssociationsQuantity(String value) { + try { + int quantity = Integer.parseInt(value.trim()); + if (quantity < 0) { + throw new NumberFormatException("negative quantity"); + } + return quantity; + } catch (NumberFormatException e) { + throw new AwsException("InvalidArgument", + "The association Quantity must be a non-negative integer.", 400); + } + } + + private static void validateAssociationsQuantity(Integer declared, int itemCount) { + if (declared != null && declared != itemCount) { + throw inconsistentQuantities(); + } + } + private DefaultCacheBehavior parseDefaultCacheBehavior(String body) { DefaultCacheBehavior dcb = new DefaultCacheBehavior(); if (body == null || body.isEmpty()) { @@ -2746,6 +2836,14 @@ public class CloudFrontController { Integer trustedKeyGroupsQuantity = null; List allowedMethods = new ArrayList<>(); List trustedKeyGroups = new ArrayList<>(); + boolean inLambdaAssociations = false; + boolean inFunctionAssociations = false; + Map currentLambdaAssociation = null; + Map currentFunctionAssociation = null; + List> lambdaAssociations = new ArrayList<>(); + List> functionAssociations = new ArrayList<>(); + Integer lambdaAssociationsQuantity = null; + Integer functionAssociationsQuantity = null; while (r.hasNext()) { int event = r.next(); @@ -2753,6 +2851,49 @@ public class CloudFrontController { String local = r.getLocalName(); switch (local) { case "DefaultCacheBehavior" -> inDcb = true; + case "LambdaFunctionAssociations" -> { + if (inDcb) { + inLambdaAssociations = true; + } + } + case "FunctionAssociations" -> { + if (inDcb) { + inFunctionAssociations = true; + } + } + case "LambdaFunctionAssociation" -> { + if (inLambdaAssociations) { + currentLambdaAssociation = new LinkedHashMap<>(); + } + } + case "FunctionAssociation" -> { + if (inFunctionAssociations) { + currentFunctionAssociation = new LinkedHashMap<>(); + } + } + case "LambdaFunctionARN" -> { + if (currentLambdaAssociation != null) { + currentLambdaAssociation.put("LambdaFunctionARN", r.getElementText()); + } + } + case "FunctionARN" -> { + if (currentFunctionAssociation != null) { + currentFunctionAssociation.put("FunctionARN", r.getElementText()); + } + } + case "IncludeBody" -> { + if (currentLambdaAssociation != null) { + currentLambdaAssociation.put( + "IncludeBody", "true".equalsIgnoreCase(r.getElementText())); + } + } + case "EventType" -> { + if (currentLambdaAssociation != null) { + currentLambdaAssociation.put("EventType", r.getElementText()); + } else if (currentFunctionAssociation != null) { + currentFunctionAssociation.put("EventType", r.getElementText()); + } + } case "TrustedKeyGroups" -> { if (inDcb) { inTrustedKeyGroups = true; @@ -2769,6 +2910,12 @@ public class CloudFrontController { if (inTrustedKeyGroups) { trustedKeyGroupsQuantity = parseTrustedKeyGroupsQuantity(r.getElementText()); + } else if (inLambdaAssociations && currentLambdaAssociation == null) { + lambdaAssociationsQuantity = + parseAssociationsQuantity(r.getElementText()); + } else if (inFunctionAssociations && currentFunctionAssociation == null) { + functionAssociationsQuantity = + parseAssociationsQuantity(r.getElementText()); } } case "KeyGroup" -> { @@ -2814,6 +2961,20 @@ public class CloudFrontController { case "AllowedMethods" -> inAllowedMethods = false; case "TrustedKeyGroups" -> inTrustedKeyGroups = false; case "DefaultCacheBehavior" -> inDcb = false; + case "LambdaFunctionAssociations" -> inLambdaAssociations = false; + case "FunctionAssociations" -> inFunctionAssociations = false; + case "LambdaFunctionAssociation" -> { + if (currentLambdaAssociation != null) { + lambdaAssociations.add(currentLambdaAssociation); + currentLambdaAssociation = null; + } + } + case "FunctionAssociation" -> { + if (currentFunctionAssociation != null) { + functionAssociations.add(currentFunctionAssociation); + currentFunctionAssociation = null; + } + } default -> { } } @@ -2826,6 +2987,16 @@ public class CloudFrontController { if (!trustedKeyGroups.isEmpty()) { dcb.setTrustedKeyGroups(trustedKeyGroups); } + validateAssociationsQuantity(lambdaAssociationsQuantity, lambdaAssociations.size()); + validateAssociationsQuantity(functionAssociationsQuantity, functionAssociations.size()); + validateLambdaFunctionAssociations(lambdaAssociations); + validateFunctionAssociations(functionAssociations); + if (!lambdaAssociations.isEmpty()) { + dcb.setLambdaFunctionAssociations(lambdaAssociations); + } + if (!functionAssociations.isEmpty()) { + dcb.setFunctionAssociations(functionAssociations); + } if (sawTrustedKeyGroups) { if (trustedKeyGroupsEnabled == null) { throw new AwsException( @@ -2866,6 +3037,14 @@ public class CloudFrontController { Integer trustedKeyGroupsQuantity = null; List allowedMethods = new ArrayList<>(); List trustedKeyGroups = new ArrayList<>(); + boolean inLambdaAssociations = false; + boolean inFunctionAssociations = false; + Map currentLambdaAssociation = null; + Map currentFunctionAssociation = null; + List> lambdaAssociations = new ArrayList<>(); + List> functionAssociations = new ArrayList<>(); + Integer lambdaAssociationsQuantity = null; + Integer functionAssociationsQuantity = null; while (r.hasNext()) { int event = r.next(); @@ -2882,6 +3061,53 @@ public class CloudFrontController { trustedKeyGroupsQuantity = null; allowedMethods = new ArrayList<>(); trustedKeyGroups = new ArrayList<>(); + lambdaAssociations = new ArrayList<>(); + functionAssociations = new ArrayList<>(); + lambdaAssociationsQuantity = null; + functionAssociationsQuantity = null; + } + } + case "LambdaFunctionAssociations" -> { + if (inCacheBehavior) { + inLambdaAssociations = true; + } + } + case "FunctionAssociations" -> { + if (inCacheBehavior) { + inFunctionAssociations = true; + } + } + case "LambdaFunctionAssociation" -> { + if (inLambdaAssociations) { + currentLambdaAssociation = new LinkedHashMap<>(); + } + } + case "FunctionAssociation" -> { + if (inFunctionAssociations) { + currentFunctionAssociation = new LinkedHashMap<>(); + } + } + case "LambdaFunctionARN" -> { + if (currentLambdaAssociation != null) { + currentLambdaAssociation.put("LambdaFunctionARN", r.getElementText()); + } + } + case "FunctionARN" -> { + if (currentFunctionAssociation != null) { + currentFunctionAssociation.put("FunctionARN", r.getElementText()); + } + } + case "IncludeBody" -> { + if (currentLambdaAssociation != null) { + currentLambdaAssociation.put( + "IncludeBody", "true".equalsIgnoreCase(r.getElementText())); + } + } + case "EventType" -> { + if (currentLambdaAssociation != null) { + currentLambdaAssociation.put("EventType", r.getElementText()); + } else if (currentFunctionAssociation != null) { + currentFunctionAssociation.put("EventType", r.getElementText()); } } case "TrustedKeyGroups" -> { @@ -2900,6 +3126,12 @@ public class CloudFrontController { if (inTrustedKeyGroups) { trustedKeyGroupsQuantity = parseTrustedKeyGroupsQuantity(r.getElementText()); + } else if (inLambdaAssociations && currentLambdaAssociation == null) { + lambdaAssociationsQuantity = + parseAssociationsQuantity(r.getElementText()); + } else if (inFunctionAssociations && currentFunctionAssociation == null) { + functionAssociationsQuantity = + parseAssociationsQuantity(r.getElementText()); } } case "KeyGroup" -> { @@ -2945,6 +3177,20 @@ public class CloudFrontController { switch (r.getLocalName()) { case "AllowedMethods" -> inAllowedMethods = false; case "TrustedKeyGroups" -> inTrustedKeyGroups = false; + case "LambdaFunctionAssociations" -> inLambdaAssociations = false; + case "FunctionAssociations" -> inFunctionAssociations = false; + case "LambdaFunctionAssociation" -> { + if (currentLambdaAssociation != null) { + lambdaAssociations.add(currentLambdaAssociation); + currentLambdaAssociation = null; + } + } + case "FunctionAssociation" -> { + if (currentFunctionAssociation != null) { + functionAssociations.add(currentFunctionAssociation); + currentFunctionAssociation = null; + } + } case "CacheBehavior" -> { if (inCacheBehavior && current != null) { if (!allowedMethods.isEmpty()) { @@ -2953,6 +3199,18 @@ public class CloudFrontController { if (!trustedKeyGroups.isEmpty()) { current.setTrustedKeyGroups(trustedKeyGroups); } + validateAssociationsQuantity( + lambdaAssociationsQuantity, lambdaAssociations.size()); + validateAssociationsQuantity( + functionAssociationsQuantity, functionAssociations.size()); + validateLambdaFunctionAssociations(lambdaAssociations); + validateFunctionAssociations(functionAssociations); + if (!lambdaAssociations.isEmpty()) { + current.setLambdaFunctionAssociations(lambdaAssociations); + } + if (!functionAssociations.isEmpty()) { + current.setFunctionAssociations(functionAssociations); + } if (sawTrustedKeyGroups) { if (trustedKeyGroupsEnabled == null) { throw new AwsException( 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 d562bc045f..67290cd01f 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 @@ -6,11 +6,14 @@ import io.github.hectorvent.floci.services.cloudfront.model.ContinuousDeployment import io.github.hectorvent.floci.services.cloudfront.model.Distribution; import jakarta.ws.rs.core.Response; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import java.util.List; +import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -104,6 +107,158 @@ class CloudFrontControllerTest { } } + @Test + void distributionConfigRoundTripsLambdaAndCloudFrontFunctionAssociations() { + CloudFrontService service = mock(CloudFrontService.class); + CloudFrontController controller = new CloudFrontController(service); + + String body = distributionConfigBody(""" + 1 + arn:aws:lambda:us-east-1:000000000000:function:edge-fn:1 + viewer-request + false + + 1 + arn:aws:cloudfront::000000000000:function/cf-fn + viewer-response + + """); + + ArgumentCaptor captor = ArgumentCaptor.forClass(Distribution.class); + when(service.createDistribution(captor.capture(), any())).thenAnswer(inv -> { + Distribution d = inv.getArgument(0); + d.setId("dist-1"); + d.setEtag("etag-1"); + return d; + }); + + try (Response created = controller.createDistribution(null, body)) { + assertEquals(201, created.getStatus()); + } + + when(service.getDistribution("dist-1")).thenReturn(captor.getValue()); + + try (Response cfg = controller.getDistributionConfig("dist-1")) { + String xml = (String) cfg.getEntity(); + + List> lambda = + XmlParser.extractGroups(xml, "LambdaFunctionAssociation"); + assertEquals(1, lambda.size()); + assertEquals("arn:aws:lambda:us-east-1:000000000000:function:edge-fn:1", + lambda.get(0).get("LambdaFunctionARN")); + assertEquals("viewer-request", lambda.get(0).get("EventType")); + assertEquals("false", lambda.get(0).get("IncludeBody")); + + List> fn = + XmlParser.extractGroups(xml, "FunctionAssociation"); + assertEquals(1, fn.size()); + assertEquals("arn:aws:cloudfront::000000000000:function/cf-fn", + fn.get(0).get("FunctionARN")); + assertEquals("viewer-response", fn.get(0).get("EventType")); + } + } + + @Test + void orderedCacheBehaviorRoundTripsLambdaFunctionAssociations() { + CloudFrontService service = mock(CloudFrontService.class); + CloudFrontController controller = new CloudFrontController(service); + + String body = distributionConfigBody("").replace("", """ + + 1 + /api/* + o1 + https-only + 2 + GETHEAD + 1 + arn:aws:lambda:us-east-1:000000000000:function:api-fn:7 + origin-request + true + + + """); + + ArgumentCaptor captor = ArgumentCaptor.forClass(Distribution.class); + when(service.createDistribution(captor.capture(), any())).thenAnswer(inv -> { + Distribution d = inv.getArgument(0); + d.setId("dist-2"); + d.setEtag("etag-2"); + return d; + }); + try (Response created = controller.createDistribution(null, body)) { + assertEquals(201, created.getStatus()); + } + when(service.getDistribution("dist-2")).thenReturn(captor.getValue()); + + try (Response cfg = controller.getDistributionConfig("dist-2")) { + String xml = (String) cfg.getEntity(); + List> lambda = + XmlParser.extractGroups(xml, "LambdaFunctionAssociation"); + assertEquals(1, lambda.size()); + assertEquals("origin-request", lambda.get(0).get("EventType")); + assertEquals("true", lambda.get(0).get("IncludeBody")); + } + } + + @Test + void invalidLambdaFunctionAssociationEventTypeIsRejected() { + CloudFrontService service = mock(CloudFrontService.class); + CloudFrontController controller = new CloudFrontController(service); + + String body = distributionConfigBody(""" + 1 + arn:aws:lambda:us-east-1:000000000000:function:edge-fn:1 + not-an-event + + """); + + try (Response created = controller.createDistribution(null, body)) { + assertEquals(400, created.getStatus()); + assertTrue(((String) created.getEntity()).contains("InvalidArgument")); + } + } + + @Test + void lambdaFunctionAssociationsQuantityMismatchIsRejected() { + CloudFrontService service = mock(CloudFrontService.class); + CloudFrontController controller = new CloudFrontController(service); + + String body = distributionConfigBody(""" + 2 + arn:aws:lambda:us-east-1:000000000000:function:edge-fn:1 + viewer-request + + """); + + try (Response created = controller.createDistribution(null, body)) { + assertEquals(400, created.getStatus()); + assertTrue(((String) created.getEntity()).contains("InconsistentQuantities")); + } + } + + private static String distributionConfigBody(String defaultCacheBehaviorExtra) { + return """ + + ref-1 + true + probe + 1 + o1example.com + 80443 + https-only + + + o1 + redirect-to-https + 2 + GETHEAD + %s + + + """.formatted(defaultCacheBehaviorExtra); + } + private static Distribution distribution(String id) { Distribution distribution = new Distribution(); distribution.setId(id);