fix(cloudfront): persist and echo LambdaFunctionAssociations and FunctionAssociations (#2915)

* fix(cloudfront): persist and echo LambdaFunctionAssociations and FunctionAssociations

CreateDistribution accepted LambdaFunctionAssociations and then silently
dropped them: the parser never read the element and the serializer
hardcoded Quantity 0. A distribution meant to run a viewer-request
Lambda@Edge function ended up with no function attached and no error.
FunctionAssociations (CloudFront Functions) had the same bug, so it is
fixed in the same change.

- parseDefaultCacheBehavior + parseCacheBehaviors: read LambdaFunctionARN,
  EventType, IncludeBody for Lambda and FunctionARN, EventType for
  Functions into the existing model fields.
- xmlDefaultCacheBehavior + xmlCacheBehavior: replace the two hardcoded
  blocks with xmlLambdaFunctionAssociations / xmlFunctionAssociations,
  still emitting <Quantity>0</Quantity> when empty.
- Validate EventType: Lambda allows all four event types, Functions only
  viewer-request and viewer-response; an empty ARN or an invalid
  EventType returns 400 InvalidArgument.

Closes #2835

* fix(cloudfront): validate association Quantity and brace association parsers

Address review feedback on the LambdaFunctionAssociations / FunctionAssociations
round-trip:

- The parsers now read the declared <Quantity> for each association block.
  A malformed value returns 400 InvalidArgument; a value that differs from
  the number of items returns 400 InconsistentQuantities, matching the
  existing TrustedKeyGroups handling, instead of being silently recomputed
  on read-back. An omitted Quantity is still accepted.
- Add braces to every conditional in the new association parsing paths, per
  the repository convention in AGENTS.md.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-02 10:29:19 -04:00
1 parent 5c71713cad
commit 3d3ab0023f
2 files changed
+417 -4

No files matched your search

@@ -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 -> "<Method>" + XmlBuilder.escape(m) + "</Method>").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 -> "<Method>" + XmlBuilder.escape(m) + "</Method>").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<Map<String, Object>> associations) {
List<Map<String, Object>> list = associations != null ? associations : List.of();
XmlBuilder xml = new XmlBuilder()
.start("LambdaFunctionAssociations")
.elem("Quantity", list.size());
if (!list.isEmpty()) {
xml.start("Items");
for (Map<String, Object> 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<Map<String, String>> associations) {
List<Map<String, String>> list = associations != null ? associations : List.of();
XmlBuilder xml = new XmlBuilder()
.start("FunctionAssociations")
.elem("Quantity", list.size());
if (!list.isEmpty()) {
xml.start("Items");
for (Map<String, String> 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<String> trustedKeyGroups) {
List<String> 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<String> LAMBDA_EVENT_TYPES = Set.of(
"viewer-request", "viewer-response", "origin-request", "origin-response");
private static final Set<String> FUNCTION_EVENT_TYPES = Set.of(
"viewer-request", "viewer-response");
private void validateLambdaFunctionAssociations(List<Map<String, Object>> associations) {
for (Map<String, Object> 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<Map<String, String>> associations) {
for (Map<String, String> 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<String> allowedMethods = new ArrayList<>();
List<String> trustedKeyGroups = new ArrayList<>();
boolean inLambdaAssociations = false;
boolean inFunctionAssociations = false;
Map<String, Object> currentLambdaAssociation = null;
Map<String, String> currentFunctionAssociation = null;
List<Map<String, Object>> lambdaAssociations = new ArrayList<>();
List<Map<String, String>> 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<String> allowedMethods = new ArrayList<>();
List<String> trustedKeyGroups = new ArrayList<>();
boolean inLambdaAssociations = false;
boolean inFunctionAssociations = false;
Map<String, Object> currentLambdaAssociation = null;
Map<String, String> currentFunctionAssociation = null;
List<Map<String, Object>> lambdaAssociations = new ArrayList<>();
List<Map<String, String>> 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(
@@ -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("""
<LambdaFunctionAssociations><Quantity>1</Quantity><Items><LambdaFunctionAssociation>
<LambdaFunctionARN>arn:aws:lambda:us-east-1:000000000000:function:edge-fn:1</LambdaFunctionARN>
<EventType>viewer-request</EventType>
<IncludeBody>false</IncludeBody>
</LambdaFunctionAssociation></Items></LambdaFunctionAssociations>
<FunctionAssociations><Quantity>1</Quantity><Items><FunctionAssociation>
<FunctionARN>arn:aws:cloudfront::000000000000:function/cf-fn</FunctionARN>
<EventType>viewer-response</EventType>
</FunctionAssociation></Items></FunctionAssociations>
""");
ArgumentCaptor<Distribution> 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<Map<String, String>> 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<Map<String, String>> 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("</DefaultCacheBehavior>", """
</DefaultCacheBehavior>
<CacheBehaviors><Quantity>1</Quantity><Items><CacheBehavior>
<PathPattern>/api/*</PathPattern>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>https-only</ViewerProtocolPolicy>
<AllowedMethods><Quantity>2</Quantity><Items>
<Method>GET</Method><Method>HEAD</Method></Items></AllowedMethods>
<LambdaFunctionAssociations><Quantity>1</Quantity><Items><LambdaFunctionAssociation>
<LambdaFunctionARN>arn:aws:lambda:us-east-1:000000000000:function:api-fn:7</LambdaFunctionARN>
<EventType>origin-request</EventType>
<IncludeBody>true</IncludeBody>
</LambdaFunctionAssociation></Items></LambdaFunctionAssociations>
</CacheBehavior></Items></CacheBehaviors>
""");
ArgumentCaptor<Distribution> 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<Map<String, String>> 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("""
<LambdaFunctionAssociations><Quantity>1</Quantity><Items><LambdaFunctionAssociation>
<LambdaFunctionARN>arn:aws:lambda:us-east-1:000000000000:function:edge-fn:1</LambdaFunctionARN>
<EventType>not-an-event</EventType>
</LambdaFunctionAssociation></Items></LambdaFunctionAssociations>
""");
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("""
<LambdaFunctionAssociations><Quantity>2</Quantity><Items><LambdaFunctionAssociation>
<LambdaFunctionARN>arn:aws:lambda:us-east-1:000000000000:function:edge-fn:1</LambdaFunctionARN>
<EventType>viewer-request</EventType>
</LambdaFunctionAssociation></Items></LambdaFunctionAssociations>
""");
try (Response created = controller.createDistribution(null, body)) {
assertEquals(400, created.getStatus());
assertTrue(((String) created.getEntity()).contains("InconsistentQuantities"));
}
}
private static String distributionConfigBody(String defaultCacheBehaviorExtra) {
return """
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
<CallerReference>ref-1</CallerReference>
<Enabled>true</Enabled>
<Comment>probe</Comment>
<Origins><Quantity>1</Quantity><Items><Origin>
<Id>o1</Id><DomainName>example.com</DomainName>
<CustomOriginConfig><HTTPPort>80</HTTPPort><HTTPSPort>443</HTTPSPort>
<OriginProtocolPolicy>https-only</OriginProtocolPolicy></CustomOriginConfig>
</Origin></Items></Origins>
<DefaultCacheBehavior>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>redirect-to-https</ViewerProtocolPolicy>
<AllowedMethods><Quantity>2</Quantity><Items>
<Method>GET</Method><Method>HEAD</Method></Items></AllowedMethods>
%s
</DefaultCacheBehavior>
</DistributionConfig>
""".formatted(defaultCacheBehaviorExtra);
}
private static Distribution distribution(String id) {
Distribution distribution = new Distribution();
distribution.setId(id);