fix(cloudfront): include terraform-required distribution fields (#1940)

Real CloudFront always returns DistributionConfig.OriginGroups and
DistributionConfig.Restrictions on Create/Get/ListDistributions. Floci
omitted both, so the Terraform AWS provider dereferenced a nil
OriginGroups.Quantity and panicked while flattening the distribution.

Emit an empty OriginGroups block plus a Restrictions/GeoRestriction block
(defaulting to RestrictionType "none") in the distribution config body and
in distribution summaries, and parse an incoming GeoRestriction so
submitted restriction types and locations are echoed back.

Closes #1930
This commit is contained in:
Ben Younes authored and GitHub committed 2026-08-21 10:33:04 -04:00
1 parent 04d120fdd5
commit 8ac23deb06
2 files changed
+209

No files matched your search

@@ -29,6 +29,16 @@ public class CloudFrontController {
private static final String NS = AwsNamespaces.CLOUDFRONT;
private static final String XML = "application/xml";
private static final String GEO_RESTRICTION = "GeoRestriction";
private static final String ORIGIN_GROUPS = "OriginGroups";
private static final String ITEMS = "Items";
private static final String LOCATION = "Location";
private static final String LOCATIONS = "Locations";
private static final String QUANTITY = "Quantity";
private static final String RESTRICTION_TYPE = "RestrictionType";
private static final String RESTRICTIONS = "Restrictions";
private static final String DEFAULT_GEO_RESTRICTION_TYPE = "none";
private static final int EMPTY_QUANTITY = 0;
private static final XMLInputFactory XML_FACTORY;
@@ -1760,6 +1770,7 @@ public class CloudFrontController {
List<Origin> origins = cfg.getOrigins();
xml.raw(xmlQuantityItems("Origins", "Origin", origins != null ? origins.size() : 0,
origins != null ? origins.stream().map(this::xmlOrigin).toList() : List.of()));
xml.raw(xmlEmptyOriginGroups());
if (cfg.getDefaultCacheBehavior() != null) {
xml.raw(xmlDefaultCacheBehavior(cfg.getDefaultCacheBehavior()));
@@ -1815,10 +1826,69 @@ public class CloudFrontController {
xml.end("Aliases");
xml.raw(xmlViewerCertificate(cfg.getViewerCertificate()));
xml.raw(xmlRestrictions(cfg.getGeoRestriction()));
return xml.build();
}
private String xmlEmptyOriginGroups() {
// Presence-only OriginGroups is intentional for Terraform compatibility; round-tripping groups is deferred.
return new XmlBuilder()
.start(ORIGIN_GROUPS)
.elem(QUANTITY, EMPTY_QUANTITY)
.end(ORIGIN_GROUPS)
.build();
}
private String xmlRestrictions(Map<String, Object> geoRestriction) {
String restrictionType = DEFAULT_GEO_RESTRICTION_TYPE;
int quantity = EMPTY_QUANTITY;
List<String> locations = List.of();
if (geoRestriction != null) {
restrictionType = String.valueOf(
geoRestriction.getOrDefault(RESTRICTION_TYPE, DEFAULT_GEO_RESTRICTION_TYPE));
locations = stringList(geoRestriction.get(LOCATIONS));
quantity = parseInt(geoRestriction.get(QUANTITY), EMPTY_QUANTITY);
if (quantity == EMPTY_QUANTITY && !locations.isEmpty()) {
quantity = locations.size();
}
}
XmlBuilder xml = new XmlBuilder()
.start(RESTRICTIONS)
.start(GEO_RESTRICTION)
.elem(RESTRICTION_TYPE, restrictionType)
.elem(QUANTITY, quantity);
if (!locations.isEmpty()) {
xml.start(ITEMS);
for (String location : locations) {
xml.elem(LOCATION, location);
}
xml.end(ITEMS);
}
return xml.end(GEO_RESTRICTION)
.end(RESTRICTIONS)
.build();
}
private List<String> stringList(Object value) {
if (value instanceof List<?> list) {
return list.stream().map(String::valueOf).toList();
}
return List.of();
}
private int parseInt(Object value, int defaultValue) {
if (value == null) {
return defaultValue;
}
try {
return Integer.parseInt(value.toString());
} catch (NumberFormatException e) {
return defaultValue;
}
}
private String xmlOrigin(Origin o) {
XmlBuilder xml = new XmlBuilder()
.start("Origin")
@@ -2013,6 +2083,7 @@ public class CloudFrontController {
origins != null ? origins.size() : 0,
origins != null ? origins.stream().map(this::xmlOrigin).toList()
: List.of()));
xml.raw(xmlEmptyOriginGroups());
List<String> aliases = cfg != null ? cfg.getAliases() : null;
int aliasCount = aliases != null ? aliases.size() : 0;
@@ -2027,6 +2098,7 @@ public class CloudFrontController {
xml.end("Aliases");
xml.raw(xmlViewerCertificate(cfg != null ? cfg.getViewerCertificate() : null));
xml.raw(xmlRestrictions(cfg != null ? cfg.getGeoRestriction() : null));
xml.end("DistributionSummary");
return xml.build();
@@ -2245,6 +2317,7 @@ public class CloudFrontController {
cfg.setAliases(parseAliases(body));
cfg.setViewerCertificate(parseViewerCertificate(body));
cfg.setCustomErrorResponses(parseCustomErrorResponses(body));
cfg.setGeoRestriction(parseGeoRestriction(body));
return cfg;
}
@@ -2378,6 +2451,19 @@ public class CloudFrontController {
return result;
}
private Map<String, Object> parseGeoRestriction(String body) {
List<Map<String, String>> groups = XmlParser.extractGroups(body, GEO_RESTRICTION);
if (groups.isEmpty()) {
return Map.of();
}
Map<String, Object> geoRestriction = new LinkedHashMap<>(groups.getFirst());
List<String> locations = XmlParser.extractAll(body, LOCATION);
if (!locations.isEmpty()) {
geoRestriction.put(LOCATIONS, locations);
}
return geoRestriction;
}
private List<Origin> parseOrigins(String body) {
List<Origin> result = new ArrayList<>();
if (body == null || body.isEmpty()) {
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
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;
@@ -15,6 +16,7 @@ import io.github.hectorvent.floci.services.cloudfront.model.OriginAccessControl;
import io.github.hectorvent.floci.services.cloudfront.model.PublicKey;
import io.github.hectorvent.floci.services.cloudfront.model.ResponseHeadersPolicy;
import io.github.hectorvent.floci.services.cloudfront.model.StreamingDistribution;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
@@ -39,6 +41,81 @@ class CloudFrontServiceTest {
private static final String ACCOUNT = "000000000000";
private static final String DEFAULT_DOMAIN_SUFFIX = "cloudfront.net";
private static final int LIST_MAX_ITEMS = 100;
private static final String ID_ELEMENT = "Id";
private static final String DISTRIBUTION_CONFIG_XML = """
<DistributionConfig>
<CallerReference>terraform-shape-test</CallerReference>
<Comment>shape test</Comment>
<Enabled>true</Enabled>
<Origins>
<Quantity>1</Quantity>
<Items>
<Origin>
<Id>origin1</Id>
<DomainName>example-bucket.s3.us-east-1.amazonaws.com</DomainName>
<S3OriginConfig>
<OriginAccessIdentity></OriginAccessIdentity>
</S3OriginConfig>
</Origin>
</Items>
</Origins>
<DefaultCacheBehavior>
<TargetOriginId>origin1</TargetOriginId>
<ViewerProtocolPolicy>redirect-to-https</ViewerProtocolPolicy>
</DefaultCacheBehavior>
<ViewerCertificate>
<CloudFrontDefaultCertificate>true</CloudFrontDefaultCertificate>
</ViewerCertificate>
</DistributionConfig>
""";
private static final String EMPTY_ORIGIN_GROUPS_XML =
"<OriginGroups><Quantity>0</Quantity></OriginGroups>";
private static final String EMPTY_RESTRICTIONS_XML =
"<Restrictions><GeoRestriction><RestrictionType>none</RestrictionType><Quantity>0</Quantity>"
+ "</GeoRestriction></Restrictions>";
private static final String GEO_RESTRICTED_DISTRIBUTION_CONFIG_XML = """
<DistributionConfig>
<CallerReference>geo-restriction-test</CallerReference>
<Comment>geo restriction test</Comment>
<Enabled>true</Enabled>
<Origins>
<Quantity>1</Quantity>
<Items>
<Origin>
<Id>origin1</Id>
<DomainName>example-bucket.s3.us-east-1.amazonaws.com</DomainName>
<S3OriginConfig>
<OriginAccessIdentity></OriginAccessIdentity>
</S3OriginConfig>
</Origin>
</Items>
</Origins>
<DefaultCacheBehavior>
<TargetOriginId>origin1</TargetOriginId>
<ViewerProtocolPolicy>redirect-to-https</ViewerProtocolPolicy>
</DefaultCacheBehavior>
<ViewerCertificate>
<CloudFrontDefaultCertificate>true</CloudFrontDefaultCertificate>
</ViewerCertificate>
<Restrictions>
<GeoRestriction>
<RestrictionType>whitelist</RestrictionType>
<Quantity>2</Quantity>
<Items>
<Location>US</Location>
<Location>CA</Location>
</Items>
</GeoRestriction>
</Restrictions>
</DistributionConfig>
""";
private static final String WHITELIST_RESTRICTIONS_XML =
"<Restrictions><GeoRestriction><RestrictionType>whitelist</RestrictionType><Quantity>2</Quantity>"
+ "<Items><Location>US</Location><Location>CA</Location></Items>"
+ "</GeoRestriction></Restrictions>";
private CloudFrontService serviceWithDomainSuffix(String domainSuffix) {
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
@@ -819,4 +896,50 @@ class CloudFrontServiceTest {
assertEquals("InvalidArgument", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void createDistributionIncludesEmptyOriginGroupsAndRestrictions() {
CloudFrontController controller =
new CloudFrontController(serviceWithDomainSuffix(DEFAULT_DOMAIN_SUFFIX));
Response response = controller.createDistribution(null, DISTRIBUTION_CONFIG_XML);
String xml = response.getEntity().toString();
String distributionId = XmlParser.extractFirst(xml, ID_ELEMENT, null);
assertIncludesTerraformRequiredDistributionConfig(xml);
Response getResponse = controller.getDistribution(distributionId);
assertIncludesTerraformRequiredDistributionConfig(getResponse.getEntity().toString());
Response listResponse = controller.listDistributions(null, LIST_MAX_ITEMS);
assertIncludesTerraformRequiredDistributionConfig(listResponse.getEntity().toString());
}
@Test
void createDistributionPreservesGeoRestrictionLocations() {
CloudFrontController controller =
new CloudFrontController(serviceWithDomainSuffix(DEFAULT_DOMAIN_SUFFIX));
Response response =
controller.createDistribution(null, GEO_RESTRICTED_DISTRIBUTION_CONFIG_XML);
String xml = response.getEntity().toString();
String distributionId = XmlParser.extractFirst(xml, ID_ELEMENT, null);
assertIncludesGeoRestrictionLocations(xml);
Response getResponse = controller.getDistribution(distributionId);
assertIncludesGeoRestrictionLocations(getResponse.getEntity().toString());
Response listResponse = controller.listDistributions(null, LIST_MAX_ITEMS);
assertIncludesGeoRestrictionLocations(listResponse.getEntity().toString());
}
private void assertIncludesTerraformRequiredDistributionConfig(String xml) {
assertTrue(xml.contains(EMPTY_ORIGIN_GROUPS_XML), xml);
assertTrue(xml.contains(EMPTY_RESTRICTIONS_XML), xml);
}
private void assertIncludesGeoRestrictionLocations(String xml) {
assertTrue(xml.contains(WHITELIST_RESTRICTIONS_XML), xml);
}
}