fix(cloudfront): report Logging on distribution reads (#3318)

* fix(cloudfront): report Logging on distribution reads

GetDistribution and GetDistributionConfig omitted the Logging member of
DistributionConfig. It is "Required: No" on input, but CloudFront reports it on
every response with its defaults, and callers read it unconditionally: the AWS
SDKs and the Terraform provider both expect the element to be present.

Report it with the defaults CloudFront uses, a disabled configuration with an
empty bucket and prefix, and echo an explicitly supplied one back in full. The
model already carried the field; it was simply never written to the response.

Restrictions and OriginGroups had the same gap and are already handled, so only
Logging is added here.

Reference: the DistributionConfig members and their types
https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_DistributionConfig.html

* fix(cloudfront): parse the Logging block on distribution writes

Reads report Logging, but parseDistributionConfig never read it from the
request body, so CreateDistribution and UpdateDistribution dropped an
explicit block and the caller read the disabled defaults back. That is the
drift aws_cloudfront_distribution sees on logging_config: it sends a
configuration and gets defaults.

parseLogging follows parseGeoRestriction, extracting Enabled,
IncludeCookies, Bucket and Prefix. An absent block yields an empty map,
which xmlLogging still renders as today's disabled defaults.

The existing coverage built the model in Java and inserted it through
CloudFrontService, so it passed with the parser missing. The new tests POST
and PUT a DistributionConfig body over HTTP and read it back, which is what
puts the parser under test.

* test(cloudfront): take CloudFrontService through the constructor

AGENTS.md asks for constructor injection and this test used an @Inject field.

I had argued against changing it on the grounds that a @QuarkusTest cannot take
constructor injection, since JUnit 5 needs a registered ParameterResolver and I
believed Quarkus does not supply one for CDI beans. That is wrong. A probe with a
constructor taking CloudFrontService compiles and passes, so the 0-of-736 count in
this repo reflects habit rather than a constraint.

209 CloudFront tests still pass.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-10 10:14:32 -04:00
1 parent 49903ab9fe
commit d4e9dcbe55
2 files changed
+285

No files matched your search

@@ -1832,10 +1832,29 @@ public class CloudFrontController {
xml.raw(xmlViewerCertificate(cfg.getViewerCertificate()));
xml.raw(xmlRestrictions(cfg.getGeoRestriction()));
xml.raw(xmlLogging(cfg.getLogging()));
return xml.build();
}
/**
* Logging is always present on a real DistributionConfig response, disabled by
* default. Callers read it unconditionally, so omitting it when the caller did not
* supply one leaves the member missing from every read.
*/
private String xmlLogging(Map<String, Object> logging) {
return new XmlBuilder()
.start("Logging")
.elem("Enabled", logging != null
&& Boolean.parseBoolean(str(logging.get("Enabled"))))
.elem("IncludeCookies", logging != null
&& Boolean.parseBoolean(str(logging.get("IncludeCookies"))))
.elem("Bucket", logging != null ? str(logging.get("Bucket")) : "")
.elem("Prefix", logging != null ? str(logging.get("Prefix")) : "")
.end("Logging")
.build();
}
private String xmlEmptyOriginGroups() {
// Presence-only OriginGroups is intentional for Terraform compatibility; round-tripping groups is deferred.
return new XmlBuilder()
@@ -2478,6 +2497,7 @@ public class CloudFrontController {
cfg.setViewerCertificate(parseViewerCertificate(body));
cfg.setCustomErrorResponses(parseCustomErrorResponses(body));
cfg.setGeoRestriction(parseGeoRestriction(body));
cfg.setLogging(parseLogging(body));
return cfg;
}
@@ -2610,6 +2630,20 @@ public class CloudFrontController {
return result;
}
/**
* Parses the optional {@code Logging} block into {@code Enabled}, {@code IncludeCookies},
* {@code Bucket} and {@code Prefix} (values kept as strings). A request that omits the block
* yields an empty map rather than {@code null}, which {@link #xmlLogging} renders as the
* disabled defaults CloudFront reports for a distribution that never asked for access logs.
*/
private Map<String, Object> parseLogging(String body) {
List<Map<String, String>> groups = XmlParser.extractGroups(body, "Logging");
if (groups.isEmpty()) {
return Map.of();
}
return new LinkedHashMap<>(groups.getFirst());
}
private Map<String, Object> parseGeoRestriction(String body) {
List<Map<String, String>> groups = XmlParser.extractGroups(body, GEO_RESTRICTION);
if (groups.isEmpty()) {
@@ -0,0 +1,251 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.xml.HasXPath.hasXPath;
/**
* DistributionConfig members that a caller may omit on input but still expects to read
* back. Logging is "Required: No" on the request, and CloudFront reports it on every
* response with its defaults; the AWS SDKs and the Terraform provider read it
* unconditionally.
*/
@QuarkusTest
class CloudFrontDistributionConfigMembersTest {
private static final String DISTRIBUTIONS = "/2020-05-31/distribution";
private static final String API = DISTRIBUTIONS + "/";
private static final String LOGGING_ENABLED =
"//*[local-name()='Logging']/*[local-name()='Enabled']";
private static final String LOGGING_INCLUDE_COOKIES =
"//*[local-name()='Logging']/*[local-name()='IncludeCookies']";
private static final String LOGGING_BUCKET =
"//*[local-name()='Logging']/*[local-name()='Bucket']";
private static final String LOGGING_PREFIX =
"//*[local-name()='Logging']/*[local-name()='Prefix']";
private final CloudFrontService cloudFrontService;
CloudFrontDistributionConfigMembersTest(CloudFrontService cloudFrontService) {
this.cloudFrontService = cloudFrontService;
}
/** The minimum a caller can legally supply: no Logging element at all. */
private String createMinimalDistribution(String originId) {
Origin origin = new Origin();
origin.setId(originId);
origin.setDomainName("example.com");
Map<String, Object> customOriginConfig = new LinkedHashMap<>();
customOriginConfig.put("HTTPPort", "80");
customOriginConfig.put("HTTPSPort", "443");
customOriginConfig.put("OriginProtocolPolicy", "http-only");
origin.setCustomOriginConfig(customOriginConfig);
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
behavior.setTargetOriginId(originId);
behavior.setViewerProtocolPolicy("allow-all");
DistributionConfig config = new DistributionConfig();
config.setEnabled(true);
config.setComment("members-test");
config.setOrigins(List.of(origin));
config.setDefaultCacheBehavior(behavior);
Distribution distribution = new Distribution();
distribution.setConfig(config);
return cloudFrontService.createDistribution(distribution, Map.of()).getId();
}
@Test
void getDistributionReportsLoggingDisabledByDefault() {
String id = createMinimalDistribution("origin-logging");
given()
.when()
.get(API + id)
.then()
.statusCode(200)
.body(hasXPath(LOGGING_ENABLED, equalTo("false")))
.body(hasXPath(LOGGING_BUCKET, equalTo("")));
}
@Test
void getDistributionConfigReportsLoggingToo() {
// The Terraform provider reads the resource back immediately after create, so the
// config response has to carry the member too: reporting it only on
// GetDistribution would still leave the read-after-create short a field.
String id = createMinimalDistribution("origin-logging-config");
given()
.when()
.get(API + id + "/config")
.then()
.statusCode(200)
.body(hasXPath(LOGGING_ENABLED, equalTo("false")));
}
@Test
void anExplicitLoggingConfigurationIsReportedBackInFull() {
Origin origin = new Origin();
origin.setId("origin-logging-explicit");
origin.setDomainName("example.com");
Map<String, Object> customOriginConfig = new LinkedHashMap<>();
customOriginConfig.put("HTTPPort", "80");
customOriginConfig.put("HTTPSPort", "443");
customOriginConfig.put("OriginProtocolPolicy", "http-only");
origin.setCustomOriginConfig(customOriginConfig);
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
behavior.setTargetOriginId("origin-logging-explicit");
behavior.setViewerProtocolPolicy("allow-all");
DistributionConfig config = new DistributionConfig();
config.setEnabled(true);
config.setComment("members-test-explicit");
config.setOrigins(List.of(origin));
config.setDefaultCacheBehavior(behavior);
Map<String, Object> logging = new LinkedHashMap<>();
logging.put("Enabled", "true");
logging.put("IncludeCookies", "true");
logging.put("Bucket", "logs.s3.amazonaws.com");
logging.put("Prefix", "cf/");
config.setLogging(logging);
Distribution distribution = new Distribution();
distribution.setConfig(config);
String id = cloudFrontService.createDistribution(distribution, Map.of()).getId();
given()
.when()
.get(API + id)
.then()
.statusCode(200)
.body(hasXPath(LOGGING_ENABLED, equalTo("true")))
.body(hasXPath(LOGGING_INCLUDE_COOKIES, equalTo("true")))
.body(hasXPath(LOGGING_BUCKET, equalTo("logs.s3.amazonaws.com")))
.body(hasXPath(LOGGING_PREFIX, equalTo("cf/")));
}
/**
* A DistributionConfig request body, which is what an SDK or the Terraform provider
* actually sends. {@code loggingBlock} goes in verbatim so a caller that omits Logging
* and a caller that supplies it share one shape.
*/
private static String distributionConfigBody(String originId, String loggingBlock) {
return """
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
<CallerReference>%s</CallerReference>
<Enabled>true</Enabled>
<Comment>members-test-request-path</Comment>
%s
<Origins><Quantity>1</Quantity><Items><Origin>
<Id>%s</Id><DomainName>example.com</DomainName>
<CustomOriginConfig><HTTPPort>80</HTTPPort><HTTPSPort>443</HTTPSPort>
<OriginProtocolPolicy>http-only</OriginProtocolPolicy></CustomOriginConfig>
</Origin></Items></Origins>
<DefaultCacheBehavior>
<TargetOriginId>%s</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
</DefaultCacheBehavior>
</DistributionConfig>
""".formatted(originId, loggingBlock, originId, originId);
}
/** POSTs a config body and returns the id of the distribution it created. */
private static String postDistribution(String body) {
String response = given()
.contentType(ContentType.XML)
.body(body)
.when()
.post(DISTRIBUTIONS)
.then()
.statusCode(201)
.extract().asString();
// Distribution.Id is the first Id in the response; the origin ids come later.
return XmlParser.extractFirst(response, "Id", null);
}
@Test
void createDistributionParsesAnExplicitLoggingBlock() {
// Goes through the request path rather than the service, so the parser is what is
// under test: emitting Logging on reads while the parser drops it on writes still
// drifts, because the provider sends a configuration and reads defaults back.
String id = postDistribution(distributionConfigBody("origin-logging-request", """
<Logging>
<Enabled>true</Enabled>
<IncludeCookies>true</IncludeCookies>
<Bucket>request-logs.s3.amazonaws.com</Bucket>
<Prefix>request/</Prefix>
</Logging>"""));
given()
.when()
.get(API + id + "/config")
.then()
.statusCode(200)
.body(hasXPath(LOGGING_ENABLED, equalTo("true")))
.body(hasXPath(LOGGING_INCLUDE_COOKIES, equalTo("true")))
.body(hasXPath(LOGGING_BUCKET, equalTo("request-logs.s3.amazonaws.com")))
.body(hasXPath(LOGGING_PREFIX, equalTo("request/")));
}
@Test
void createDistributionWithoutALoggingBlockKeepsTheDisabledDefaults() {
String id = postDistribution(distributionConfigBody("origin-logging-request-absent", ""));
given()
.when()
.get(API + id + "/config")
.then()
.statusCode(200)
.body(hasXPath(LOGGING_ENABLED, equalTo("false")))
.body(hasXPath(LOGGING_INCLUDE_COOKIES, equalTo("false")))
.body(hasXPath(LOGGING_BUCKET, equalTo("")))
.body(hasXPath(LOGGING_PREFIX, equalTo("")));
}
@Test
void updateDistributionParsesAnExplicitLoggingBlock() {
// Turning logging on for an existing distribution is an UpdateDistribution, which
// parses the body through the same path and must not drop the block either.
String id = postDistribution(distributionConfigBody("origin-logging-update", ""));
String etag = given()
.when()
.get(API + id + "/config")
.then()
.statusCode(200)
.extract().header("ETag");
given()
.contentType(ContentType.XML)
.header("If-Match", etag)
.body(distributionConfigBody("origin-logging-update", """
<Logging>
<Enabled>true</Enabled>
<IncludeCookies>false</IncludeCookies>
<Bucket>update-logs.s3.amazonaws.com</Bucket>
<Prefix>update/</Prefix>
</Logging>"""))
.when()
.put(API + id + "/config")
.then()
.statusCode(200)
.body(hasXPath(LOGGING_ENABLED, equalTo("true")))
.body(hasXPath(LOGGING_INCLUDE_COOKIES, equalTo("false")))
.body(hasXPath(LOGGING_BUCKET, equalTo("update-logs.s3.amazonaws.com")))
.body(hasXPath(LOGGING_PREFIX, equalTo("update/")));
}
}