diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEcrRepositoryTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEcrRepositoryTest.java new file mode 100644 index 0000000000..3ec65e8909 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEcrRepositoryTest.java @@ -0,0 +1,167 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.CloudFormationException; +import software.amazon.awssdk.services.cloudformation.model.CreateStackRequest; +import software.amazon.awssdk.services.cloudformation.model.DeleteStackRequest; +import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest; +import software.amazon.awssdk.services.cloudformation.model.Stack; +import software.amazon.awssdk.services.ecr.EcrClient; +import software.amazon.awssdk.services.ecr.model.DescribeRepositoriesRequest; +import software.amazon.awssdk.services.ecr.model.Repository; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@DisplayName("CloudFormation AWS::ECR::Repository") +class CloudFormationEcrRepositoryTest { + + private static CloudFormationClient cloudFormation; + private static EcrClient ecr; + private static String stackName; + private static String repoName; + + @BeforeAll + static void setup() { + cloudFormation = TestFixtures.cloudFormationClient(); + ecr = TestFixtures.ecrClient(); + stackName = TestFixtures.uniqueName("compat-cfn-ecr"); + repoName = TestFixtures.uniqueName("compat-cfn-repo").toLowerCase(); + } + + @AfterAll + static void cleanup() { + if (cloudFormation != null) { + try { + cloudFormation.deleteStack(DeleteStackRequest.builder().stackName(stackName).build()); + waitForDeleted(stackName, 30); + } catch (Exception e) { + System.err.println("CloudFormation ECR cleanup skipped: " + e.getMessage()); + } + cloudFormation.close(); + } + if (ecr != null) { + ecr.close(); + } + } + + @Test + void createsAndUpdatesImageScanningConfigurationThroughAwsSdk() throws InterruptedException { + cloudFormation.createStack(CreateStackRequest.builder() + .stackName(stackName) + .templateBody(templateWithScanOnPush(true, "MUTABLE")) + .build()); + assertThat(waitForTerminal(stackName, 30)).isEqualTo("CREATE_COMPLETE"); + + assertThat(describeRepo().imageScanningConfiguration().scanOnPush()).isTrue(); + + cloudFormation.updateStack(r -> r + .stackName(stackName) + .templateBody(templateWithScanOnPush(false, "MUTABLE"))); + assertThat(waitForTerminal(stackName, 30)).isEqualTo("UPDATE_COMPLETE"); + assertThat(describeRepo().imageScanningConfiguration().scanOnPush()).isFalse(); + + cloudFormation.updateStack(r -> r + .stackName(stackName) + .templateBody(templateWithScanOnPush(true, "MUTABLE"))); + assertThat(waitForTerminal(stackName, 30)).isEqualTo("UPDATE_COMPLETE"); + assertThat(describeRepo().imageScanningConfiguration().scanOnPush()).isTrue(); + + // Dropping ImageScanningConfiguration leaves the stored scanOnPush value intact. + cloudFormation.updateStack(r -> r + .stackName(stackName) + .templateBody(templateWithoutScanOnPush("IMMUTABLE"))); + assertThat(waitForTerminal(stackName, 30)).isEqualTo("UPDATE_COMPLETE"); + assertThat(describeRepo().imageScanningConfiguration().scanOnPush()).isTrue(); + + cloudFormation.deleteStack(DeleteStackRequest.builder().stackName(stackName).build()); + waitForDeleted(stackName, 30); + } + + private static Repository describeRepo() { + return ecr.describeRepositories(DescribeRepositoriesRequest.builder() + .repositoryNames(repoName) + .build()) + .repositories() + .get(0); + } + + private static String templateWithScanOnPush(boolean scanOnPush, String mutability) { + return """ + { + "Resources": { + "Repo": { + "Type": "AWS::ECR::Repository", + "Properties": { + "RepositoryName": "%s", + "ImageTagMutability": "%s", + "ImageScanningConfiguration": { + "ScanOnPush": %s + } + } + } + } + } + """.formatted(repoName, mutability, scanOnPush); + } + + private static String templateWithoutScanOnPush(String mutability) { + return """ + { + "Resources": { + "Repo": { + "Type": "AWS::ECR::Repository", + "Properties": { + "RepositoryName": "%s", + "ImageTagMutability": "%s" + } + } + } + } + """.formatted(repoName, mutability); + } + + private static String waitForTerminal(String name, int maxSeconds) throws InterruptedException { + long deadline = System.currentTimeMillis() + maxSeconds * 1000L; + while (System.currentTimeMillis() < deadline) { + List stacks = cloudFormation.describeStacks( + DescribeStacksRequest.builder().stackName(name).build()).stacks(); + if (!stacks.isEmpty()) { + String status = stacks.get(0).stackStatusAsString(); + if (!status.endsWith("_IN_PROGRESS")) { + return status; + } + } + Thread.sleep(500); + } + throw new AssertionError( + "Stack " + name + " did not reach a terminal state within " + maxSeconds + "s"); + } + + private static void waitForDeleted(String name, int maxSeconds) throws InterruptedException { + long deadline = System.currentTimeMillis() + maxSeconds * 1000L; + while (System.currentTimeMillis() < deadline) { + try { + List stacks = cloudFormation.describeStacks( + DescribeStacksRequest.builder().stackName(name).build()).stacks(); + if (stacks.isEmpty() + || "DELETE_COMPLETE".equals(stacks.get(0).stackStatusAsString())) { + return; + } + } catch (CloudFormationException e) { + if (e.getMessage() != null && e.getMessage().contains("does not exist")) { + return; + } + throw e; + } + Thread.sleep(500); + } + throw new AssertionError( + "Stack " + name + " was not deleted within " + maxSeconds + "s"); + } +} diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EcrCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EcrCfnProvisioner.java index c31523ff08..c3f99517d9 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EcrCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EcrCfnProvisioner.java @@ -103,6 +103,7 @@ public class EcrCfnProvisioner implements CfnResourceProvisioner { } String mutability = ctx.resolveOptional(props, "ImageTagMutability"); + Boolean scanOnPush = scanOnPush(props, ctx); Map tags = parseCfnTags(props != null ? props.get("Tags") : null, ctx); String region = ctx.region(); String lifecyclePolicy = lifecyclePolicyText(props, ctx); @@ -117,8 +118,8 @@ public class EcrCfnProvisioner implements CfnResourceProvisioner { // EncryptionConfiguration is create-only, so it is read only when the repository is created. JsonNode encryption = props != null ? props.get("EncryptionConfiguration") : null; Repository repo = reusing - ? reconcileExisting(repoName, mutability, tags, region) - : ecrService.createRepository(repoName, null, mutability, null, + ? reconcileExisting(repoName, mutability, scanOnPush, tags, region) + : ecrService.createRepository(repoName, null, mutability, scanOnPush, ctx.resolveOptional(encryption, "EncryptionType"), ctx.resolveOptional(encryption, "KmsKey"), tags, region); if (!reusing) { @@ -170,10 +171,11 @@ public class EcrCfnProvisioner implements CfnResourceProvisioner { * template's desired state (TagResource alone leaves unspecified tags in place, so dropped * keys are untagged first), and so is ImageTagMutability: a template that no longer declares * it means the MUTABLE default the API applies when the parameter is omitted, not "keep the - * previous value". Both are updatable in the registry schema. + * previous value". ImageScanningConfiguration is applied only when declared, leaving the + * stored setting intact if an update drops it. */ - private Repository reconcileExisting(String repoName, String mutability, Map tags, - String region) { + private Repository reconcileExisting(String repoName, String mutability, Boolean scanOnPush, + Map tags, String region) { List stale = ProvisionContext.staleTagKeys( ecrService.listTagsForResource(repoName, null, region), tags); if (!stale.isEmpty()) { @@ -182,8 +184,41 @@ public class EcrCfnProvisioner implements CfnResourceProvisioner { if (!tags.isEmpty()) { ecrService.tagResource(repoName, null, tags, region); } - return ecrService.putImageTagMutability(repoName, null, + Repository repo = ecrService.putImageTagMutability(repoName, null, mutability != null ? mutability : DEFAULT_IMAGE_TAG_MUTABILITY, region); + if (scanOnPush != null) { + repo = ecrService.putImageScanningConfiguration(repoName, null, scanOnPush, region); + } + return repo; + } + + /** {@code ImageScanningConfiguration.ScanOnPush}, or null when the template declares none. */ + private static Boolean scanOnPush(JsonNode props, ProvisionContext ctx) { + if (props == null || !props.has("ImageScanningConfiguration")) { + return null; + } + JsonNode config = ctx.engine().resolveNode(props.get("ImageScanningConfiguration")); + if (config == null || config.isNull() || config.isMissingNode() || !config.has("ScanOnPush")) { + return null; + } + JsonNode value = ctx.engine().resolveNode(config.get("ScanOnPush")); + if (value == null || value.isNull() || value.isMissingNode()) { + return null; + } + if (value.isBoolean()) { + return value.booleanValue(); + } + String text = value.asText(null); + if (text == null || text.isBlank()) { + return null; + } + if ("true".equalsIgnoreCase(text)) { + return Boolean.TRUE; + } + if ("false".equalsIgnoreCase(text)) { + return Boolean.FALSE; + } + return null; } /** {@code LifecyclePolicy.LifecyclePolicyText}, or null when the template declares none. */ diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/LeafCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/LeafCfnProvisionerTest.java index a907f406c3..d3e0a9bd89 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/LeafCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/LeafCfnProvisionerTest.java @@ -29,6 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -403,6 +404,77 @@ class LeafCfnProvisionerTest { verify(ecr, never()).deleteLifecyclePolicy(anyString(), any(), anyString()); } + @Test + void imageScanningConfigurationReachesCreateRepository() { + when(ecr.createRepository(eq("app"), eq(null), eq(null), eq(Boolean.TRUE), + eq(null), eq(null), any(), eq(REGION))) + .thenReturn(repo("arn:app", "uri:app")); + + provisioner.provision(resource("Repo", "AWS::ECR::Repository"), props(""" + {"RepositoryName": "app", "ImageScanningConfiguration": {"ScanOnPush": true}} + """), ctx); + + verify(ecr).createRepository(eq("app"), eq(null), eq(null), eq(Boolean.TRUE), + eq(null), eq(null), any(), eq(REGION)); + } + + @Test + void imageScanningConfigurationStringTrueFromRefReachesCreateRepository() { + when(ecr.createRepository(eq("app"), eq(null), eq(null), eq(Boolean.TRUE), + eq(null), eq(null), any(), eq(REGION))) + .thenReturn(repo("arn:app", "uri:app")); + + provisioner.provision(resource("Repo", "AWS::ECR::Repository"), props(""" + {"RepositoryName": "app", "ImageScanningConfiguration": {"ScanOnPush": "true"}} + """), ctx); + + verify(ecr).createRepository(eq("app"), eq(null), eq(null), eq(Boolean.TRUE), + eq(null), eq(null), any(), eq(REGION)); + } + + @Test + void omittedImageScanningConfigurationPassesNullToCreateRepository() { + when(ecr.createRepository(eq("app"), eq(null), eq(null), eq(null), + eq(null), eq(null), any(), eq(REGION))) + .thenReturn(repo("arn:app", "uri:app")); + + provisioner.provision(resource("Repo", "AWS::ECR::Repository"), props(""" + {"RepositoryName": "app"} + """), ctx); + + verify(ecr).createRepository(eq("app"), eq(null), eq(null), eq(null), + eq(null), eq(null), any(), eq(REGION)); + } + + @Test + void updatingImageScanningConfigurationCallsPutImageScanningConfiguration() { + Repository updated = repo("arn:updated", "uri:updated"); + when(ecr.putImageTagMutability("app", null, "MUTABLE", REGION)) + .thenReturn(repo("arn:existing", "uri:existing")); + when(ecr.putImageScanningConfiguration("app", null, true, REGION)) + .thenReturn(updated); + + StackResource r = resource("Repo", "AWS::ECR::Repository"); + provisioner.provision(r, props(""" + {"RepositoryName": "app", "ImageScanningConfiguration": {"ScanOnPush": true}} + """), new ProvisionContext(engine, REGION, "000000000000", "my-stack", "app")); + + verify(ecr).putImageScanningConfiguration("app", null, true, REGION); + assertEquals("arn:updated", r.getAttributes().get("Arn")); + } + + @Test + void droppingImageScanningConfigurationOnUpdateLeavesItUnchanged() { + when(ecr.putImageTagMutability("app", null, "MUTABLE", REGION)) + .thenReturn(repo("arn:existing", "uri:existing")); + + provisioner.provision(resource("Repo", "AWS::ECR::Repository"), props(""" + {"RepositoryName": "app"} + """), new ProvisionContext(engine, REGION, "000000000000", "my-stack", "app")); + + verify(ecr, never()).putImageScanningConfiguration(anyString(), any(), anyBoolean(), anyString()); + } + @Test void deleteForcesRemovalSoANonEmptyRepositoryStillGoes() { provisioner.delete("AWS::ECR::Repository", "app", REGION); diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index 823f41d10d..781c7ed40a 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -251,7 +251,6 @@ AWS::EC2::VPCEndpoint ServiceNetworkArn accepted and ignored AWS::EC2::VPCEndpoint ServiceRegion accepted and ignored AWS::EC2::VPCEndpoint Tags accepted and ignored AWS::ECR::Repository EmptyOnDelete accepted and ignored -AWS::ECR::Repository ImageScanningConfiguration accepted and ignored AWS::ECR::Repository ImageTagMutabilityExclusionFilters accepted and ignored AWS::ECS::CapacityProvider ClusterName accepted and ignored AWS::ECS::CapacityProvider ManagedInstancesProvider accepted and ignored