diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2FlowLogFormatTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2FlowLogFormatTest.java index 39da8df7fc..cd4d0c7dbd 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2FlowLogFormatTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2FlowLogFormatTest.java @@ -3,6 +3,8 @@ package com.floci.test; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.DestinationFileFormat; +import software.amazon.awssdk.services.ec2.model.DestinationOptionsResponse; import software.amazon.awssdk.services.ec2.model.FlowLog; import software.amazon.awssdk.services.ec2.model.FlowLogsResourceType; import software.amazon.awssdk.services.ec2.model.TrafficType; @@ -61,4 +63,34 @@ class Ec2FlowLogFormatTest { } } } + + @Test + @DisplayName("DescribeFlowLogs returns the DestinationOptions the s3 flow log was created with") + void describesTheDestinationOptions() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + String vpcId = ec2.createVpc(r -> r.cidrBlock("10.73.0.0/16")).vpc().vpcId(); + String flowLogId = null; + try { + flowLogId = ec2.createFlowLogs(r -> r.resourceIds(vpcId) + .resourceType(FlowLogsResourceType.VPC) + .trafficType(TrafficType.ALL) + .logDestinationType("s3") + .logDestination("arn:aws:s3:::flow-logs-bucket") + .destinationOptions(o -> o.fileFormat(DestinationFileFormat.PARQUET) + .hiveCompatiblePartitions(true) + .perHourPartition(true))).flowLogIds().get(0); + + DestinationOptionsResponse options = describe(ec2, flowLogId).destinationOptions(); + assertThat(options.fileFormat()).isEqualTo(DestinationFileFormat.PARQUET); + assertThat(options.hiveCompatiblePartitions()).isTrue(); + assertThat(options.perHourPartition()).isTrue(); + } finally { + if (flowLogId != null) { + String id = flowLogId; + ec2.deleteFlowLogs(r -> r.flowLogIds(id)); + } + ec2.deleteVpc(r -> r.vpcId(vpcId)); + } + } + } } diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 488af14d22..cb135b02c8 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -1493,7 +1493,7 @@ Validation matches AWS behavior: | Action | Description | |--------|-------------| -| CreateFlowLogs | Creates flow logs for the given resources; returns one flow log id per resource. A `vpc-flow-log` `TagSpecification` tags each one, and `DescribeFlowLogs` returns the tags. | +| CreateFlowLogs | Creates flow logs for the given resources; returns one flow log id per resource. A `vpc-flow-log` `TagSpecification` tags each one, and `DescribeFlowLogs` returns the tags. `DestinationOptions` (`FileFormat`, `HiveCompatiblePartitions`, `PerHourPartition`) are stored and returned by `DescribeFlowLogs`; an `s3` flow log created without them reports `plain-text`, `false`, `false`, and a `cloud-watch-logs` flow log omits the element. A partition flag that is not a boolean is refused. | | DescribeFlowLogs | Lists stored flow logs, optionally filtered by id. | | DeleteFlowLogs | Deletes the named flow logs. `DryRun=true` is answered with `DryRunOperation` and deletes nothing. | diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/Ec2FlowLogCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/Ec2FlowLogCfnProvisioner.java index 2e46824be9..2c2af95dd7 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/Ec2FlowLogCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/Ec2FlowLogCfnProvisioner.java @@ -3,6 +3,7 @@ package io.floci.aws.services.cloudformation.provisioners; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.JacksonConfig; import io.floci.aws.core.common.JsonNodes; +import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine; import io.floci.aws.services.cloudformation.model.StackResource; import io.floci.aws.services.ec2.Ec2Service; import io.floci.aws.services.ec2.FlowLogService; @@ -11,6 +12,7 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.JsonNodeType; import tools.jackson.databind.node.ObjectNode; import java.util.List; @@ -89,6 +91,7 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner { return; } } + JsonNode options = destinationOptionsBlock(props, ctx); FlowLog fl = flowLogService.createFlowLog(ctx.region(), ctx.resolveOptional(props, "ResourceId"), ctx.resolveOptional(props, "ResourceType"), @@ -100,7 +103,10 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner { ctx.resolveOptional(props, "LogFormat"), props != null && props.hasNonNull("MaxAggregationInterval") ? JsonNodes.asInt(props.get("MaxAggregationInterval"), 0) - : DEFAULT_MAX_AGGREGATION_INTERVAL); + : DEFAULT_MAX_AGGREGATION_INTERVAL, + ctx.resolveOptional(options, "FileFormat"), + ctx.resolveOptionalBoolean(options, "HiveCompatiblePartitions"), + ctx.resolveOptionalBoolean(options, "PerHourPartition")); String flowLogId = fl.getFlowLogId(); r.setPhysicalId(flowLogId); r.getAttributes().put("Id", flowLogId); @@ -206,6 +212,16 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner { rejectIfChanged("DeliverLogsPermissionArn", existing.getDeliverLogsPermissionArn(), ctx.resolveOptional(props, "DeliverLogsPermissionArn")); rejectIfChanged("LogFormat", existing.getLogFormat(), ctx.resolveOptional(props, "LogFormat")); + // Only an s3 log stored before its options were kept has none to compare, so any template + // reuses it. A non-s3 log stores none unless sent, so its absence is a real default. + if (!"s3".equals(existing.getLogDestinationType()) || existing.getDestinationFileFormat() != null) { + JsonNode options = destinationOptionsBlock(props, ctx); + rejectIfChanged("DestinationOptions", destinationOptions(existing.getDestinationFileFormat(), + existing.getHiveCompatiblePartitions(), existing.getPerHourPartition()), + destinationOptions(ctx.resolveOptional(options, "FileFormat"), + ctx.resolveOptionalBoolean(options, "HiveCompatiblePartitions"), + ctx.resolveOptionalBoolean(options, "PerHourPartition"))); + } int requestedInterval = props != null && props.hasNonNull("MaxAggregationInterval") ? JsonNodes.asInt(props.get("MaxAggregationInterval"), 0) : DEFAULT_MAX_AGGREGATION_INTERVAL; @@ -215,6 +231,25 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner { } } + /** The DestinationOptions block, resolved whole first because an intrinsic such as Fn::If can supply it. */ + private static JsonNode destinationOptionsBlock(JsonNode props, ProvisionContext ctx) { + JsonNode block = ctx.engine().resolvePropertyShape(props == null ? null : props.get("DestinationOptions")); + if (block != null && !block.isNull() && !block.isMissingNode()) { + // A call left unresolved, such as a Ref to a String parameter, is judged by what it yields. + if (CloudFormationTemplateEngine.callsIntrinsic(block)) { + block = ctx.engine().resolveNode(block); + } + CfnPropertyTypes.requireType("DestinationOptions", block, JsonNodeType.OBJECT); + } + return block; + } + + /** The three options with createFlowLog's defaults applied, so omitted and default compare equal. */ + private static String destinationOptions(String fileFormat, Boolean hive, Boolean perHour) { + return FlowLogService.effectiveFileFormat(fileFormat) + "/" + Boolean.TRUE.equals(hive) + "/" + + Boolean.TRUE.equals(perHour); + } + private static String orDefault(String requested, String fallback) { return requested == null || requested.isBlank() ? fallback : requested; } diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java index fab1695331..b7e38d8624 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java @@ -2254,6 +2254,11 @@ public class Ec2QueryHandler { String deliverLogsPermissionArn = p.getFirst("DeliverLogsPermissionArn"); String logFormat = p.getFirst("LogFormat"); int maxAgg = parseIntParam(p, "MaxAggregationInterval", 600); + String fileFormat = p.getFirst("DestinationOptions.FileFormat"); + Boolean hive = parseOptionalBoolean(p.getFirst("DestinationOptions.HiveCompatiblePartitions"), + "DestinationOptions.HiveCompatiblePartitions"); + Boolean perHour = parseOptionalBoolean(p.getFirst("DestinationOptions.PerHourPartition"), + "DestinationOptions.PerHourPartition"); if (resourceIds.isEmpty()) { // Some SDKs send ResourceIds.member.N — fall back to that prefix. @@ -2270,7 +2275,8 @@ public class Ec2QueryHandler { List flowLogTags = parseTagsForResource(p, "vpc-flow-log"); for (String resourceId : resourceIds) { FlowLog fl = flowLogService.createFlowLog(region, resourceId, resourceType, trafficType, - logDestinationType, logDestination, logGroupName, deliverLogsPermissionArn, logFormat, maxAgg); + logDestinationType, logDestination, logGroupName, deliverLogsPermissionArn, logFormat, maxAgg, + fileFormat, hive, perHour); if (!flowLogTags.isEmpty()) { service.createTags(region, List.of(fl.getFlowLogId()), flowLogTags); } @@ -2306,8 +2312,15 @@ public class Ec2QueryHandler { ? fl.getLogFormat() : FlowLogService.DEFAULT_LOG_FORMAT) .elem("deliverLogsStatus", fl.getDeliverLogsStatus()) .elem("maxAggregationInterval", String.valueOf(fl.getMaxAggregationInterval())) - .elem("creationTime", ISO_FMT.format(fl.getCreationTime())) - .raw(tagSetXml(service.resourceTags(region, fl.getFlowLogId()))) + .elem("creationTime", ISO_FMT.format(fl.getCreationTime())); + if (fl.getDestinationFileFormat() != null) { + xml.start("destinationOptions") + .elem("fileFormat", fl.getDestinationFileFormat()) + .elem("hiveCompatiblePartitions", String.valueOf(fl.getHiveCompatiblePartitions())) + .elem("perHourPartition", String.valueOf(fl.getPerHourPartition())) + .end("destinationOptions"); + } + xml.raw(tagSetXml(service.resourceTags(region, fl.getFlowLogId()))) .end("item"); } xml.end("flowLogSet").end("DescribeFlowLogsResponse"); diff --git a/src/main/java/io/floci/aws/services/ec2/FlowLogService.java b/src/main/java/io/floci/aws/services/ec2/FlowLogService.java index c93974a6cb..e492d70d69 100644 --- a/src/main/java/io/floci/aws/services/ec2/FlowLogService.java +++ b/src/main/java/io/floci/aws/services/ec2/FlowLogService.java @@ -158,14 +158,22 @@ public class FlowLogService { String logDestination, String deliverLogsPermissionArn, String logFormat, int maxAggregationInterval) { return createFlowLog(region, resourceId, resourceType, trafficType, logDestinationType, - logDestination, null, deliverLogsPermissionArn, logFormat, maxAggregationInterval); + logDestination, null, deliverLogsPermissionArn, logFormat, maxAggregationInterval, + null, null, null); + } + + /** The file format a flow log reports when none was sent. */ + public static String effectiveFileFormat(String fileFormat) { + return fileFormat != null && !fileFormat.isBlank() ? fileFormat : "plain-text"; } public FlowLog createFlowLog(String region, String resourceId, String resourceType, String trafficType, String logDestinationType, String logDestination, String logGroupName, String deliverLogsPermissionArn, - String logFormat, int maxAggregationInterval) { + String logFormat, int maxAggregationInterval, + String fileFormat, Boolean hiveCompatiblePartitions, + Boolean perHourPartition) { String groupName = effectiveLogGroupName(logDestination, logGroupName); FlowLog fl = new FlowLog(); fl.setFlowLogId("fl-" + randomHex(17)); @@ -179,6 +187,13 @@ public class FlowLogService { fl.setBucketName(bucketFromArn(logDestination)); fl.setLogFormat(logFormat); fl.setMaxAggregationInterval(maxAggregationInterval); + // AWS reports options only for an s3 destination, with plain-text/false/false when none were sent. + boolean s3 = "s3".equals(fl.getLogDestinationType()); + if (s3 || fileFormat != null || hiveCompatiblePartitions != null || perHourPartition != null) { + fl.setDestinationFileFormat(effectiveFileFormat(fileFormat)); + fl.setHiveCompatiblePartitions(Boolean.TRUE.equals(hiveCompatiblePartitions)); + fl.setPerHourPartition(Boolean.TRUE.equals(perHourPartition)); + } fl.setRegion(region); fl.setAccountId(ec2Service.callerAccountId()); flowLogs.put(fl.getFlowLogId(), fl); diff --git a/src/main/java/io/floci/aws/services/ec2/model/FlowLog.java b/src/main/java/io/floci/aws/services/ec2/model/FlowLog.java index 508b4378e3..5cbd8bd693 100644 --- a/src/main/java/io/floci/aws/services/ec2/model/FlowLog.java +++ b/src/main/java/io/floci/aws/services/ec2/model/FlowLog.java @@ -29,6 +29,9 @@ public class FlowLog { private String deliverLogsPermissionArn; // IAM role ARN used for cloud-watch-logs delivery private String bucketName; // resolved bucket name from the ARN private String logFormat; // optional custom format string (default format used if null) + private String destinationFileFormat; // plain-text | parquet; null when the destination takes no options + private Boolean hiveCompatiblePartitions; + private Boolean perHourPartition; private int maxAggregationInterval = 600; // seconds (60 or 600) private String region; private String accountId; @@ -68,6 +71,15 @@ public class FlowLog { public String getLogFormat() { return logFormat; } public void setLogFormat(String logFormat) { this.logFormat = logFormat; } + public String getDestinationFileFormat() { return destinationFileFormat; } + public void setDestinationFileFormat(String destinationFileFormat) { this.destinationFileFormat = destinationFileFormat; } + + public Boolean getHiveCompatiblePartitions() { return hiveCompatiblePartitions; } + public void setHiveCompatiblePartitions(Boolean hiveCompatiblePartitions) { this.hiveCompatiblePartitions = hiveCompatiblePartitions; } + + public Boolean getPerHourPartition() { return perHourPartition; } + public void setPerHourPartition(Boolean perHourPartition) { this.perHourPartition = perHourPartition; } + public int getMaxAggregationInterval() { return maxAggregationInterval; } public void setMaxAggregationInterval(int maxAggregationInterval) { this.maxAggregationInterval = maxAggregationInterval; } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationFlowLogDestinationOptionsIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationFlowLogDestinationOptionsIntegrationTest.java new file mode 100644 index 0000000000..ecfd963092 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationFlowLogDestinationOptionsIntegrationTest.java @@ -0,0 +1,65 @@ +package io.floci.aws.services.cloudformation; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.CfnStackWaits; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.Stack; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.DestinationOptionsResponse; + +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class CloudFormationFlowLogDestinationOptionsIntegrationTest { + + private static final String TEMPLATE = """ + { + "Resources": { + "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.45.0.0/16"}}, + "Bucket": {"Type": "AWS::S3::Bucket"}, + "Flow": { + "Type": "AWS::EC2::FlowLog", + "Properties": { + "ResourceId": {"Ref": "Vpc"}, + "ResourceType": "VPC", + "TrafficType": "ALL", + "LogDestinationType": "s3", + "LogDestination": {"Fn::GetAtt": ["Bucket", "Arn"]}, + "DestinationOptions": { + "FileFormat": "parquet", + "HiveCompatiblePartitions": true, + "PerHourPartition": true + } + } + } + }, + "Outputs": {"FlowId": {"Value": {"Ref": "Flow"}}} + } + """; + + @Test + void destinationOptionsReadBackFromDescribeFlowLogs() { + String stackName = "flow-options-" + UUID.randomUUID(); + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1); + Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + cfn.createStack(request -> request.stackName(stackName).templateBody(TEMPLATE)); + try { + Stack created = CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE"); + String flowId = CfnStackWaits.output(created, "FlowId"); + DestinationOptionsResponse options = ec2.describeFlowLogs(request -> request.flowLogIds(flowId)) + .flowLogs().getFirst().destinationOptions(); + assertEquals("parquet", options.fileFormatAsString()); + assertTrue(options.hiveCompatiblePartitions()); + assertTrue(options.perHourPartition()); + } finally { + CfnStackWaits.deleteStack(cfn, stackName); + } + } + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/Ec2FlowLogCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/Ec2FlowLogCfnProvisionerTest.java index 86c95a483a..0b8fec23ff 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/Ec2FlowLogCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/Ec2FlowLogCfnProvisionerTest.java @@ -109,7 +109,7 @@ class Ec2FlowLogCfnProvisionerTest { void flowLogSetsPhysicalIdAndIdAttribute() { when(flowLogs.createFlowLog(eq("us-east-1"), eq("vpc-123"), eq("VPC"), eq("ALL"), eq("cloud-watch-logs"), eq("arn:aws:logs:us-east-1:000000000000:log-group:flows"), isNull(), - eq("arn:aws:iam::000000000000:role/flow-logs-role"), eq("${srcaddr}"), eq(60))) + eq("arn:aws:iam::000000000000:role/flow-logs-role"), eq("${srcaddr}"), eq(60), isNull(), isNull(), isNull())) .thenReturn(flowLog("fl-0abc")); StackResource r = resource(); ObjectNode props = mapper.createObjectNode() @@ -130,12 +130,12 @@ class Ec2FlowLogCfnProvisionerTest { @Test void omittedAggregationIntervalDefaultsToTenMinutes() { - when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), anyInt())) + when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), anyInt(), any(), any(), any())) .thenReturn(flowLog("fl-0def")); provisioner.provision(resource(), mapper.createObjectNode().put("ResourceId", "vpc-9"), ctx()); - verify(flowLogs).createFlowLog("us-east-1", "vpc-9", null, null, null, null, null, null, null, 600); + verify(flowLogs).createFlowLog("us-east-1", "vpc-9", null, null, null, null, null, null, null, 600, null, null, null); } @Test @@ -153,7 +153,7 @@ class Ec2FlowLogCfnProvisionerTest { // A second flow log here outlives the stack: delete only knows the id recorded last. verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), - any(), anyInt()); + any(), anyInt(), any(), any(), any()); assertEquals("fl-0abc", r.getPhysicalId()); assertEquals("fl-0abc", r.getAttributes().get("Id")); } @@ -173,7 +173,178 @@ class Ec2FlowLogCfnProvisionerTest { mapper.createObjectNode().put("ResourceId", "vpc-123").put("TrafficType", "REJECT"), ctx())); assertEquals("ValidationError", e.getErrorCode()); verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), - any(), anyInt()); + any(), anyInt(), any(), any(), any()); + } + + private FlowLog parquetLog() { + FlowLog existing = flowLog("fl-0abc"); + existing.setResourceId("vpc-123"); + existing.setDestinationFileFormat("parquet"); + existing.setHiveCompatiblePartitions(false); + existing.setPerHourPartition(false); + when(flowLogs.describeFlowLogs("us-east-1", List.of("fl-0abc"))).thenReturn(List.of(existing)); + return existing; + } + + private ObjectNode withOptions(String fileFormat, Boolean hive, Boolean perHour) { + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + ObjectNode options = props.putObject("DestinationOptions"); + options.put("FileFormat", fileFormat); + options.put("HiveCompatiblePartitions", hive); + options.put("PerHourPartition", perHour); + return props; + } + + @ParameterizedTest + @ValueSource(strings = {"FileFormat", "HiveCompatiblePartitions", "PerHourPartition"}) + void changingDestinationOptionsReportsAnUnsupportedReplacement(String changed) { + StackResource r = resource(); + r.setPhysicalId("fl-0abc"); + parquetLog(); + ObjectNode props = withOptions("parquet", false, false); + ObjectNode options = (ObjectNode) props.get("DestinationOptions"); + if ("FileFormat".equals(changed)) { + options.put(changed, "plain-text"); + } else { + options.put(changed, true); + } + + AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx())); + assertEquals("ValidationError", e.getErrorCode()); + assertEquals("Updating DestinationOptions requires resource replacement, which is not supported.", + e.getMessage()); + } + + /** A block an intrinsic selects whole has to be resolved before its members are read. */ + @ParameterizedTest + @ValueSource(strings = { + "{\"Fn::Select\": [0, [{\"FileFormat\": \"parquet\", \"PerHourPartition\": true}]]}", + "{\"Fn::If\": [\"Unset\", {\"Ref\": \"AWS::NoValue\"}, {\"FileFormat\": \"parquet\", \"PerHourPartition\": true}]}" + }) + void destinationOptionsSelectedWholeByAnIntrinsicAreRead(String options) { + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.set("DestinationOptions", ProvisionContexts.json(options)); + when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), + any(), anyInt(), any(), any(), any())).thenReturn(flowLog("fl-0abc")); + provisioner.provision(resource(), props, ProvisionContexts.standalone(null, null)); + verify(flowLogs).createFlowLog(eq("us-east-1"), eq("vpc-123"), isNull(), isNull(), isNull(), isNull(), + isNull(), isNull(), isNull(), eq(600), eq("parquet"), isNull(), eq(true)); + + StackResource reused = resource(); + reused.setPhysicalId("fl-0abc"); + FlowLog existing = parquetLog(); + existing.setPerHourPartition(true); + provisioner.provision(reused, props, ProvisionContexts.standalone("fl-0abc", props)); + assertEquals("fl-0abc", reused.getPhysicalId()); + } + + @Test + void destinationOptionsAnIntrinsicOmitsTakeTheDefaults() { + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.set("DestinationOptions", ProvisionContexts.json( + "{\"Fn::If\": [\"Unset\", {\"FileFormat\": \"parquet\"}, {\"Ref\": \"AWS::NoValue\"}]}")); + when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), + any(), anyInt(), any(), any(), any())).thenReturn(flowLog("fl-0abc")); + provisioner.provision(resource(), props, ProvisionContexts.standalone(null, null)); + verify(flowLogs).createFlowLog(eq("us-east-1"), eq("vpc-123"), isNull(), isNull(), isNull(), isNull(), + isNull(), isNull(), isNull(), eq(600), isNull(), isNull(), isNull()); + } + + @Test + void aDestinationOptionsIntrinsicThatYieldsAStringIsRefused() { + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.set("DestinationOptions", ProvisionContexts.json("{\"Ref\": \"AWS::Region\"}")); + + AwsException e = assertThrows(AwsException.class, + () -> provisioner.provision(resource(), props, ProvisionContexts.standalone(null, null))); + + assertEquals("ValidationError", e.getErrorCode()); + verifyNoInteractions(flowLogs); + } + + @ParameterizedTest + @ValueSource(strings = {"HiveCompatiblePartitions", "PerHourPartition"}) + void aDestinationOptionThatIsNotABooleanIsRefused(String name) { + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.putObject("DestinationOptions").put(name, "yes"); + + AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(resource(), props, ctx())); + + assertEquals("ValidationError", e.getErrorCode()); + assertEquals("Value of property " + name + " must be a boolean.", e.getMessage()); + verifyNoInteractions(flowLogs); + } + + @Test + void aDestinationOptionsBlockThatIsNotAnObjectIsRefused() { + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123").put("DestinationOptions", "parquet"); + + AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(resource(), props, ctx())); + + assertEquals("ValidationError", e.getErrorCode()); + verifyNoInteractions(flowLogs); + } + + @Test + void droppingDestinationOptionsFromAParquetLogReportsAnUnsupportedReplacement() { + StackResource r = resource(); + r.setPhysicalId("fl-0abc"); + parquetLog(); + + assertThrows(AwsException.class, () -> provisioner.provision(r, + mapper.createObjectNode().put("ResourceId", "vpc-123"), ctx())); + } + + @Test + void omittedOrDefaultDestinationOptionsOnALogCreatedWithoutThemIsANoOp() { + StackResource r = resource(); + r.setPhysicalId("fl-0abc"); + FlowLog existing = flowLog("fl-0abc"); + existing.setResourceId("vpc-123"); + existing.setDestinationFileFormat("plain-text"); + existing.setHiveCompatiblePartitions(false); + existing.setPerHourPartition(false); + when(flowLogs.describeFlowLogs("us-east-1", List.of("fl-0abc"))).thenReturn(List.of(existing)); + + provisioner.provision(r, mapper.createObjectNode().put("ResourceId", "vpc-123"), ctx()); + provisioner.provision(r, withOptions("plain-text", false, false), ctx()); + + assertEquals("fl-0abc", r.getPhysicalId()); + verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), + any(), anyInt(), any(), any(), any()); + } + + @Test + void aLogStoredBeforeItsOptionsWereKeptReusesUnderAnyDestinationOptions() { + StackResource r = resource(); + r.setPhysicalId("fl-0abc"); + FlowLog existing = flowLog("fl-0abc"); + existing.setResourceId("vpc-123"); + when(flowLogs.describeFlowLogs("us-east-1", List.of("fl-0abc"))).thenReturn(List.of(existing)); + + provisioner.provision(r, withOptions("parquet", true, true), ctx()); + + assertEquals("fl-0abc", r.getPhysicalId()); + verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), + any(), anyInt(), any(), any(), any()); + } + + @Test + void addingDestinationOptionsToANonS3LogStoredWithoutThemReportsAnUnsupportedReplacement() { + StackResource r = resource(); + r.setPhysicalId("fl-0abc"); + FlowLog existing = flowLog("fl-0abc"); + existing.setResourceId("vpc-123"); + existing.setLogDestinationType("cloud-watch-logs"); + when(flowLogs.describeFlowLogs("us-east-1", List.of("fl-0abc"))).thenReturn(List.of(existing)); + + AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, + withOptions("parquet", null, null).put("LogDestinationType", "cloud-watch-logs"), ctx())); + assertEquals("Updating DestinationOptions requires resource replacement, which is not supported.", + e.getMessage()); + provisioner.provision(r, mapper.createObjectNode().put("ResourceId", "vpc-123") + .put("LogDestinationType", "cloud-watch-logs"), ctx()); + assertEquals("fl-0abc", r.getPhysicalId()); } @Test @@ -190,7 +361,7 @@ class Ec2FlowLogCfnProvisionerTest { .put("DeliverLogsPermissionArn", "arn:aws:iam::000000000000:role/new-role"), ctx())); assertEquals("ValidationError", e.getErrorCode()); verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), - any(), anyInt()); + any(), anyInt(), any(), any(), any()); } @Test @@ -249,7 +420,7 @@ class Ec2FlowLogCfnProvisionerTest { mapper.createObjectNode().put("ResourceId", "vpc-123"), ctx())); assertEquals("ValidationError", e.getErrorCode()); verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), - any(), anyInt()); + any(), anyInt(), any(), any(), any()); } @Test @@ -269,7 +440,7 @@ class Ec2FlowLogCfnProvisionerTest { assertEquals("fl-0abc", r.getPhysicalId()); verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), - any(), anyInt()); + any(), anyInt(), any(), any(), any()); } @Test @@ -316,7 +487,7 @@ class Ec2FlowLogCfnProvisionerTest { StackResource r = resource(); r.setPhysicalId("fl-gone"); when(flowLogs.describeFlowLogs("us-east-1", List.of("fl-gone"))).thenReturn(List.of()); - when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), anyInt())) + when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), anyInt(), any(), any(), any())) .thenReturn(flowLog("fl-new")); provisioner.provision(r, mapper.createObjectNode().put("ResourceId", "vpc-123"), ctx()); @@ -327,7 +498,7 @@ class Ec2FlowLogCfnProvisionerTest { @Test void createTagsTheNewFlowLog() { - when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), anyInt())) + when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), anyInt(), any(), any(), any())) .thenReturn(flowLog("fl-0abc")); ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); props.putArray("Tags").addObject().put("Key", "team").put("Value", "core"); @@ -347,7 +518,7 @@ class Ec2FlowLogCfnProvisionerTest { // Tags are the one property an update changes in place, so the log is kept, not replaced. verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), - any(), anyInt()); + any(), anyInt(), any(), any(), any()); // Only the key the previous template owned goes; AWS keeps one added through EC2. verify(ec2).deleteTags(eq("us-east-1"), eq(List.of("fl-0abc")), tags("old", "gone")); verify(ec2).createTags(eq("us-east-1"), eq(List.of("fl-0abc")), tags("team", "core")); @@ -422,7 +593,7 @@ class Ec2FlowLogCfnProvisionerTest { @Test void createRecordsTheTagKeysItWrote() { - when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), anyInt())) + when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), anyInt(), any(), any(), any())) .thenReturn(flowLog("fl-0abc")); StackResource r = resource(); ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); @@ -451,7 +622,7 @@ class Ec2FlowLogCfnProvisionerTest { assertThrows(AwsException.class, () -> provisioner.provision(resource(), props, ctx())); verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), - any(), anyInt()); + any(), anyInt(), any(), any(), any()); } @Test @@ -462,12 +633,12 @@ class Ec2FlowLogCfnProvisionerTest { assertThrows(AwsException.class, () -> provisioner.provision(resource(), props, ctx())); verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), - any(), anyInt()); + any(), anyInt(), any(), any(), any()); } @Test void aFailedTagWriteDeletesTheNewFlowLog() { - when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), anyInt())) + when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), anyInt(), any(), any(), any())) .thenReturn(flowLog("fl-0abc")); doThrow(new AwsException("InternalError", "tag store down", 500)) .when(ec2).createTags(anyString(), any(), any()); @@ -526,7 +697,7 @@ class Ec2FlowLogCfnProvisionerTest { r.setPhysicalId("fl-gone"); r.getAttributes().put(Ec2FlowLogCfnProvisioner.TAG_KEYS_ATTR, "[\"team\"]"); when(flowLogs.describeFlowLogs("us-east-1", List.of("fl-gone"))).thenReturn(List.of()); - when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), anyInt())) + when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), anyInt(), any(), any(), any())) .thenReturn(flowLog("fl-new")); provisioner.provision(r, mapper.createObjectNode().put("ResourceId", "vpc-123"), updateCtx("fl-gone")); assertEquals("fl-new", r.getPhysicalId()); diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java index e475b0dc04..baeba95a57 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java @@ -34,6 +34,7 @@ public final class ProvisionContexts { return node == null || node.isMissingNode() || node.isNull() ? null : JsonNodes.asText(node); }); when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + when(engine.resolvePropertyShape(any())).thenAnswer(inv -> inv.getArgument(0)); when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(inv -> inv.getArgument(0)); return engine; } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2FlowLogDestinationOptionsIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2FlowLogDestinationOptionsIntegrationTest.java new file mode 100644 index 0000000000..90de9ebc1d --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2FlowLogDestinationOptionsIntegrationTest.java @@ -0,0 +1,120 @@ +package io.floci.aws.services.ec2; + +import io.floci.aws.testing.Ec2Requests; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; + +/** + * DescribeFlowLogs reports the DestinationOptions the flow log was created with. + * + *

CreateFlowLogs ignored them and the describe never emitted them, so a client comparing its + * declared options against the live flow log saw them as unset and replaced the flow log on every + * plan. An s3 flow log created without options reports AWS's defaults. + */ +@QuarkusTest +class Ec2FlowLogDestinationOptionsIntegrationTest { + + private static final String ITEM = "DescribeFlowLogsResponse.flowLogSet.item.destinationOptions"; + + private static ValidatableResponse ec2(String action, String... formParams) { + RequestSpecification request = Ec2Requests.ec2(action, "test", "us-east-1"); + for (int i = 0; i < formParams.length; i += 2) { + request = request.formParam(formParams[i], formParams[i + 1]); + } + return request.when().post("/").then(); + } + + private static String vpc() { + return ec2("CreateVpc", "CidrBlock", "10.72.0.0/16") + .statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId"); + } + + private static String createS3FlowLog(String... extraParams) { + String[] params = { + "ResourceId.1", vpc(), + "ResourceType", "VPC", + "TrafficType", "ALL", + "LogDestinationType", "s3", + "LogDestination", "arn:aws:s3:::flow-logs-bucket" + }; + String[] all = new String[params.length + extraParams.length]; + System.arraycopy(params, 0, all, 0, params.length); + System.arraycopy(extraParams, 0, all, params.length, extraParams.length); + return ec2("CreateFlowLogs", all) + .statusCode(200).extract().path("CreateFlowLogsResponse.flowLogIdSet.item"); + } + + @Test + void destinationOptionsSurviveTheRoundTrip() { + String flowLogId = createS3FlowLog( + "DestinationOptions.FileFormat", "parquet", + "DestinationOptions.HiveCompatiblePartitions", "true", + "DestinationOptions.PerHourPartition", "true"); + + ec2("DescribeFlowLogs", "FlowLogId.1", flowLogId) + .statusCode(200) + .body(ITEM + ".fileFormat", equalTo("parquet")) + .body(ITEM + ".hiveCompatiblePartitions", equalTo("true")) + .body(ITEM + ".perHourPartition", equalTo("true")); + } + + @Test + void partialOptionsDefaultTheRest() { + String flowLogId = createS3FlowLog("DestinationOptions.FileFormat", "parquet"); + + ec2("DescribeFlowLogs", "FlowLogId.1", flowLogId) + .statusCode(200) + .body(ITEM + ".fileFormat", equalTo("parquet")) + .body(ITEM + ".hiveCompatiblePartitions", equalTo("false")) + .body(ITEM + ".perHourPartition", equalTo("false")); + } + + @Test + void anS3FlowLogWithoutOptionsReportsTheDefaults() { + String flowLogId = createS3FlowLog(); + + ec2("DescribeFlowLogs", "FlowLogId.1", flowLogId) + .statusCode(200) + .body(ITEM + ".fileFormat", equalTo("plain-text")) + .body(ITEM + ".hiveCompatiblePartitions", equalTo("false")) + .body(ITEM + ".perHourPartition", equalTo("false")); + } + + @ParameterizedTest + @ValueSource(strings = {"HiveCompatiblePartitions", "PerHourPartition"}) + void aDestinationOptionThatIsNotABooleanIsRefused(String name) { + ec2("CreateFlowLogs", + "ResourceId.1", vpc(), + "LogDestinationType", "s3", + "LogDestination", "arn:aws:s3:::flow-logs-bucket", + "DestinationOptions." + name, "yes") + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue")); + } + + /** The provider reads an absent element as "no block", which its diff suppression accepts. */ + @Test + void aCloudWatchLogsFlowLogOmitsDestinationOptions() { + String flowLogId = ec2("CreateFlowLogs", + "ResourceId.1", vpc(), + "ResourceType", "VPC", + "TrafficType", "ALL", + "LogDestinationType", "cloud-watch-logs", + "LogGroupName", "flow-logs-group") + .statusCode(200).extract().path("CreateFlowLogsResponse.flowLogIdSet.item"); + + ec2("DescribeFlowLogs", "FlowLogId.1", flowLogId) + .statusCode(200) + .body("DescribeFlowLogsResponse.flowLogSet.item.flowLogId", equalTo(flowLogId)) + .body("DescribeFlowLogsResponse.flowLogSet.item.children().collect { it.name() }", + not(hasItem("destinationOptions"))); + } +} diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index dffbf3dc38..e402658bb5 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -179,7 +179,6 @@ AWS::EC2::EIP NetworkBorderGroup accepted and ignored AWS::EC2::EIP PublicIpv4Pool accepted and ignored AWS::EC2::EIP TransferAddress accepted and ignored AWS::EC2::FlowLog DeliverCrossAccountRole accepted and ignored -AWS::EC2::FlowLog DestinationOptions accepted and ignored AWS::EC2::FlowLog TagFieldSpecifications accepted and ignored AWS::EC2::Instance AdditionalInfo accepted and ignored AWS::EC2::Instance Affinity accepted and ignored