From f1a6260a94ff1c225e2ec15aa1080eebf85b94bd Mon Sep 17 00:00:00 2001 From: Kal Cramer Date: Fri, 13 Nov 2026 13:30:10 -0700 Subject: [PATCH] feat(cloudformation): add AWS::EFS::FileSystem, MountTarget and AccessPoint (#8074) A template can now create the three EFS types. They are provisioned through EfsService, so a stack and a direct API call see the same file systems, mount targets and access points. - Ref and Fn::GetAtt resolve for every type. - Updates change ThroughputMode, ProvisionedThroughputInMibps, BackupPolicy, LifecyclePolicies, FileSystemPolicy, FileSystemProtection and tags in place; create-only properties replace the resource, and a failed update puts back what it changed. - Backups are off on create unless BackupPolicy is ENABLED or the file system is One Zone, and ThroughputMode provisioned requires ProvisionedThroughputInMibps. - Required properties are validated from the registry schema. Ref #7972 --- .../com/floci/test/CloudFormationEfsTest.java | 142 +++ docs/services/cloudformation.md | 1 + docs/services/efs.md | 19 + .../provisioners/CfnRollback.java | 20 + .../provisioners/EfsCfnProvisioner.java | 754 ++++++++++++++++ .../create-only-properties.json | 28 + .../cloudformation/CfnProvisionerFixture.java | 11 + .../CloudFormationEfsIntegrationTest.java | 450 ++++++++++ .../provisioners/EfsCfnProvisionerTest.java | 828 ++++++++++++++++++ .../io/floci/aws/testing/CfnRequests.java | 15 + .../cloudformation/schema-surface.tsv | 3 + .../supported-resource-types.tsv | 3 + .../cloudformation/writable-property-gaps.tsv | 2 + tools/docs/cfn_resource_types.yaml | 6 + 14 files changed, 2282 insertions(+) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEfsTest.java create mode 100644 src/main/java/io/floci/aws/services/cloudformation/provisioners/EfsCfnProvisioner.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/CloudFormationEfsIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/provisioners/EfsCfnProvisionerTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEfsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEfsTest.java new file mode 100644 index 0000000000..32f762f896 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEfsTest.java @@ -0,0 +1,142 @@ +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.efs.EfsClient; +import software.amazon.awssdk.services.efs.model.AccessPointDescription; +import software.amazon.awssdk.services.efs.model.FileSystemDescription; + +import java.time.Duration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +/** + * A stack that defines an EFS file system and access point, and a stack with a mount target, + * deployed and read back through the CloudFormation and EFS SDK clients. + */ +@DisplayName("CloudFormation EFS file system, access point and mount target") +class CloudFormationEfsTest { + + private static final Duration DEPLOY_TIMEOUT = + TestFixtures.isRealAws() ? Duration.ofMinutes(15) : Duration.ofSeconds(15); + private static final String STACK = TestFixtures.uniqueName("compat-cfn-efs"); + private static final String MOUNT_TARGET_STACK = TestFixtures.uniqueName("compat-cfn-efs-mt"); + + private static CloudFormationClient cfn; + private static EfsClient efs; + + @BeforeAll + static void setup() { + cfn = TestFixtures.cloudFormationClient(); + efs = TestFixtures.efsClient(); + } + + @AfterAll + static void cleanup() throws InterruptedException { + try { + if (cfn != null) { + // DeleteStack answers for a stack that is gone too, so a failure here is a real one. + CloudFormationStackTestHelper.deleteStack(cfn, STACK, STACK); + CloudFormationStackTestHelper.deleteStack(cfn, MOUNT_TARGET_STACK, MOUNT_TARGET_STACK); + } + } finally { + try { + if (cfn != null) { + cfn.close(); + } + } finally { + if (efs != null) { + efs.close(); + } + } + } + } + + @Test + @DisplayName("the file system and access point the stack created are described with the template's settings") + void fileSystemAndAccessPointAreDescribed() throws InterruptedException { + cfn.createStack(request -> request.stackName(STACK).templateBody(TEMPLATE)); + assertThat(TestFixtures.awaitStackTerminal(cfn, STACK, DEPLOY_TIMEOUT)).isEqualTo("CREATE_COMPLETE"); + + String fileSystemId = physicalId(STACK, "Files"); + String accessPointId = physicalId(STACK, "Data"); + + FileSystemDescription fileSystem = efs.describeFileSystems(request -> request.fileSystemId(fileSystemId)) + .fileSystems().get(0); + assertThat(fileSystem.fileSystemId()).startsWith("fs-"); + assertThat(fileSystem.tags()).anyMatch(tag -> tag.key().equals("env") && tag.value().equals("compat")); + + AccessPointDescription accessPoint = efs.describeAccessPoints(request -> request.accessPointId(accessPointId)) + .accessPoints().get(0); + assertThat(accessPoint.fileSystemId()).isEqualTo(fileSystemId); + assertThat(accessPoint.posixUser().uid()).isEqualTo(1000L); + assertThat(accessPoint.rootDirectory().path()).isEqualTo("/data"); + assertThat(accessPoint.rootDirectory().creationInfo().permissions()).isEqualTo("0755"); + } + + @Test + @DisplayName("a mount target created by the stack is deleted before its file system") + void mountTargetIsDeletedBeforeItsFileSystem() throws InterruptedException { + assumeFalse(TestFixtures.isRealAws(), "A mount target needs a real subnet and takes minutes to delete on AWS"); + cfn.createStack(request -> request.stackName(MOUNT_TARGET_STACK).templateBody(""" + { + "Resources": { + "Files": {"Type": "AWS::EFS::FileSystem", "Properties": {}}, + "Mount": { + "Type": "AWS::EFS::MountTarget", + "Properties": { + "FileSystemId": {"Ref": "Files"}, + "SubnetId": "subnet-0123456789abcdef0", + "SecurityGroups": ["sg-0123456789abcdef0"] + } + } + } + } + """)); + assertThat(TestFixtures.awaitStackTerminal(cfn, MOUNT_TARGET_STACK, DEPLOY_TIMEOUT)) + .isEqualTo("CREATE_COMPLETE"); + String fileSystemId = physicalId(MOUNT_TARGET_STACK, "Files"); + assertThat(efs.describeMountTargets(request -> request.fileSystemId(fileSystemId)).mountTargets()) + .singleElement() + .satisfies(mountTarget -> assertThat(mountTarget.subnetId()).isEqualTo("subnet-0123456789abcdef0")); + + // The stack only goes away if the file system delete was not refused for its mount target; + // a refused delete leaves DELETE_FAILED, which deleteStack reports as a failure. + CloudFormationStackTestHelper.deleteStack(cfn, MOUNT_TARGET_STACK, MOUNT_TARGET_STACK); + assertThat(efs.describeFileSystems().fileSystems()) + .noneMatch(fileSystem -> fileSystem.fileSystemId().equals(fileSystemId)); + } + + private static String physicalId(String stackName, String logicalId) { + return cfn.describeStackResource(request -> request.stackName(stackName).logicalResourceId(logicalId)) + .stackResourceDetail().physicalResourceId(); + } + + private static final String TEMPLATE = """ + { + "Resources": { + "Files": { + "Type": "AWS::EFS::FileSystem", + "Properties": { + "FileSystemTags": [{"Key": "env", "Value": "compat"}] + } + }, + "Data": { + "Type": "AWS::EFS::AccessPoint", + "Properties": { + "FileSystemId": {"Ref": "Files"}, + "PosixUser": {"Uid": "1000", "Gid": "1000"}, + "RootDirectory": { + "Path": "/data", + "CreationInfo": {"OwnerUid": "1000", "OwnerGid": "1000", "Permissions": "0755"} + } + } + } + } + } + """; +} diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index e146cbee69..6eca55b2be 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -204,6 +204,7 @@ cross-resource references. | Secrets Manager | `Secret`, `SecretTargetAttachment` | | ECR | `Repository` | | ECS | `Cluster`, `TaskDefinition`, `Service`, `CapacityProvider`, `ClusterCapacityProviderAssociations` | +| EFS | `FileSystem` (metadata only, there is no NFS data plane), `MountTarget` (`SecurityGroups` update in place, every other property replaces), `AccessPoint` (`AccessPointTags` update in place, every other property replaces) | | EKS | `Cluster`, `Nodegroup` | | RDS | `DBInstance` (starts a real container), `DBCluster` (starts a real container), `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup`, `DBProxy`, `DBProxyTargetGroup` | | Aurora DSQL | `Cluster` | diff --git a/docs/services/efs.md b/docs/services/efs.md index d6ca5fd71b..92dc654e44 100644 --- a/docs/services/efs.md +++ b/docs/services/efs.md @@ -38,6 +38,25 @@ The EFS emulator provides a metadata control plane for file systems, mount targe | `DescribeLifecycleConfiguration` | - | +## CloudFormation + +A template can create `AWS::EFS::FileSystem`, `AWS::EFS::MountTarget` and `AWS::EFS::AccessPoint`. They go through the same metadata control plane as the API, so a stack and a direct call see the same file systems. + +| Type | `Ref` | `Fn::GetAtt` | Updates in place | Replaces | +| --- | --- | --- | --- | --- | +| `AWS::EFS::FileSystem` | `FileSystemId` | `Arn`, `FileSystemId` | `ThroughputMode`, `ProvisionedThroughputInMibps`, `BackupPolicy`, `LifecyclePolicies`, `FileSystemPolicy`, `FileSystemProtection`, `FileSystemTags` | `Encrypted`, `KmsKeyId`, `PerformanceMode`, `AvailabilityZoneName` | +| `AWS::EFS::MountTarget` | mount target id | `Id`, `IpAddress` | `SecurityGroups` | `FileSystemId`, `SubnetId`, `IpAddress`, `IpAddressType`, `Ipv6Address` | +| `AWS::EFS::AccessPoint` | `AccessPointId` | `AccessPointId`, `Arn` | `AccessPointTags` | `FileSystemId`, `ClientToken`, `PosixUser`, `RootDirectory` | + +- **Replacement**: the new resource is created first and the displaced one is deleted once the stack update commits. A failed update deletes the new one and keeps the old. +- **Replacement that collides**: because the new resource exists before the old one is deleted, a replacement that keeps the old one's key is refused. A mount target is keyed by file system and subnet, so changing only `IpAddress`, `IpAddressType` or `Ipv6Address` fails with `Mount target already exists in this subnet`. An access point that keeps an explicit `ClientToken` fails the same way when `PosixUser` or `RootDirectory` changes. The update then rolls back and the old resource stays as it was. To change those properties, also change the subnet, or change the `ClientToken` or leave it out so a new one is generated. +- **Rollback**: a failed stack update puts back what it changed in place (throughput, backup and lifecycle settings, policy, protection, tags, security groups). +- **Dropped properties**: removing a property the previous template declared resets it to the AWS default. A setting made outside the stack is left alone, with one exception: `FileSystemTags` and `AccessPointTags` are driven to the template's set on every update, so a tag added outside the stack is removed. +- **Backup**: a file system that leaves `BackupPolicy` out is created with automatic backups off, or on when `AvailabilityZoneName` is set (One Zone). Dropping a declared `BackupPolicy` resets it to that same default. +- **Provisioned throughput**: `ThroughputMode: provisioned` requires `ProvisionedThroughputInMibps`, and `ProvisionedThroughputInMibps` is refused in any other mode. +- **Delete order**: a file system that still has mount targets fails with `FileSystemInUse`, as on AWS, so list the file system in the mount target's `FileSystemId` with `Ref` and let the stack delete the mount target first. +- **Not supported**: `ReplicationConfiguration` and `BypassPolicyLockoutSafetyCheck` are accepted and ignored. + ## Limitations - **Metadata Only**: Floci provides an EFS API simulation (the control plane) so you can provision file systems for your ECS tasks and Lambda functions. It does not provide an actual NFSv4.1 data plane endpoint. Reading or writing files via standard file-system mounts will fail. - **Lifecycle Evaluation**: Lifecycle policies are saved but no background worker evaluates them to move data across storage classes. Transition fields will remain static. diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java index b0839179aa..b176aff64a 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java @@ -386,6 +386,26 @@ public final class CfnRollback { */ public static final String NETWORK_CONNECTOR_UPDATE_SNAPSHOT_ATTR = "__FlociNetworkConnectorUpdateSnapshot"; + /** + * Holds the mutable configuration an EFS file system carried before an in-place update changed + * it (throughput, backup, lifecycle, policy, protection and tags), so a failed stack update can + * put it back. Written by {@code EfsCfnProvisioner} before it reconciles and spent by its + * {@code rollbackUpdate}. + */ + public static final String EFS_FILE_SYSTEM_UPDATE_SNAPSHOT_ATTR = "__FlociEfsFileSystemUpdateSnapshot"; + + /** + * Holds the security groups an EFS mount target carried before an in-place update changed them, + * so a failed stack update can put them back. + */ + public static final String EFS_MOUNT_TARGET_UPDATE_SNAPSHOT_ATTR = "__FlociEfsMountTargetUpdateSnapshot"; + + /** + * Holds the tags an EFS access point carried before an in-place update changed them, so a + * failed stack update can put them back. + */ + public static final String EFS_ACCESS_POINT_UPDATE_SNAPSHOT_ATTR = "__FlociEfsAccessPointUpdateSnapshot"; + private CfnRollback() { } diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EfsCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EfsCfnProvisioner.java new file mode 100644 index 0000000000..2ea0a26b49 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EfsCfnProvisioner.java @@ -0,0 +1,754 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.efs.EfsException; +import io.floci.aws.services.efs.EfsService; +import io.floci.aws.services.efs.model.AccessPointDescription; +import io.floci.aws.services.efs.model.BackupPolicy; +import io.floci.aws.services.efs.model.CreateAccessPointRequest; +import io.floci.aws.services.efs.model.CreateFileSystemRequest; +import io.floci.aws.services.efs.model.CreateMountTargetRequest; +import io.floci.aws.services.efs.model.CreationInfo; +import io.floci.aws.services.efs.model.DescribeMountTargetsRequest; +import io.floci.aws.services.efs.model.FileSystem; +import io.floci.aws.services.efs.model.IpAddressType; +import io.floci.aws.services.efs.model.LifecyclePolicy; +import io.floci.aws.services.efs.model.ModifyMountTargetSecurityGroupsRequest; +import io.floci.aws.services.efs.model.MountTarget; +import io.floci.aws.services.efs.model.PerformanceMode; +import io.floci.aws.services.efs.model.PosixUser; +import io.floci.aws.services.efs.model.ReplicationOverwriteProtection; +import io.floci.aws.services.efs.model.RootDirectory; +import io.floci.aws.services.efs.model.Tag; +import io.floci.aws.services.efs.model.TagResourceRequest; +import io.floci.aws.services.efs.model.ThroughputMode; +import io.floci.aws.services.efs.model.UpdateFileSystemProtectionRequest; +import io.floci.aws.services.efs.model.UpdateFileSystemRequest; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * CloudFormation provisioning for EFS: {@code AWS::EFS::FileSystem}, {@code AWS::EFS::MountTarget} + * and {@code AWS::EFS::AccessPoint}. + * + *

A file system is reconciled in place for the properties AWS updates without interruption + * (throughput, backup policy, lifecycle policies, file system policy, replication overwrite + * protection and tags). A mount target updates its security groups in place and an access point its + * tags. Every other property is create-only, so a change replaces the resource. An in-place update + * keeps a snapshot of what it changes on the resource, so a failed stack update can put it back. + * The displaced entity of a replacement is left to the {@link ReplacementCleanup} record: deleted + * once the update commits and named again on rollback. + */ +@ApplicationScoped +public class EfsCfnProvisioner implements CfnResourceProvisioner { + + static final String FILE_SYSTEM = "AWS::EFS::FileSystem"; + static final String MOUNT_TARGET = "AWS::EFS::MountTarget"; + static final String ACCESS_POINT = "AWS::EFS::AccessPoint"; + + private static final int CREATION_TOKEN_MAX_LENGTH = 64; + private static final String BACKUP_ENABLED = "ENABLED"; + private static final String BACKUP_DISABLED = "DISABLED"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final TypeReference> LIFECYCLE_POLICIES = + new TypeReference<>() { }; + + private final EfsService efsService; + + @Inject + public EfsCfnProvisioner(EfsService efsService) { + this.efsService = efsService; + } + + /** + * The mutable configuration a template asks for. A null member means the template says nothing + * and the stored value is left alone; a property the previous template declared and this one + * dropped is carried as its AWS default, so it is reset rather than left standing. + */ + private record Desired(ThroughputMode throughputMode, Double provisionedThroughput, String backupStatus, + List lifecyclePolicies, String policy, + ReplicationOverwriteProtection protection, Map tags) { + } + + @Override + public Set resourceTypes() { + return Set.of(FILE_SYSTEM, MOUNT_TARGET, ACCESS_POINT); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + // A snapshot describes the update in flight; one an earlier update left behind is stale. + r.getAttributes().remove(snapshotAttribute(r.getResourceType())); + if (ctx.isUpdate()) { + ReplacementCleanup.endRollbackRetry(r); + } + Map attributesBefore = Map.copyOf(r.getAttributes()); + switch (r.getResourceType()) { + case FILE_SYSTEM -> provisionFileSystem(r, props, ctx); + case MOUNT_TARGET -> provisionMountTarget(r, props, ctx); + case ACCESS_POINT -> provisionAccessPoint(r, props, ctx); + default -> throw new IllegalStateException("EfsCfnProvisioner cannot handle " + r.getResourceType()); + } + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + private static String snapshotAttribute(String resourceType) { + return switch (resourceType) { + case FILE_SYSTEM -> CfnRollback.EFS_FILE_SYSTEM_UPDATE_SNAPSHOT_ATTR; + case MOUNT_TARGET -> CfnRollback.EFS_MOUNT_TARGET_UPDATE_SNAPSHOT_ATTR; + case ACCESS_POINT -> CfnRollback.EFS_ACCESS_POINT_UPDATE_SNAPSHOT_ATTR; + default -> throw new IllegalStateException("EfsCfnProvisioner cannot handle " + resourceType); + }; + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + if (physicalId == null || physicalId.isBlank()) { + return; + } + switch (resourceType) { + // Only the service's own not-found code is tolerated: FileSystemInUse (mount targets + // still exist) must fail the stack delete, not be reported as a clean deletion. + case FILE_SYSTEM -> CfnDeletes.safeDelete("EFS file system", physicalId, + () -> efsService.deleteFileSystem(region, physicalId), "FileSystemNotFound"); + case MOUNT_TARGET -> CfnDeletes.safeDelete("EFS mount target", physicalId, + () -> efsService.deleteMountTarget(region, physicalId), "MountTargetNotFound"); + case ACCESS_POINT -> CfnDeletes.safeDelete("EFS access point", physicalId, + () -> efsService.deleteAccessPoint(region, physicalId), "AccessPointNotFound"); + default -> { } + } + } + + @Override + public boolean retainsFailedUpdateState(StackResource resource) { + return resource.getAttributes().containsKey(snapshotAttribute(resource.getResourceType())); + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + resource.getAttributes().remove(snapshotAttribute(resource.getResourceType())); + return ReplacementCleanup.complete(resource, this::delete); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(snapshotAttribute(resource.getResourceType())); + ReplacementCleanup.clear(resource); + } + + /** + * A replacement is undone through the cleanup record, and an update in place from the snapshot + * taken before it. The snapshot is spent only once the restore succeeded, so a restore that + * throws leaves it for ContinueUpdateRollback to retry. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + return true; + } + String attribute = snapshotAttribute(resource.getResourceType()); + String raw = resource.getAttributes().get(attribute); + if (raw == null) { + return false; + } + restoreFrom(resource.getResourceType(), readSnapshot(raw, resource)); + resource.getAttributes().remove(attribute); + return true; + } + + private void provisionFileSystem(StackResource r, JsonNode props, ProvisionContext ctx) { + String region = ctx.region(); + boolean encrypted = "true".equalsIgnoreCase(ctx.resolveOptional(props, "Encrypted")); + String kmsKeyId = blankToNull(ctx.resolveOptional(props, "KmsKeyId")); + PerformanceMode performanceMode = parseEnum(PerformanceMode.class, + ctx.resolveOptional(props, "PerformanceMode"), "PerformanceMode"); + String availabilityZone = blankToNull(ctx.resolveOptional(props, "AvailabilityZoneName")); + Desired desired = desired(props, ctx, availabilityZone != null); + requireProvisionedThroughput(desired); + + // Encrypted, KmsKeyId, PerformanceMode and AvailabilityZoneName are create-only, so a change + // to any of them, or a file system that is gone, is a replacement: a new file system is + // created and the displaced one is deleted once the update commits. + FileSystem prior = ctx.isUpdate() ? findFileSystem(ctx.priorPhysicalId(), region) : null; + boolean reuse = prior != null + && !createOnlyChanged(prior, encrypted, kmsKeyId, performanceMode, availabilityZone); + + FileSystem fileSystem; + if (reuse) { + fileSystem = prior; + r.getAttributes().put(CfnRollback.EFS_FILE_SYSTEM_UPDATE_SNAPSHOT_ATTR, + snapshot(prior, region).toString()); + } else { + if (desired.provisionedThroughput() != null && desired.throughputMode() != ThroughputMode.provisioned) { + throw new AwsException("ValidationError", + "ProvisionedThroughputInMibps is only valid when ThroughputMode is provisioned.", 400); + } + CreateFileSystemRequest request = new CreateFileSystemRequest(); + request.setCreationToken(ctx.generatePhysicalName(r.getLogicalId(), CREATION_TOKEN_MAX_LENGTH, false)); + request.setEncrypted(encrypted); + request.setKmsKeyId(kmsKeyId); + request.setPerformanceMode(performanceMode); + request.setAvailabilityZoneName(availabilityZone); + request.setThroughputMode(desired.throughputMode()); + request.setProvisionedThroughputInMibps(desired.provisionedThroughput()); + request.setBackup(backupOnCreate(desired.backupStatus(), availabilityZone != null)); + request.setTags(toTags(desired.tags())); + fileSystem = efsService.createFileSystem(request, region); + } + String fileSystemId = fileSystem.getFileSystemId(); + r.setPhysicalId(fileSystemId); + r.getAttributes().put("Arn", fileSystem.getFileSystemArn()); + r.getAttributes().put("FileSystemId", fileSystemId); + CfnRollback.guarded(r, ctx, !reuse, + () -> efsService.deleteFileSystem(region, fileSystemId), + () -> undoInPlace(r), + () -> reconcile(fileSystemId, desired, reuse, region)); + } + + private void provisionMountTarget(StackResource r, JsonNode props, ProvisionContext ctx) { + String region = ctx.region(); + String fileSystemId = required(ctx.resolveOptional(props, "FileSystemId"), "FileSystemId", MOUNT_TARGET); + String subnetId = required(ctx.resolveOptional(props, "SubnetId"), "SubnetId", MOUNT_TARGET); + if (props == null || !props.hasNonNull("SecurityGroups")) { + throw requiredProperty("SecurityGroups", MOUNT_TARGET); + } + String ipAddress = blankToNull(ctx.resolveOptional(props, "IpAddress")); + IpAddressType ipAddressType = parseEnum(IpAddressType.class, + ctx.resolveOptional(props, "IpAddressType"), "IpAddressType"); + String ipv6Address = blankToNull(ctx.resolveOptional(props, "Ipv6Address")); + List securityGroups = ctx.resolveStringList(props, "SecurityGroups"); + + // FileSystemId, SubnetId, IpAddress, IpAddressType and Ipv6Address are create-only, so a + // change to one, or a mount target that is gone, is a replacement. An address or address + // type the template leaves out is assigned by EFS, and is never compared unless the + // previous template declared it: removing a declared one is a change. + MountTarget prior = ctx.isUpdate() ? findMountTarget(ctx.priorPhysicalId(), region) : null; + boolean reuse = prior != null + && Objects.equals(fileSystemId, prior.getFileSystemId()) + && Objects.equals(subnetId, prior.getSubnetId()) + && createOnlyUnchanged(ipAddress, prior.getIpAddress(), "IpAddress", ctx) + && createOnlyUnchanged(ipAddressType, prior.getIpAddressType(), "IpAddressType", ctx) + && createOnlyUnchanged(ipv6Address, prior.getIpv6Address(), "Ipv6Address", ctx); + + MountTarget mountTarget; + if (reuse) { + mountTarget = prior; + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("region", region); + snapshot.put("mountTargetId", prior.getMountTargetId()); + ArrayNode priorGroups = snapshot.putArray("securityGroups"); + prior.getSecurityGroups().forEach(priorGroups::add); + r.getAttributes().put(CfnRollback.EFS_MOUNT_TARGET_UPDATE_SNAPSHOT_ATTR, snapshot.toString()); + } else { + CreateMountTargetRequest request = new CreateMountTargetRequest(); + request.setFileSystemId(fileSystemId); + request.setSubnetId(subnetId); + request.setIpAddress(ipAddress); + request.setIpAddressType(ipAddressType); + request.setIpv6Address(ipv6Address); + request.setSecurityGroups(securityGroups); + mountTarget = efsService.createMountTarget(request, region); + } + String mountTargetId = mountTarget.getMountTargetId(); + r.setPhysicalId(mountTargetId); + r.getAttributes().put("Id", mountTargetId); + if (mountTarget.getIpAddress() != null) { + r.getAttributes().put("IpAddress", mountTarget.getIpAddress()); + } + CfnRollback.guarded(r, ctx, !reuse, + () -> efsService.deleteMountTarget(region, mountTargetId), + () -> undoInPlace(r), + () -> { + if (reuse && !securityGroups.equals(mountTarget.getSecurityGroups())) { + modifySecurityGroups(region, mountTargetId, securityGroups); + } + }); + } + + private void provisionAccessPoint(StackResource r, JsonNode props, ProvisionContext ctx) { + String region = ctx.region(); + String fileSystemId = required(ctx.resolveOptional(props, "FileSystemId"), "FileSystemId", ACCESS_POINT); + String declaredToken = blankToNull(ctx.resolveOptional(props, "ClientToken")); + PosixUser posixUser = posixUser(props, ctx); + RootDirectory rootDirectory = rootDirectory(props, ctx); + Map tags = ctx.resolveTags(props, "AccessPointTags"); + + // Everything but the tags is create-only. A ClientToken the template leaves out is generated + // at create and never compared, unless the previous template declared one: removing it is + // a change. + AccessPointDescription prior = ctx.isUpdate() ? findAccessPoint(ctx.priorPhysicalId(), region) : null; + boolean reuse = prior != null + && Objects.equals(fileSystemId, prior.getFileSystemId()) + && createOnlyUnchanged(declaredToken, prior.getClientToken(), "ClientToken", ctx) + && Objects.equals(MAPPER.valueToTree(posixUser), MAPPER.valueToTree(prior.getPosixUser())) + && Objects.equals(MAPPER.valueToTree(rootDirectory), MAPPER.valueToTree(prior.getRootDirectory())); + + AccessPointDescription accessPoint; + if (reuse) { + accessPoint = prior; + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("region", region); + snapshot.put("accessPointId", prior.getAccessPointId()); + ObjectNode priorTags = snapshot.putObject("tags"); + tagMap(prior.getTags()).forEach(priorTags::put); + r.getAttributes().put(CfnRollback.EFS_ACCESS_POINT_UPDATE_SNAPSHOT_ATTR, snapshot.toString()); + } else { + CreateAccessPointRequest request = new CreateAccessPointRequest(); + request.setFileSystemId(fileSystemId); + request.setClientToken(declaredToken != null ? declaredToken + : ctx.generatePhysicalName(r.getLogicalId(), CREATION_TOKEN_MAX_LENGTH, false)); + request.setPosixUser(posixUser); + request.setRootDirectory(rootDirectory); + request.setTags(toTags(tags)); + accessPoint = efsService.createAccessPoint(region, request); + } + String accessPointId = accessPoint.getAccessPointId(); + r.setPhysicalId(accessPointId); + r.getAttributes().put("AccessPointId", accessPointId); + r.getAttributes().put("Arn", accessPoint.getAccessPointArn()); + CfnRollback.guarded(r, ctx, !reuse, + () -> efsService.deleteAccessPoint(region, accessPointId), + () -> undoInPlace(r), + () -> { + if (reuse) { + applyTags(accessPointId, tagMap(accessPoint.getTags()), tags, region); + } + }); + } + + /** + * Whether a create-only property is unchanged. A value the template declares must equal the + * prior one. A value it leaves out matches whatever EFS assigned, unless the previous template + * declared it, which makes the removal a change. + */ + private static boolean createOnlyUnchanged(Object declared, Object prior, String property, ProvisionContext ctx) { + if (declared == null) { + return !ctx.previouslyDeclared(property); + } + return declared.equals(prior); + } + + private static String required(String value, String property, String resourceType) { + if (value == null || value.isBlank()) { + throw requiredProperty(property, resourceType); + } + return value; + } + + private static AwsException requiredProperty(String property, String resourceType) { + return new AwsException("ValidationError", property + " is required for " + resourceType + ".", 400); + } + + private MountTarget findMountTarget(String mountTargetId, String region) { + DescribeMountTargetsRequest request = new DescribeMountTargetsRequest(); + request.setMountTargetId(mountTargetId); + List found = efsService.describeMountTargets(region, request).getMountTargets(); + return found.isEmpty() ? null : found.get(0); + } + + private AccessPointDescription findAccessPoint(String accessPointId, String region) { + List found = efsService.describeAccessPoints(region, null, accessPointId); + return found.isEmpty() ? null : found.get(0); + } + + private PosixUser posixUser(JsonNode props, ProvisionContext ctx) { + JsonNode node = resolvedProperty(props, "PosixUser", ctx); + if (node == null) { + return null; + } + PosixUser user = new PosixUser(); + user.setUid(parseLong(node.path("Uid"), "PosixUser.Uid")); + user.setGid(parseLong(node.path("Gid"), "PosixUser.Gid")); + if (node.path("SecondaryGids").isArray()) { + List secondary = new ArrayList<>(); + for (JsonNode gid : node.path("SecondaryGids")) { + secondary.add(parseLong(gid, "PosixUser.SecondaryGids")); + } + user.setSecondaryGids(secondary); + } + return user; + } + + private RootDirectory rootDirectory(JsonNode props, ProvisionContext ctx) { + JsonNode node = resolvedProperty(props, "RootDirectory", ctx); + if (node == null) { + return null; + } + RootDirectory directory = new RootDirectory(); + directory.setPath(blankToNull(node.path("Path").asText(null))); + JsonNode info = node.path("CreationInfo"); + if (info.isObject()) { + CreationInfo creationInfo = new CreationInfo(); + creationInfo.setOwnerUid(parseLong(info.path("OwnerUid"), "RootDirectory.CreationInfo.OwnerUid")); + creationInfo.setOwnerGid(parseLong(info.path("OwnerGid"), "RootDirectory.CreationInfo.OwnerGid")); + creationInfo.setPermissions(blankToNull(info.path("Permissions").asText(null))); + directory.setCreationInfo(creationInfo); + } + return directory; + } + + private static Long parseLong(JsonNode value, String property) { + if (value == null || value.isMissingNode() || value.isNull() || value.asText().isBlank()) { + return null; + } + try { + return Long.valueOf(value.asText().trim()); + } catch (NumberFormatException e) { + throw new AwsException("ValidationError", "Value of property " + property + " must be a number.", 400); + } + } + + private static Map tagMap(List tags) { + Map result = new LinkedHashMap<>(); + if (tags != null) { + for (Tag tag : tags) { + result.put(tag.getKey(), tag.getValue()); + } + } + return result; + } + + private void modifySecurityGroups(String region, String mountTargetId, List securityGroups) { + ModifyMountTargetSecurityGroupsRequest request = new ModifyMountTargetSecurityGroupsRequest(); + request.setMountTargetId(mountTargetId); + request.setSecurityGroups(securityGroups); + efsService.modifyMountTargetSecurityGroups(region, mountTargetId, request); + } + + private void restoreMountTarget(JsonNode snapshot) { + List securityGroups = new ArrayList<>(); + snapshot.path("securityGroups").forEach(group -> securityGroups.add(group.asText())); + modifySecurityGroups(snapshot.path("region").asText(), snapshot.path("mountTargetId").asText(), + securityGroups); + } + + private void restoreAccessPoint(JsonNode snapshot) { + String region = snapshot.path("region").asText(); + String accessPointId = snapshot.path("accessPointId").asText(); + Map tags = new LinkedHashMap<>(); + snapshot.path("tags").properties().forEach(tag -> tags.put(tag.getKey(), tag.getValue().asText())); + AccessPointDescription accessPoint = findAccessPoint(accessPointId, region); + if (accessPoint == null) { + throw EfsException.accessPointNotFound(accessPointId); + } + applyTags(accessPointId, tagMap(accessPoint.getTags()), tags, region); + } + + /** + * CreateFileSystem turns automatic backups on by default only for a One Zone file system, so + * a template that leaves {@code BackupPolicy} out gets them on for one and off for a regional + * one. + */ + private static boolean backupOnCreate(String declaredStatus, boolean oneZone) { + if (declaredStatus != null) { + return BACKUP_ENABLED.equals(declaredStatus); + } + return oneZone; + } + + /** AWS refuses {@code ThroughputMode: provisioned} with no throughput to provision. */ + private static void requireProvisionedThroughput(Desired desired) { + if (desired.throughputMode() == ThroughputMode.provisioned && desired.provisionedThroughput() == null) { + throw new AwsException("ValidationError", + "ProvisionedThroughputInMibps is required when ThroughputMode is provisioned.", 400); + } + } + + private Desired desired(JsonNode props, ProvisionContext ctx, boolean oneZone) { + ThroughputMode throughputMode = parseEnum(ThroughputMode.class, + ctx.resolveOptional(props, "ThroughputMode"), "ThroughputMode"); + if (throughputMode == null && ctx.previouslyDeclared("ThroughputMode")) { + throughputMode = ThroughputMode.bursting; + } + Double provisionedThroughput = null; + String provisionedText = ctx.resolveOptional(props, "ProvisionedThroughputInMibps"); + if (provisionedText != null && !provisionedText.isBlank()) { + try { + provisionedThroughput = Double.valueOf(provisionedText.trim()); + } catch (NumberFormatException e) { + throw new AwsException("ValidationError", + "Value of property ProvisionedThroughputInMibps must be a number.", 400); + } + } + + JsonNode backup = resolvedProperty(props, "BackupPolicy", ctx); + String backupStatus = backup == null ? null : blankToNull(backup.path("Status").asText(null)); + if (backupStatus != null) { + backupStatus = backupStatus.toUpperCase(); + } else if (ctx.previouslyDeclared("BackupPolicy")) { + backupStatus = oneZone ? BACKUP_ENABLED : BACKUP_DISABLED; + } + + List lifecyclePolicies = null; + JsonNode lifecycle = resolvedProperty(props, "LifecyclePolicies", ctx); + if (lifecycle != null && lifecycle.isArray()) { + lifecyclePolicies = new ArrayList<>(); + for (JsonNode item : lifecycle) { + if (item.isObject()) { + LifecyclePolicy policy = new LifecyclePolicy(); + policy.setTransitionToIA(item.path("TransitionToIA").asText(null)); + policy.setTransitionToPrimaryStorageClass( + item.path("TransitionToPrimaryStorageClass").asText(null)); + policy.setTransitionToArchive(item.path("TransitionToArchive").asText(null)); + lifecyclePolicies.add(policy); + } + } + } else if (ctx.previouslyDeclared("LifecyclePolicies")) { + lifecyclePolicies = new ArrayList<>(); + } + + // An empty string means "remove the policy", for a template that dropped a declared one. + String policy = null; + if (props != null && props.hasNonNull("FileSystemPolicy")) { + policy = ctx.engine().resolveJsonAttribute(props.get("FileSystemPolicy")); + } + if (policy == null || policy.isBlank()) { + policy = ctx.previouslyDeclared("FileSystemPolicy") ? "" : null; + } + + ReplicationOverwriteProtection protection = null; + JsonNode protectionNode = resolvedProperty(props, "FileSystemProtection", ctx); + if (protectionNode != null) { + protection = parseEnum(ReplicationOverwriteProtection.class, + protectionNode.path("ReplicationOverwriteProtection").asText(null), + "ReplicationOverwriteProtection"); + } + if (protection == null && ctx.previouslyDeclared("FileSystemProtection")) { + protection = ReplicationOverwriteProtection.ENABLED; + } + + return new Desired(throughputMode, provisionedThroughput, backupStatus, lifecyclePolicies, policy, + protection, ctx.resolveTags(props, "FileSystemTags")); + } + + /** The property resolved through the template, or null when it is absent, null or AWS::NoValue. */ + private static JsonNode resolvedProperty(JsonNode props, String name, ProvisionContext ctx) { + if (props == null || !props.hasNonNull(name)) { + return null; + } + JsonNode resolved = ctx.engine().resolveNodeOmittingNoValue(props.get(name)); + return resolved == null || resolved.isMissingNode() || resolved.isNull() ? null : resolved; + } + + private FileSystem findFileSystem(String fileSystemId, String region) { + try { + return efsService.getFileSystem(region, fileSystemId); + } catch (AwsException e) { + if (!"FileSystemNotFound".equals(e.getErrorCode())) { + throw e; + } + return null; + } + } + + private static boolean createOnlyChanged(FileSystem prior, boolean encrypted, String kmsKeyId, + PerformanceMode performanceMode, String availabilityZone) { + String desiredPerformance = performanceMode == null ? PerformanceMode.generalPurpose.name() + : performanceMode.name(); + return Boolean.TRUE.equals(prior.getEncrypted()) != encrypted + || !Objects.equals(prior.getKmsKeyId(), kmsKeyId) + || !desiredPerformance.equals(prior.getPerformanceMode()) + || !Objects.equals(prior.getAvailabilityZoneName(), availabilityZone); + } + + /** + * Drives an existing file system to the template's desired state, and sets what creation does + * not take (lifecycle, policy, protection) on a new one. A null member of {@code desired} is + * left alone. + */ + private void reconcile(String fileSystemId, Desired desired, boolean existing, String region) { + if (existing && (desired.throughputMode() != null || desired.provisionedThroughput() != null)) { + UpdateFileSystemRequest update = new UpdateFileSystemRequest(); + update.setThroughputMode(desired.throughputMode()); + update.setProvisionedThroughputInMibps(desired.provisionedThroughput()); + efsService.updateFileSystem(region, fileSystemId, update); + } + if (existing && desired.backupStatus() != null) { + efsService.putBackupPolicy(region, fileSystemId, backupPolicy(desired.backupStatus())); + } + if (desired.lifecyclePolicies() != null + && (existing || !desired.lifecyclePolicies().isEmpty())) { + efsService.putLifecycleConfiguration(region, fileSystemId, desired.lifecyclePolicies()); + } + if (desired.policy() != null) { + if (desired.policy().isEmpty()) { + efsService.deleteFileSystemPolicy(region, fileSystemId); + } else { + efsService.putFileSystemPolicy(region, fileSystemId, desired.policy()); + } + } + if (desired.protection() != null) { + UpdateFileSystemProtectionRequest protection = new UpdateFileSystemProtectionRequest(); + protection.setReplicationOverwriteProtection(desired.protection()); + efsService.updateFileSystemProtection(region, fileSystemId, protection); + } + if (existing) { + reconcileTags(fileSystemId, desired.tags(), region); + } + } + + /** Drives the tags to the template's set: a dropped key is untagged, as CloudFormation does. */ + private void reconcileTags(String fileSystemId, Map desired, String region) { + applyTags(fileSystemId, tagMap(efsService.getFileSystem(region, fileSystemId).getTags()), desired, region); + } + + private void applyTags(String resourceId, Map current, Map desired, + String region) { + List stale = ProvisionContext.staleTagKeys(current, desired); + if (!stale.isEmpty()) { + efsService.untagResource(region, resourceId, stale); + } + if (!desired.isEmpty()) { + TagResourceRequest request = new TagResourceRequest(); + request.setResourceId(resourceId); + request.setTags(toTags(desired)); + efsService.tagResource(region, request); + } + } + + private ObjectNode snapshot(FileSystem fileSystem, String region) { + String fileSystemId = fileSystem.getFileSystemId(); + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("region", region); + snapshot.put("fileSystemId", fileSystemId); + snapshot.put("throughputMode", fileSystem.getThroughputMode()); + if (fileSystem.getProvisionedThroughputInMibps() != null) { + snapshot.put("provisionedThroughputInMibps", fileSystem.getProvisionedThroughputInMibps()); + } + snapshot.put("backupStatus", efsService.getBackupPolicy(region, fileSystemId).getStatus()); + snapshot.set("lifecyclePolicies", + MAPPER.valueToTree(efsService.getLifecycleConfiguration(region, fileSystemId))); + try { + snapshot.put("policy", efsService.getFileSystemPolicy(region, fileSystemId)); + } catch (AwsException e) { + if (!"PolicyNotFound".equals(e.getErrorCode())) { + throw e; + } + } + if (fileSystem.getFileSystemProtection() != null + && fileSystem.getFileSystemProtection().getReplicationOverwriteProtection() != null) { + snapshot.put("protection", + fileSystem.getFileSystemProtection().getReplicationOverwriteProtection().name()); + } + ObjectNode tags = snapshot.putObject("tags"); + for (Tag tag : fileSystem.getTags()) { + tags.put(tag.getKey(), tag.getValue()); + } + return snapshot; + } + + private JsonNode readSnapshot(String raw, StackResource resource) { + try { + return MAPPER.readTree(raw); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Could not read the EFS file system update snapshot for " + + resource.getLogicalId(), e); + } + } + + private void restore(JsonNode snapshot) { + String region = snapshot.path("region").asText(); + String fileSystemId = snapshot.path("fileSystemId").asText(); + UpdateFileSystemRequest throughput = new UpdateFileSystemRequest(); + throughput.setThroughputMode(parseEnum(ThroughputMode.class, + snapshot.path("throughputMode").asText(null), "ThroughputMode")); + if (snapshot.hasNonNull("provisionedThroughputInMibps")) { + throughput.setProvisionedThroughputInMibps(snapshot.get("provisionedThroughputInMibps").asDouble()); + } + efsService.updateFileSystem(region, fileSystemId, throughput); + efsService.putBackupPolicy(region, fileSystemId, backupPolicy(snapshot.path("backupStatus").asText())); + efsService.putLifecycleConfiguration(region, fileSystemId, + MAPPER.convertValue(snapshot.path("lifecyclePolicies"), LIFECYCLE_POLICIES)); + if (snapshot.hasNonNull("policy")) { + efsService.putFileSystemPolicy(region, fileSystemId, snapshot.get("policy").asText()); + } else { + efsService.deleteFileSystemPolicy(region, fileSystemId); + } + if (snapshot.hasNonNull("protection")) { + UpdateFileSystemProtectionRequest protection = new UpdateFileSystemProtectionRequest(); + protection.setReplicationOverwriteProtection( + ReplicationOverwriteProtection.valueOf(snapshot.get("protection").asText())); + efsService.updateFileSystemProtection(region, fileSystemId, protection); + } + Map tags = new LinkedHashMap<>(); + snapshot.path("tags").properties().forEach(tag -> tags.put(tag.getKey(), tag.getValue().asText())); + reconcileTags(fileSystemId, tags, region); + } + + private void undoInPlace(StackResource r) { + String attribute = snapshotAttribute(r.getResourceType()); + String raw = r.getAttributes().get(attribute); + if (raw == null) { + return; + } + restoreFrom(r.getResourceType(), readSnapshot(raw, r)); + r.getAttributes().remove(attribute); + } + + private void restoreFrom(String resourceType, JsonNode snapshot) { + switch (resourceType) { + case FILE_SYSTEM -> restore(snapshot); + case MOUNT_TARGET -> restoreMountTarget(snapshot); + case ACCESS_POINT -> restoreAccessPoint(snapshot); + default -> throw new IllegalStateException("EfsCfnProvisioner cannot handle " + resourceType); + } + } + + private static BackupPolicy backupPolicy(String status) { + BackupPolicy policy = new BackupPolicy(); + policy.setStatus(status); + return policy; + } + + private static List toTags(Map tags) { + List result = new ArrayList<>(); + tags.forEach((key, value) -> { + Tag tag = new Tag(); + tag.setKey(key); + tag.setValue(value); + result.add(tag); + }); + return result; + } + + private static > E parseEnum(Class type, String value, String property) { + if (value == null || value.isBlank()) { + return null; + } + for (E constant : type.getEnumConstants()) { + if (constant.name().equalsIgnoreCase(value.trim())) { + return constant; + } + } + throw new AwsException("ValidationError", "Value '" + value + "' is not valid for property " + + property + ".", 400); + } + + private static String blankToNull(String value) { + return value == null || value.isBlank() ? null : value; + } +} diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index 64df5db397..6cb745d3a2 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -468,6 +468,34 @@ "IpcMode", "EphemeralStorage" ], + "AWS::EFS::AccessPoint": [ + "FileSystemId", + "ClientToken", + "CreationInfo", + "CreationInfo/OwnerUid", + "CreationInfo/OwnerGid", + "CreationInfo/Permissions", + "PosixUser", + "PosixUser/Uid", + "PosixUser/Gid", + "PosixUser/SecondaryGids", + "RootDirectory", + "RootDirectory/Path", + "RootDirectory/CreationInfo" + ], + "AWS::EFS::FileSystem": [ + "AvailabilityZoneName", + "Encrypted", + "KmsKeyId", + "PerformanceMode" + ], + "AWS::EFS::MountTarget": [ + "IpAddress", + "Ipv6Address", + "IpAddressType", + "SubnetId", + "FileSystemId" + ], "AWS::EKS::Cluster": [ "OutpostConfig", "EncryptionConfig", diff --git a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java index 1ea6aee03c..08d0ec3ec1 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java @@ -68,6 +68,7 @@ import io.floci.aws.services.cloudformation.provisioners.Ec2VpcGatewayAttachment import io.floci.aws.services.cloudformation.provisioners.EcrCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.EcsCapacityCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.EcsCfnProvisioner; +import io.floci.aws.services.cloudformation.provisioners.EfsCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.EksCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.ElastiCacheCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.ElastiCacheServerlessCfnProvisioner; @@ -139,6 +140,7 @@ import io.floci.aws.services.ec2.Ec2Service; import io.floci.aws.services.ec2.FlowLogService; import io.floci.aws.services.ecr.EcrService; import io.floci.aws.services.ecs.EcsService; +import io.floci.aws.services.efs.EfsService; import io.floci.aws.services.eks.EksService; import io.floci.aws.services.elasticache.ElastiCacheMemcachedService; import io.floci.aws.services.elasticache.ElastiCacheServerlessService; @@ -246,6 +248,7 @@ final class CfnProvisionerFixture { private CustomResourceResponseStore customResourceResponseStore; private ContainerReachableEndpoint reachableEndpoint; private EcsService ecsService; + private EfsService efsService; private ElbV2Service elbV2Service; private StepFunctionsService stepFunctionsService; private BatchService batchService; @@ -424,6 +427,9 @@ final class CfnProvisionerFixture { discovered.add(new EcsCapacityCfnProvisioner(ecsService)); discovered.add(new EcsCfnProvisioner(ecsService)); } + if (efsService != null) { + discovered.add(new EfsCfnProvisioner(efsService)); + } if (apiGatewayService != null) { discovered.add(new ApiGatewayAccountCfnProvisioner(apiGatewayService)); discovered.add(new ApiGatewayApiKeyCfnProvisioner(apiGatewayService)); @@ -710,6 +716,11 @@ final class CfnProvisionerFixture { return this; } + public Builder efs(EfsService v) { + this.efsService = v; + return this; + } + public Builder elbV2(ElbV2Service v) { this.elbV2Service = v; return this; diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEfsIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEfsIntegrationTest.java new file mode 100644 index 0000000000..624adaead1 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEfsIntegrationTest.java @@ -0,0 +1,450 @@ +package io.floci.aws.services.cloudformation; + +import io.floci.aws.testing.CfnRequests; +import io.floci.aws.testing.CfnStackWaits; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static io.floci.aws.testing.CfnRequests.describe; +import static io.floci.aws.testing.CfnRequests.output; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * End-to-end check that CloudFormation provisions the EFS types for real, into EfsService, and + * that {@code Ref} and each {@code Fn::GetAtt} key resolve to the created entity rather than the + * stub arm's fake ARN. EFS is metadata only, so the test is Docker-free. + */ +@QuarkusTest +class CloudFormationEfsIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; + + private static String template(String fileSystemProperties, String mountTargetSecurityGroup) { + return """ + { + "Resources": { + "Files": { + "Type": "AWS::EFS::FileSystem", + "Properties": {%s} + }, + "Mount": { + "Type": "AWS::EFS::MountTarget", + "Properties": { + "FileSystemId": {"Ref": "Files"}, + "SubnetId": "subnet-0123456789abcdef0", + "SecurityGroups": ["%s"] + } + }, + "Data": { + "Type": "AWS::EFS::AccessPoint", + "Properties": { + "FileSystemId": {"Ref": "Files"}, + "PosixUser": {"Uid": "1000", "Gid": "1001"}, + "RootDirectory": { + "Path": "/data", + "CreationInfo": {"OwnerUid": "1000", "OwnerGid": "1001", "Permissions": "0755"} + } + } + } + }, + "Outputs": { + "FsId": {"Value": {"Ref": "Files"}}, + "FsArn": {"Value": {"Fn::GetAtt": ["Files", "Arn"]}}, + "FsGetAttId": {"Value": {"Fn::GetAtt": ["Files", "FileSystemId"]}}, + "MtId": {"Value": {"Ref": "Mount"}}, + "MtGetAttId": {"Value": {"Fn::GetAtt": ["Mount", "Id"]}}, + "MtIp": {"Value": {"Fn::GetAtt": ["Mount", "IpAddress"]}}, + "ApId": {"Value": {"Ref": "Data"}}, + "ApGetAttId": {"Value": {"Fn::GetAtt": ["Data", "AccessPointId"]}}, + "ApArn": {"Value": {"Fn::GetAtt": ["Data", "Arn"]}} + } + } + """.formatted(fileSystemProperties, mountTargetSecurityGroup); + } + + private static void createStack(String stackName, String template) { + CfnRequests.deploy("CreateStack", stackName, template, CFN_AUTH, "CREATE_COMPLETE"); + } + + private static void updateStack(String stackName, String template) { + CfnRequests.deploy("UpdateStack", stackName, template, CFN_AUTH, "UPDATE_COMPLETE"); + } + + private static void submitUpdate(String stackName, String template) { + CfnRequests.cfn("UpdateStack", stackName) + .header("Authorization", CFN_AUTH) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + } + + private static String suffix() { + return Long.toString(System.nanoTime(), 36); + } + + @Test + void createStackProvisionsTheThreeEfsTypesAndResolvesRefAndGetAtt() { + String stackName = "cfn-efs-create-" + suffix(); + createStack(stackName, template("\"Encrypted\": false, \"FileSystemTags\": [{\"Key\": \"env\", \"Value\": \"dev\"}]", + "sg-aaaa1111")); + try { + XmlPath stack = describe(stackName, CFN_AUTH); + String fileSystemId = output(stack, "FsId"); + assertTrue(fileSystemId.startsWith("fs-"), fileSystemId); + assertEquals(fileSystemId, output(stack, "FsGetAttId")); + assertTrue(output(stack, "FsArn").endsWith(":file-system/" + fileSystemId), output(stack, "FsArn")); + + String mountTargetId = output(stack, "MtId"); + assertTrue(mountTargetId.startsWith("fsmt-"), mountTargetId); + assertEquals(mountTargetId, output(stack, "MtGetAttId")); + assertTrue(output(stack, "MtIp").matches("\\d+\\.\\d+\\.\\d+\\.\\d+"), output(stack, "MtIp")); + + String accessPointId = output(stack, "ApId"); + assertTrue(accessPointId.startsWith("fsap-"), accessPointId); + assertEquals(accessPointId, output(stack, "ApGetAttId")); + assertTrue(output(stack, "ApArn").endsWith(":access-point/" + accessPointId), output(stack, "ApArn")); + + given().queryParam("FileSystemId", fileSystemId) + .when().get("/2015-02-01/file-systems") + .then().statusCode(200) + .body("FileSystems", hasSize(1)) + .body("FileSystems[0].NumberOfMountTargets", equalTo(1)) + .body("FileSystems[0].Tags[0].Key", equalTo("env")); + + given().queryParam("AccessPointId", accessPointId) + .when().get("/2015-02-01/access-points") + .then().statusCode(200) + .body("AccessPoints[0].FileSystemId", equalTo(fileSystemId)) + .body("AccessPoints[0].PosixUser.Uid", equalTo(1000)) + .body("AccessPoints[0].RootDirectory.Path", equalTo("/data")) + .body("AccessPoints[0].RootDirectory.CreationInfo.Permissions", equalTo("0755")); + } finally { + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + } + + @Test + void updateChangesMutablePropertiesInPlaceKeepingEveryPhysicalId() { + String stackName = "cfn-efs-inplace-" + suffix(); + createStack(stackName, template("\"Encrypted\": false", "sg-aaaa1111")); + try { + XmlPath before = describe(stackName, CFN_AUTH); + + updateStack(stackName, template(""" + "Encrypted": false, + "ThroughputMode": "provisioned", + "ProvisionedThroughputInMibps": 64, + "FileSystemTags": [{"Key": "team", "Value": "core"}]""", "sg-bbbb2222")); + + XmlPath after = describe(stackName, CFN_AUTH); + assertEquals(output(before, "FsId"), output(after, "FsId")); + assertEquals(output(before, "MtId"), output(after, "MtId")); + assertEquals(output(before, "ApId"), output(after, "ApId")); + + given().queryParam("FileSystemId", output(after, "FsId")) + .when().get("/2015-02-01/file-systems") + .then().statusCode(200) + .body("FileSystems[0].ThroughputMode", equalTo("provisioned")) + .body("FileSystems[0].ProvisionedThroughputInMibps", equalTo(64.0f)) + .body("FileSystems[0].Tags[0].Key", equalTo("team")); + + given() + .when().get("/2015-02-01/mount-targets/" + output(after, "MtId") + "/security-groups") + .then().statusCode(200) + .body("SecurityGroups", equalTo(List.of("sg-bbbb2222"))); + } finally { + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + } + + @Test + void createOnlyChangeReplacesTheFileSystemAndDeletesTheDisplacedOne() { + String stackName = "cfn-efs-replace-" + suffix(); + createStack(stackName, template("\"Encrypted\": false", "sg-aaaa1111")); + try { + XmlPath before = describe(stackName, CFN_AUTH); + String oldFileSystemId = output(before, "FsId"); + String oldMountTargetId = output(before, "MtId"); + + updateStack(stackName, template("\"Encrypted\": true", "sg-aaaa1111")); + + XmlPath after = describe(stackName, CFN_AUTH); + assertNotEquals(oldFileSystemId, output(after, "FsId")); + // The mount target and access point follow the file system they reference. + assertNotEquals(oldMountTargetId, output(after, "MtId")); + assertNotEquals(output(before, "ApId"), output(after, "ApId")); + + given().queryParam("FileSystemId", oldFileSystemId) + .when().get("/2015-02-01/file-systems") + .then().statusCode(404); + given().queryParam("FileSystemId", output(after, "FsId")) + .when().get("/2015-02-01/file-systems") + .then().statusCode(200) + .body("FileSystems[0].Encrypted", equalTo(true)) + .body("FileSystems[0].NumberOfMountTargets", equalTo(1)); + } finally { + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + } + + @Test + void deleteStackRemovesTheMountTargetAndAccessPointBeforeTheFileSystem() { + String stackName = "cfn-efs-delete-" + suffix(); + createStack(stackName, template("\"Encrypted\": false", "sg-aaaa1111")); + XmlPath stack = describe(stackName, CFN_AUTH); + String fileSystemId = output(stack, "FsId"); + String accessPointId = output(stack, "ApId"); + + // A file system with a mount target cannot be deleted, so the stack delete succeeding + // means the mount target went first. + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + + given().queryParam("FileSystemId", fileSystemId) + .when().get("/2015-02-01/file-systems") + .then().statusCode(404); + given().queryParam("FileSystemId", fileSystemId) + .when().get("/2015-02-01/mount-targets") + .then().statusCode(200) + .body("MountTargets", empty()); + given().queryParam("AccessPointId", accessPointId) + .when().get("/2015-02-01/access-points") + .then().statusCode(200) + .body("AccessPoints", empty()); + } + + @Test + void ipv6OnlyMountTargetHasNoIpv4AddressAndSurvivesAnUpdate() { + String stackName = "cfn-efs-ipv6-" + suffix(); + String template = """ + { + "Resources": { + "Files": {"Type": "AWS::EFS::FileSystem", "Properties": {}}, + "Mount": { + "Type": "AWS::EFS::MountTarget", + "Properties": { + "FileSystemId": {"Ref": "Files"}, + "SubnetId": "subnet-0123456789abcdef0", + "IpAddressType": "IPV6_ONLY", + "SecurityGroups": ["%s"] + } + } + }, + "Outputs": { + "FsId": {"Value": {"Ref": "Files"}}, + "MtId": {"Value": {"Ref": "Mount"}} + } + } + """; + createStack(stackName, template.formatted("sg-aaaa1111")); + try { + XmlPath stack = describe(stackName, CFN_AUTH); + String fileSystemId = output(stack, "FsId"); + String mountTargetId = output(stack, "MtId"); + + given().queryParam("MountTargetId", mountTargetId) + .when().get("/2015-02-01/mount-targets") + .then().statusCode(200) + .body("MountTargets[0].IpAddressType", equalTo("IPV6_ONLY")) + .body("MountTargets[0].IpAddress", nullValue()); + + updateStack(stackName, template.formatted("sg-bbbb2222")); + + assertEquals(mountTargetId, output(describe(stackName, CFN_AUTH), "MtId")); + given().queryParam("FileSystemId", fileSystemId) + .when().get("/2015-02-01/mount-targets") + .then().statusCode(200) + .body("MountTargets", hasSize(1)) + .body("MountTargets[0].SecurityGroups", equalTo(List.of("sg-bbbb2222"))); + } finally { + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + } + + @Test + void mountTargetCreatedWithoutASubnetIsRejected() { + String stackName = "cfn-efs-nosubnet-" + suffix(); + createStack(stackName, """ + {"Resources": {"Files": {"Type": "AWS::EFS::FileSystem", "Properties": {}}}, + "Outputs": {"FsId": {"Value": {"Ref": "Files"}}}} + """); + try { + String fileSystemId = output(describe(stackName, CFN_AUTH), "FsId"); + + given() + .contentType("application/json") + .body("{\"FileSystemId\": \"" + fileSystemId + "\"}") + .when() + .post("/2015-02-01/mount-targets") + .then() + .statusCode(400); + + given().queryParam("FileSystemId", fileSystemId) + .when().get("/2015-02-01/mount-targets") + .then().statusCode(200) + .body("MountTargets", empty()); + } finally { + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + } + + /** + * A replacement creates the new entity before the old one is deleted, so one that keeps the + * old entity's collision key (same file system and subnet for a mount target) is refused by + * EFS, the update rolls back, and the old mount target is left as it was. + */ + @Test + void mountTargetReplacementThatCollidesWithTheOldOneRollsBackAndKeepsIt() { + String stackName = "cfn-efs-mtcollide-" + suffix(); + String template = """ + { + "Resources": { + "Files": {"Type": "AWS::EFS::FileSystem", "Properties": {}}, + "Mount": { + "Type": "AWS::EFS::MountTarget", + "Properties": { + "FileSystemId": {"Ref": "Files"}, + "SubnetId": "subnet-0123456789abcdef0", + "IpAddress": "%s", + "SecurityGroups": ["sg-aaaa1111"] + } + } + }, + "Outputs": { + "FsId": {"Value": {"Ref": "Files"}}, + "MtId": {"Value": {"Ref": "Mount"}} + } + } + """; + createStack(stackName, template.formatted("10.0.0.21")); + try { + XmlPath before = describe(stackName, CFN_AUTH); + String fileSystemId = output(before, "FsId"); + String mountTargetId = output(before, "MtId"); + + submitUpdate(stackName, template.formatted("10.0.0.22")); + + CfnStackWaits.awaitStatus(stackName, "UPDATE_ROLLBACK_COMPLETE", CFN_AUTH); + assertEquals(mountTargetId, output(describe(stackName, CFN_AUTH), "MtId")); + given().queryParam("FileSystemId", fileSystemId) + .when().get("/2015-02-01/mount-targets") + .then().statusCode(200) + .body("MountTargets", hasSize(1)) + .body("MountTargets[0].MountTargetId", equalTo(mountTargetId)) + .body("MountTargets[0].IpAddress", equalTo("10.0.0.21")); + assertEquals("Mount target already exists in this subnet", + CfnStackWaits.failedResourceReason(stackName, CFN_AUTH)); + } finally { + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + } + + /** + * The same for an access point that keeps an explicit ClientToken: the token must stay + * unique, so changing a create-only property such as RootDirectory without changing the token + * is refused, the update rolls back and the old access point is left as it was. + */ + @Test + void accessPointReplacementThatKeepsItsClientTokenRollsBackAndKeepsTheOldOne() { + String stackName = "cfn-efs-apcollide-" + suffix(); + String template = """ + { + "Resources": { + "Files": {"Type": "AWS::EFS::FileSystem", "Properties": {}}, + "Data": { + "Type": "AWS::EFS::AccessPoint", + "Properties": { + "FileSystemId": {"Ref": "Files"}, + "ClientToken": "fixed-token-%s", + "RootDirectory": {"Path": "%s"} + } + } + }, + "Outputs": { + "FsId": {"Value": {"Ref": "Files"}}, + "ApId": {"Value": {"Ref": "Data"}} + } + } + """; + String token = suffix(); + createStack(stackName, template.formatted(token, "/one")); + try { + XmlPath before = describe(stackName, CFN_AUTH); + String accessPointId = output(before, "ApId"); + + submitUpdate(stackName, template.formatted(token, "/two")); + + CfnStackWaits.awaitStatus(stackName, "UPDATE_ROLLBACK_COMPLETE", CFN_AUTH); + assertEquals(accessPointId, output(describe(stackName, CFN_AUTH), "ApId")); + given().queryParam("FileSystemId", output(before, "FsId")) + .when().get("/2015-02-01/access-points") + .then().statusCode(200) + .body("AccessPoints", hasSize(1)) + .body("AccessPoints[0].AccessPointId", equalTo(accessPointId)) + .body("AccessPoints[0].RootDirectory.Path", equalTo("/one")); + assertEquals("Access point with client token fixed-token-" + token + " already exists.", + CfnStackWaits.failedResourceReason(stackName, CFN_AUTH)); + } finally { + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + } + + @Test + void mountTargetCreatedOutsideTheStackFailsTheFileSystemDelete() { + String stackName = "cfn-efs-inuse-" + suffix(); + String template = """ + { + "Resources": { + "Files": {"Type": "AWS::EFS::FileSystem", "Properties": {}} + }, + "Outputs": {"FsId": {"Value": {"Ref": "Files"}}} + } + """; + createStack(stackName, template); + String fileSystemId = output(describe(stackName, CFN_AUTH), "FsId"); + given() + .contentType("application/json") + .body("{\"FileSystemId\": \"" + fileSystemId + "\", \"SubnetId\": \"subnet-0123456789abcdef0\"}") + .when() + .post("/2015-02-01/mount-targets") + .then() + .statusCode(200); + + CfnRequests.cfn("DeleteStack", stackName) + .header("Authorization", CFN_AUTH) + .when() + .post("/") + .then() + .statusCode(200); + + CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName, CFN_AUTH); + assertEquals("DELETE_FAILED", state.status()); + String events = CfnRequests.cfn("DescribeStackEvents", stackName) + .header("Authorization", CFN_AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + assertTrue(events.contains("AWS::EFS::FileSystem" + + "DELETE_FAILED" + + "File system " + fileSystemId + " is in use."), events); + given().queryParam("FileSystemId", fileSystemId) + .when().get("/2015-02-01/file-systems") + .then().statusCode(200) + .body("FileSystems[0].FileSystemId", startsWith("fs-")); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/EfsCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EfsCfnProvisionerTest.java new file mode 100644 index 0000000000..8036c29e6b --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EfsCfnProvisionerTest.java @@ -0,0 +1,828 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine; +import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.efs.EfsException; +import io.floci.aws.services.efs.EfsService; +import io.floci.aws.services.efs.model.AccessPointDescription; +import io.floci.aws.services.efs.model.BackupPolicy; +import io.floci.aws.services.efs.model.CreateAccessPointRequest; +import io.floci.aws.services.efs.model.CreateFileSystemRequest; +import io.floci.aws.services.efs.model.CreateMountTargetRequest; +import io.floci.aws.services.efs.model.DescribeMountTargetsResponse; +import io.floci.aws.services.efs.model.FileSystem; +import io.floci.aws.services.efs.model.FileSystemProtectionDescription; +import io.floci.aws.services.efs.model.LifecyclePolicy; +import io.floci.aws.services.efs.model.ModifyMountTargetSecurityGroupsRequest; +import io.floci.aws.services.efs.model.MountTarget; +import io.floci.aws.services.efs.model.ReplicationOverwriteProtection; +import io.floci.aws.services.efs.model.Tag; +import io.floci.aws.services.efs.model.TagResourceRequest; +import io.floci.aws.services.efs.model.ThroughputMode; +import io.floci.aws.services.efs.model.UpdateFileSystemRequest; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +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.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class EfsCfnProvisionerTest { + + private static final String REGION = "us-east-1"; + private static final String FS_ID = "fs-0123456789abcdef0"; + + private final EfsService efs = mock(EfsService.class); + private final EfsCfnProvisioner provisioner = new EfsCfnProvisioner(efs); + private final ObjectMapper mapper = new ObjectMapper(); + + private ProvisionContext ctx(String priorPhysicalId, JsonNode priorProperties) { + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null ? null : node.asText(); + }); + when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(inv -> inv.getArgument(0)); + when(engine.resolveStringList(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + List values = new ArrayList<>(); + node.forEach(item -> values.add(item.asText())); + return values; + }); + when(engine.resolveJsonAttribute(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node.isTextual() ? node.asText() : node.toString(); + }); + return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId, + event -> { }, priorProperties); + } + + private ProvisionContext createCtx() { + return ctx(null, null); + } + + private StackResource resource() { + StackResource r = new StackResource(); + r.setLogicalId("Files"); + r.setResourceType("AWS::EFS::FileSystem"); + r.setAttributes(new HashMap<>()); + return r; + } + + private FileSystem fileSystem(String id) { + FileSystem fs = new FileSystem(); + fs.setFileSystemId(id); + fs.setFileSystemArn("arn:aws:elasticfilesystem:us-east-1:000000000000:file-system/" + id); + fs.setEncrypted(false); + fs.setPerformanceMode("generalPurpose"); + fs.setThroughputMode("bursting"); + fs.setTags(new ArrayList<>()); + FileSystemProtectionDescription protection = new FileSystemProtectionDescription(); + protection.setReplicationOverwriteProtection(ReplicationOverwriteProtection.ENABLED); + fs.setFileSystemProtection(protection); + return fs; + } + + private void stubExisting(FileSystem fs) { + when(efs.getFileSystem(REGION, fs.getFileSystemId())).thenReturn(fs); + BackupPolicy backup = new BackupPolicy(); + backup.setStatus("ENABLED"); + when(efs.getBackupPolicy(REGION, fs.getFileSystemId())).thenReturn(backup); + when(efs.getLifecycleConfiguration(REGION, fs.getFileSystemId())).thenReturn(new ArrayList<>()); + when(efs.getFileSystemPolicy(REGION, fs.getFileSystemId())) + .thenThrow(EfsException.policyNotFound(fs.getFileSystemId())); + } + + private ObjectNode props() { + return mapper.createObjectNode(); + } + + @Test + void createSetsPhysicalIdAndGetAttAttributes() { + when(efs.createFileSystem(any(), eq(REGION))).thenReturn(fileSystem(FS_ID)); + StackResource r = resource(); + + provisioner.provision(r, props(), createCtx()); + + assertEquals(FS_ID, r.getPhysicalId()); + assertEquals("arn:aws:elasticfilesystem:us-east-1:000000000000:file-system/" + FS_ID, + r.getAttributes().get("Arn")); + assertEquals(FS_ID, r.getAttributes().get("FileSystemId")); + } + + @Test + void createMapsPropertiesOntoTheRequest() throws Exception { + when(efs.createFileSystem(any(), eq(REGION))).thenReturn(fileSystem(FS_ID)); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"Encrypted": true, "KmsKeyId": "key-1", "PerformanceMode": "maxIO", + "ThroughputMode": "provisioned", "ProvisionedThroughputInMibps": 128, + "BackupPolicy": {"Status": "DISABLED"}, + "FileSystemTags": [{"Key": "env", "Value": "dev"}]}"""); + + provisioner.provision(resource(), props, createCtx()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CreateFileSystemRequest.class); + verify(efs).createFileSystem(captor.capture(), eq(REGION)); + CreateFileSystemRequest request = captor.getValue(); + assertEquals(Boolean.TRUE, request.getEncrypted()); + assertEquals("key-1", request.getKmsKeyId()); + assertEquals("maxIO", request.getPerformanceMode().name()); + assertEquals(ThroughputMode.provisioned, request.getThroughputMode()); + assertEquals(128.0, request.getProvisionedThroughputInMibps()); + assertEquals(Boolean.FALSE, request.getBackup()); + assertEquals(1, request.getTags().size()); + assertEquals("env", request.getTags().get(0).getKey()); + assertTrue(request.getCreationToken().startsWith("my-stack-Files-")); + } + + @Test + void createRejectsProvisionedThroughputOutsideProvisionedMode() throws Exception { + for (String mode : List.of("", "\"ThroughputMode\": \"bursting\",", "\"ThroughputMode\": \"elastic\",")) { + ObjectNode props = (ObjectNode) mapper.readTree( + "{" + mode + " \"ProvisionedThroughputInMibps\": 128}"); + + AwsException e = assertThrows(AwsException.class, + () -> provisioner.provision(resource(), props, createCtx())); + + assertEquals("ValidationError", e.getErrorCode()); + assertEquals("ProvisionedThroughputInMibps is only valid when ThroughputMode is provisioned.", + e.getMessage()); + } + verify(efs, never()).createFileSystem(any(), any()); + } + + @Test + void createWithoutABackupPolicyLeavesBackupsOffForARegionalFileSystem() { + when(efs.createFileSystem(any(), eq(REGION))).thenReturn(fileSystem(FS_ID)); + + provisioner.provision(resource(), props(), createCtx()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CreateFileSystemRequest.class); + verify(efs).createFileSystem(captor.capture(), eq(REGION)); + assertEquals(Boolean.FALSE, captor.getValue().getBackup()); + } + + @Test + void createWithoutABackupPolicyTurnsBackupsOnForAOneZoneFileSystem() throws Exception { + when(efs.createFileSystem(any(), eq(REGION))).thenReturn(fileSystem(FS_ID)); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"AvailabilityZoneName": "us-east-1a"}"""); + + provisioner.provision(resource(), props, createCtx()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CreateFileSystemRequest.class); + verify(efs).createFileSystem(captor.capture(), eq(REGION)); + assertEquals(Boolean.TRUE, captor.getValue().getBackup()); + } + + @Test + void createHonorsAnEnabledBackupPolicyOnARegionalFileSystem() throws Exception { + when(efs.createFileSystem(any(), eq(REGION))).thenReturn(fileSystem(FS_ID)); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"BackupPolicy": {"Status": "ENABLED"}}"""); + + provisioner.provision(resource(), props, createCtx()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CreateFileSystemRequest.class); + verify(efs).createFileSystem(captor.capture(), eq(REGION)); + assertEquals(Boolean.TRUE, captor.getValue().getBackup()); + } + + @Test + void createHonorsADisabledBackupPolicyOnAOneZoneFileSystem() throws Exception { + when(efs.createFileSystem(any(), eq(REGION))).thenReturn(fileSystem(FS_ID)); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"AvailabilityZoneName": "us-east-1a", "BackupPolicy": {"Status": "DISABLED"}}"""); + + provisioner.provision(resource(), props, createCtx()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CreateFileSystemRequest.class); + verify(efs).createFileSystem(captor.capture(), eq(REGION)); + assertEquals(Boolean.FALSE, captor.getValue().getBackup()); + } + + @Test + void provisionedThroughputModeWithoutAThroughputIsRejectedOnCreateAndUpdate() throws Exception { + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"ThroughputMode": "provisioned"}"""); + stubExisting(fileSystem(FS_ID)); + + AwsException onCreate = assertThrows(AwsException.class, + () -> provisioner.provision(resource(), props, createCtx())); + AwsException onUpdate = assertThrows(AwsException.class, + () -> provisioner.provision(resource(), props, ctx(FS_ID, mapper.createObjectNode()))); + + for (AwsException e : List.of(onCreate, onUpdate)) { + assertEquals("ValidationError", e.getErrorCode()); + assertEquals("ProvisionedThroughputInMibps is required when ThroughputMode is provisioned.", + e.getMessage()); + } + verify(efs, never()).createFileSystem(any(), any()); + verify(efs, never()).updateFileSystem(any(), any(), any()); + } + + @Test + void provisionedThroughputModeWithAThroughputIsAccepted() throws Exception { + when(efs.createFileSystem(any(), eq(REGION))).thenReturn(fileSystem(FS_ID)); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"ThroughputMode": "provisioned", "ProvisionedThroughputInMibps": 64}"""); + + provisioner.provision(resource(), props, createCtx()); + + verify(efs).createFileSystem(any(), eq(REGION)); + } + + @Test + void createAppliesLifecyclePolicyAndProtectionAfterCreation() throws Exception { + when(efs.createFileSystem(any(), eq(REGION))).thenReturn(fileSystem(FS_ID)); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"LifecyclePolicies": [{"TransitionToIA": "AFTER_30_DAYS"}], + "FileSystemPolicy": {"Version": "2012-10-17", "Statement": []}, + "FileSystemProtection": {"ReplicationOverwriteProtection": "DISABLED"}}"""); + + provisioner.provision(resource(), props, createCtx()); + + @SuppressWarnings("unchecked") + ArgumentCaptor> lifecycle = ArgumentCaptor.forClass(List.class); + verify(efs).putLifecycleConfiguration(eq(REGION), eq(FS_ID), lifecycle.capture()); + assertEquals("AFTER_30_DAYS", lifecycle.getValue().get(0).getTransitionToIA()); + verify(efs).putFileSystemPolicy(REGION, FS_ID, "{\"Version\":\"2012-10-17\",\"Statement\":[]}"); + verify(efs).updateFileSystemProtection(eq(REGION), eq(FS_ID), any()); + } + + @Test + void createWithoutOptionalPropertiesTouchesNothingElse() { + when(efs.createFileSystem(any(), eq(REGION))).thenReturn(fileSystem(FS_ID)); + + provisioner.provision(resource(), props(), createCtx()); + + verify(efs, never()).putLifecycleConfiguration(any(), any(), anyList()); + verify(efs, never()).putFileSystemPolicy(any(), any(), any()); + verify(efs, never()).deleteFileSystemPolicy(any(), any()); + verify(efs, never()).updateFileSystemProtection(any(), any(), any()); + verify(efs, never()).putBackupPolicy(any(), any(), any()); + } + + @Test + void failedFollowUpStepDeletesTheFileSystemItCreated() throws Exception { + when(efs.createFileSystem(any(), eq(REGION))).thenReturn(fileSystem(FS_ID)); + doThrow(EfsException.badRequest("bad policy")).when(efs).putFileSystemPolicy(any(), any(), any()); + ObjectNode props = (ObjectNode) mapper.readTree("{\"FileSystemPolicy\": {\"Statement\": []}}"); + + assertThrows(AwsException.class, () -> provisioner.provision(resource(), props, createCtx())); + + verify(efs).deleteFileSystem(REGION, FS_ID); + } + + @Test + void updateKeepsTheFileSystemAndReconcilesMutableProperties() throws Exception { + stubExisting(fileSystem(FS_ID)); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"ThroughputMode": "provisioned", "ProvisionedThroughputInMibps": 64, + "FileSystemTags": [{"Key": "team", "Value": "core"}]}"""); + StackResource r = resource(); + + provisioner.provision(r, props, ctx(FS_ID, null)); + + verify(efs, never()).createFileSystem(any(), any()); + assertEquals(FS_ID, r.getPhysicalId()); + ArgumentCaptor update = ArgumentCaptor.forClass(UpdateFileSystemRequest.class); + verify(efs).updateFileSystem(eq(REGION), eq(FS_ID), update.capture()); + assertEquals(ThroughputMode.provisioned, update.getValue().getThroughputMode()); + assertEquals(64.0, update.getValue().getProvisionedThroughputInMibps()); + ArgumentCaptor tags = ArgumentCaptor.forClass(TagResourceRequest.class); + verify(efs).tagResource(eq(REGION), tags.capture()); + assertEquals(FS_ID, tags.getValue().getResourceId()); + assertFalse(ReplacementCleanup.hasReplacement(r)); + } + + @Test + void updateUntagsKeysTheTemplateDropped() { + FileSystem fs = fileSystem(FS_ID); + Tag old = new Tag(); + old.setKey("old"); + old.setValue("v"); + fs.getTags().add(old); + stubExisting(fs); + + provisioner.provision(resource(), props(), ctx(FS_ID, null)); + + verify(efs).untagResource(REGION, FS_ID, List.of("old")); + } + + @Test + void updateResetsADroppedPolicyAndBackupPolicy() throws Exception { + stubExisting(fileSystem(FS_ID)); + JsonNode prior = mapper.readTree(""" + {"FileSystemPolicy": {"Statement": []}, "BackupPolicy": {"Status": "DISABLED"}}"""); + + provisioner.provision(resource(), props(), ctx(FS_ID, prior)); + + verify(efs).deleteFileSystemPolicy(REGION, FS_ID); + ArgumentCaptor backup = ArgumentCaptor.forClass(BackupPolicy.class); + verify(efs).putBackupPolicy(eq(REGION), eq(FS_ID), backup.capture()); + assertEquals("DISABLED", backup.getValue().getStatus()); + } + + @Test + void updateResetsADroppedBackupPolicyToEnabledForAOneZoneFileSystem() throws Exception { + FileSystem oneZone = fileSystem(FS_ID); + oneZone.setAvailabilityZoneName("us-east-1a"); + stubExisting(oneZone); + JsonNode prior = mapper.readTree(""" + {"AvailabilityZoneName": "us-east-1a", "BackupPolicy": {"Status": "DISABLED"}}"""); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"AvailabilityZoneName": "us-east-1a"}"""); + + provisioner.provision(resource(), props, ctx(FS_ID, prior)); + + ArgumentCaptor backup = ArgumentCaptor.forClass(BackupPolicy.class); + verify(efs).putBackupPolicy(eq(REGION), eq(FS_ID), backup.capture()); + assertEquals("ENABLED", backup.getValue().getStatus()); + } + + @Test + void updateLeavesAPolicySetOutsideTheStackAlone() { + stubExisting(fileSystem(FS_ID)); + + provisioner.provision(resource(), props(), ctx(FS_ID, mapper.createObjectNode())); + + verify(efs, never()).deleteFileSystemPolicy(any(), any()); + verify(efs, never()).putBackupPolicy(any(), any(), any()); + } + + @Test + void createOnlyChangeReplacesTheFileSystemAndOwesTheOldOneADelete() throws Exception { + stubExisting(fileSystem(FS_ID)); + when(efs.createFileSystem(any(), eq(REGION))).thenReturn(fileSystem("fs-new")); + StackResource r = resource(); + r.setPhysicalId(FS_ID); + ObjectNode props = (ObjectNode) mapper.readTree("{\"Encrypted\": true}"); + + provisioner.provision(r, props, ctx(FS_ID, null)); + + assertEquals("fs-new", r.getPhysicalId()); + assertNotEquals(FS_ID, r.getPhysicalId()); + assertTrue(provisioner.hasReplacementUpdate(r)); + assertEquals(FS_ID, provisioner.updateCleanupPhysicalId(r)); + verify(efs, never()).deleteFileSystem(REGION, FS_ID); + } + + @Test + void missingPriorFileSystemIsCreatedAgain() { + when(efs.getFileSystem(REGION, FS_ID)).thenThrow(EfsException.fileSystemNotFound(FS_ID)); + when(efs.createFileSystem(any(), eq(REGION))).thenReturn(fileSystem("fs-new")); + StackResource r = resource(); + + provisioner.provision(r, props(), ctx(FS_ID, null)); + + assertEquals("fs-new", r.getPhysicalId()); + } + + @Test + void completingAReplacementDeletesTheDisplacedFileSystem() throws Exception { + stubExisting(fileSystem(FS_ID)); + when(efs.createFileSystem(any(), eq(REGION))).thenReturn(fileSystem("fs-new")); + StackResource r = resource(); + r.setPhysicalId(FS_ID); + provisioner.provision(r, (ObjectNode) mapper.readTree("{\"Encrypted\": true}"), ctx(FS_ID, null)); + + provisioner.completeUpdate(r); + + verify(efs).deleteFileSystem(REGION, FS_ID); + } + + @Test + void failedInPlaceUpdateRestoresTheSnapshot() throws Exception { + FileSystem fs = fileSystem(FS_ID); + stubExisting(fs); + doThrow(EfsException.badRequest("nope")).doReturn(new FileSystemProtectionDescription()) + .when(efs).updateFileSystemProtection(any(), any(), any()); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"ThroughputMode": "provisioned", "ProvisionedThroughputInMibps": 64, + "FileSystemProtection": {"ReplicationOverwriteProtection": "DISABLED"}}"""); + StackResource r = resource(); + + assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx(FS_ID, null))); + + ArgumentCaptor update = ArgumentCaptor.forClass(UpdateFileSystemRequest.class); + verify(efs, times(2)).updateFileSystem(eq(REGION), eq(FS_ID), update.capture()); + assertEquals(ThroughputMode.bursting, update.getAllValues().get(1).getThroughputMode()); + assertNull(r.getAttributes().get(CfnRollback.EFS_FILE_SYSTEM_UPDATE_SNAPSHOT_ATTR)); + } + + @Test + void rollbackRestoresTheSnapshotAndSpendsIt() throws Exception { + stubExisting(fileSystem(FS_ID)); + StackResource r = resource(); + provisioner.provision(r, props(), ctx(FS_ID, null)); + assertTrue(provisioner.retainsFailedUpdateState(r)); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(efs).putBackupPolicy(eq(REGION), eq(FS_ID), any()); + assertFalse(provisioner.retainsFailedUpdateState(r)); + } + + @Test + void rollbackWithNothingRecordedReportsNotRolledBack() { + assertFalse(provisioner.rollbackUpdate(resource())); + } + + @Test + void deleteToleratesAFileSystemThatIsAlreadyGone() { + doThrow(EfsException.fileSystemNotFound(FS_ID)).when(efs).deleteFileSystem(REGION, FS_ID); + + provisioner.delete("AWS::EFS::FileSystem", FS_ID, REGION); + } + + @Test + void deleteFailsWhileMountTargetsRemain() { + doThrow(EfsException.fileSystemInUse(FS_ID)).when(efs).deleteFileSystem(REGION, FS_ID); + + AwsException e = assertThrows(AwsException.class, + () -> provisioner.delete("AWS::EFS::FileSystem", FS_ID, REGION)); + + assertEquals("FileSystemInUse", e.getErrorCode()); + } + + private static final String MT_ID = "fsmt-0123456789abcdef0"; + private static final String AP_ID = "fsap-0123456789abcdef0"; + + private MountTarget mountTarget(String id, String subnet, List groups) { + MountTarget mt = new MountTarget(); + mt.setMountTargetId(id); + mt.setFileSystemId(FS_ID); + mt.setSubnetId(subnet); + mt.setIpAddress("10.0.0.10"); + mt.setSecurityGroups(new ArrayList<>(groups)); + return mt; + } + + private void stubMountTargetLookup(MountTarget mt) { + DescribeMountTargetsResponse response = new DescribeMountTargetsResponse(); + response.setMountTargets(List.of(mt)); + when(efs.describeMountTargets(eq(REGION), any())).thenReturn(response); + } + + private StackResource resource(String type, String logicalId) { + StackResource r = new StackResource(); + r.setLogicalId(logicalId); + r.setResourceType(type); + r.setAttributes(new HashMap<>()); + return r; + } + + private AccessPointDescription accessPoint(String id) { + AccessPointDescription ap = new AccessPointDescription(); + ap.setAccessPointId(id); + ap.setAccessPointArn("arn:aws:elasticfilesystem:us-east-1:000000000000:access-point/" + id); + ap.setFileSystemId(FS_ID); + ap.setClientToken("token-1"); + ap.setTags(new ArrayList<>()); + return ap; + } + + @Test + void mountTargetCreateSetsPhysicalIdAndGetAttAttributes() throws Exception { + when(efs.createMountTarget(any(), eq(REGION))).thenReturn(mountTarget(MT_ID, "subnet-1", List.of("sg-1"))); + StackResource r = resource("AWS::EFS::MountTarget", "Mount"); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", "SubnetId": "subnet-1", "SecurityGroups": ["sg-1"]}"""); + + provisioner.provision(r, props, createCtx()); + + assertEquals(MT_ID, r.getPhysicalId()); + assertEquals(MT_ID, r.getAttributes().get("Id")); + assertEquals("10.0.0.10", r.getAttributes().get("IpAddress")); + ArgumentCaptor request = ArgumentCaptor.forClass(CreateMountTargetRequest.class); + verify(efs).createMountTarget(request.capture(), eq(REGION)); + assertEquals(FS_ID, request.getValue().getFileSystemId()); + assertEquals("subnet-1", request.getValue().getSubnetId()); + assertEquals(List.of("sg-1"), request.getValue().getSecurityGroups()); + } + + @Test + void mountTargetUpdateChangesSecurityGroupsInPlace() throws Exception { + MountTarget prior = mountTarget(MT_ID, "subnet-1", List.of("sg-1")); + stubMountTargetLookup(prior); + StackResource r = resource("AWS::EFS::MountTarget", "Mount"); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", "SubnetId": "subnet-1", "SecurityGroups": ["sg-2"]}"""); + + provisioner.provision(r, props, ctx(MT_ID, null)); + + verify(efs, never()).createMountTarget(any(), any()); + ArgumentCaptor request = + ArgumentCaptor.forClass(ModifyMountTargetSecurityGroupsRequest.class); + verify(efs).modifyMountTargetSecurityGroups(eq(REGION), eq(MT_ID), request.capture()); + assertEquals(List.of("sg-2"), request.getValue().getSecurityGroups()); + assertEquals(MT_ID, r.getPhysicalId()); + assertFalse(ReplacementCleanup.hasReplacement(r)); + } + + @Test + void mountTargetSubnetChangeReplacesTheMountTarget() throws Exception { + stubMountTargetLookup(mountTarget(MT_ID, "subnet-1", List.of())); + when(efs.createMountTarget(any(), eq(REGION))).thenReturn(mountTarget("fsmt-new", "subnet-2", List.of())); + StackResource r = resource("AWS::EFS::MountTarget", "Mount"); + r.setPhysicalId(MT_ID); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", "SubnetId": "subnet-2", "SecurityGroups": []}"""); + + provisioner.provision(r, props, ctx(MT_ID, null)); + + assertEquals("fsmt-new", r.getPhysicalId()); + assertEquals(MT_ID, provisioner.updateCleanupPhysicalId(r)); + } + + @Test + void mountTargetReplacementRefusedByEfsLeavesTheOldTargetUntouched() throws Exception { + stubMountTargetLookup(mountTarget(MT_ID, "subnet-1", List.of("sg-1"))); + when(efs.createMountTarget(any(), eq(REGION))) + .thenThrow(EfsException.mountTargetConflict("Mount target already exists in this subnet")); + StackResource r = resource("AWS::EFS::MountTarget", "Mount"); + r.setPhysicalId(MT_ID); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", "SubnetId": "subnet-1", "SecurityGroups": ["sg-1"], + "IpAddress": "10.0.0.99"}"""); + + EfsException e = assertThrows(EfsException.class, () -> provisioner.provision(r, props, ctx(MT_ID, null))); + + assertEquals("MountTargetConflict", e.getErrorCode()); + assertEquals(MT_ID, r.getPhysicalId()); + verify(efs, never()).deleteMountTarget(any(), any()); + } + + @Test + void mountTargetWithoutARequiredPropertyIsRejected() throws Exception { + for (String missing : List.of("FileSystemId", "SubnetId", "SecurityGroups")) { + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", "SubnetId": "subnet-1", "SecurityGroups": ["sg-1"]}"""); + props.remove(missing); + + AwsException e = assertThrows(AwsException.class, + () -> provisioner.provision(resource("AWS::EFS::MountTarget", "Mount"), props, createCtx())); + + assertEquals("ValidationError", e.getErrorCode()); + assertEquals(missing + " is required for AWS::EFS::MountTarget.", e.getMessage()); + } + verify(efs, never()).createMountTarget(any(), any()); + } + + @Test + void mountTargetWithoutAnIpAddressDoesNotPublishTheAttribute() throws Exception { + MountTarget created = mountTarget(MT_ID, "subnet-1", List.of("sg-1")); + created.setIpAddress(null); + when(efs.createMountTarget(any(), eq(REGION))).thenReturn(created); + StackResource r = resource("AWS::EFS::MountTarget", "Mount"); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", "SubnetId": "subnet-1", "SecurityGroups": ["sg-1"]}"""); + + provisioner.provision(r, props, createCtx()); + + assertFalse(r.getAttributes().containsKey("IpAddress")); + } + + @Test + void mountTargetUpdateKeepsTheTargetWhenAnAddressWasNeverDeclared() throws Exception { + stubMountTargetLookup(mountTarget(MT_ID, "subnet-1", List.of("sg-1"))); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", "SubnetId": "subnet-1", "SecurityGroups": ["sg-1"]}"""); + + provisioner.provision(resource("AWS::EFS::MountTarget", "Mount"), props, ctx(MT_ID, props)); + + verify(efs, never()).createMountTarget(any(), any()); + } + + @Test + void mountTargetUpdateThatDropsADeclaredAddressReplacesTheTarget() throws Exception { + stubMountTargetLookup(mountTarget(MT_ID, "subnet-1", List.of("sg-1"))); + when(efs.createMountTarget(any(), eq(REGION))).thenReturn(mountTarget("fsmt-new", "subnet-1", List.of("sg-1"))); + ObjectNode before = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", "SubnetId": "subnet-1", "SecurityGroups": ["sg-1"], + "IpAddress": "10.0.0.10", "IpAddressType": "IPV4_ONLY"}"""); + ObjectNode after = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", "SubnetId": "subnet-1", "SecurityGroups": ["sg-1"]}"""); + StackResource r = resource("AWS::EFS::MountTarget", "Mount"); + r.setPhysicalId(MT_ID); + + provisioner.provision(r, after, ctx(MT_ID, before)); + + assertEquals("fsmt-new", r.getPhysicalId()); + assertEquals(MT_ID, provisioner.updateCleanupPhysicalId(r)); + } + + @Test + void mountTargetRollbackRestoresSecurityGroups() throws Exception { + stubMountTargetLookup(mountTarget(MT_ID, "subnet-1", List.of("sg-1"))); + StackResource r = resource("AWS::EFS::MountTarget", "Mount"); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", "SubnetId": "subnet-1", "SecurityGroups": ["sg-2"]}"""); + provisioner.provision(r, props, ctx(MT_ID, null)); + + assertTrue(provisioner.rollbackUpdate(r)); + + ArgumentCaptor request = + ArgumentCaptor.forClass(ModifyMountTargetSecurityGroupsRequest.class); + verify(efs, times(2)).modifyMountTargetSecurityGroups(eq(REGION), eq(MT_ID), request.capture()); + assertEquals(List.of("sg-1"), request.getAllValues().get(1).getSecurityGroups()); + } + + @Test + void mountTargetDeleteToleratesAlreadyGoneButNotOtherFailures() { + doThrow(EfsException.mountTargetNotFound(MT_ID)).when(efs).deleteMountTarget(REGION, MT_ID); + provisioner.delete("AWS::EFS::MountTarget", MT_ID, REGION); + + doThrow(EfsException.badRequest("boom")).when(efs).deleteMountTarget(REGION, MT_ID); + assertThrows(AwsException.class, () -> provisioner.delete("AWS::EFS::MountTarget", MT_ID, REGION)); + } + + @Test + void accessPointCreateMapsPosixUserRootDirectoryAndTags() throws Exception { + when(efs.createAccessPoint(eq(REGION), any())).thenReturn(accessPoint(AP_ID)); + StackResource r = resource("AWS::EFS::AccessPoint", "Ap"); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", + "PosixUser": {"Uid": "1000", "Gid": "1001", "SecondaryGids": ["5", "6"]}, + "RootDirectory": {"Path": "/data", + "CreationInfo": {"OwnerUid": "1000", "OwnerGid": "1001", "Permissions": "0755"}}, + "AccessPointTags": [{"Key": "Name", "Value": "data"}]}"""); + + provisioner.provision(r, props, createCtx()); + + assertEquals(AP_ID, r.getPhysicalId()); + assertEquals(AP_ID, r.getAttributes().get("AccessPointId")); + assertEquals("arn:aws:elasticfilesystem:us-east-1:000000000000:access-point/" + AP_ID, + r.getAttributes().get("Arn")); + ArgumentCaptor request = ArgumentCaptor.forClass(CreateAccessPointRequest.class); + verify(efs).createAccessPoint(eq(REGION), request.capture()); + CreateAccessPointRequest sent = request.getValue(); + assertEquals(FS_ID, sent.getFileSystemId()); + assertEquals(1000L, sent.getPosixUser().getUid()); + assertEquals(1001L, sent.getPosixUser().getGid()); + assertEquals(List.of(5L, 6L), sent.getPosixUser().getSecondaryGids()); + assertEquals("/data", sent.getRootDirectory().getPath()); + assertEquals("0755", sent.getRootDirectory().getCreationInfo().getPermissions()); + assertEquals(1000L, sent.getRootDirectory().getCreationInfo().getOwnerUid()); + assertEquals("Name", sent.getTags().get(0).getKey()); + assertTrue(sent.getClientToken().startsWith("my-stack-Ap-")); + } + + @Test + void accessPointUpdateOfTagsOnlyKeepsTheAccessPoint() throws Exception { + AccessPointDescription prior = accessPoint(AP_ID); + when(efs.describeAccessPoints(REGION, null, AP_ID)).thenReturn(List.of(prior)); + StackResource r = resource("AWS::EFS::AccessPoint", "Ap"); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", + "AccessPointTags": [{"Key": "team", "Value": "core"}]}"""); + + provisioner.provision(r, props, ctx(AP_ID, null)); + + verify(efs, never()).createAccessPoint(any(), any()); + verify(efs).tagResource(eq(REGION), any()); + assertEquals(AP_ID, r.getPhysicalId()); + assertFalse(ReplacementCleanup.hasReplacement(r)); + } + + @Test + void accessPointUpdateRemovesATagAddedOutsideTheStack() throws Exception { + AccessPointDescription prior = accessPoint(AP_ID); + Tag outside = new Tag(); + outside.setKey("added-by-hand"); + outside.setValue("v"); + prior.getTags().add(outside); + when(efs.describeAccessPoints(REGION, null, AP_ID)).thenReturn(List.of(prior)); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0"}"""); + + provisioner.provision(resource("AWS::EFS::AccessPoint", "Ap"), props, ctx(AP_ID, null)); + + verify(efs).untagResource(REGION, AP_ID, List.of("added-by-hand")); + } + + @Test + void accessPointWithoutAFileSystemIdIsRejected() throws Exception { + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"PosixUser": {"Uid": "1", "Gid": "1"}}"""); + + AwsException e = assertThrows(AwsException.class, + () -> provisioner.provision(resource("AWS::EFS::AccessPoint", "Ap"), props, createCtx())); + + assertEquals("ValidationError", e.getErrorCode()); + assertEquals("FileSystemId is required for AWS::EFS::AccessPoint.", e.getMessage()); + verify(efs, never()).createAccessPoint(any(), any()); + } + + @Test + void accessPointUpdateThatDropsADeclaredClientTokenReplacesTheAccessPoint() throws Exception { + when(efs.describeAccessPoints(REGION, null, AP_ID)).thenReturn(List.of(accessPoint(AP_ID))); + when(efs.createAccessPoint(eq(REGION), any())).thenReturn(accessPoint("fsap-new")); + ObjectNode before = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", "ClientToken": "token-1"}"""); + ObjectNode after = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0"}"""); + StackResource r = resource("AWS::EFS::AccessPoint", "Ap"); + r.setPhysicalId(AP_ID); + + provisioner.provision(r, after, ctx(AP_ID, before)); + + assertEquals("fsap-new", r.getPhysicalId()); + assertEquals(AP_ID, provisioner.updateCleanupPhysicalId(r)); + } + + @Test + void accessPointUpdateKeepsTheAccessPointWhenAClientTokenWasNeverDeclared() throws Exception { + when(efs.describeAccessPoints(REGION, null, AP_ID)).thenReturn(List.of(accessPoint(AP_ID))); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0"}"""); + + provisioner.provision(resource("AWS::EFS::AccessPoint", "Ap"), props, ctx(AP_ID, props)); + + verify(efs, never()).createAccessPoint(any(), any()); + } + + @Test + void accessPointRollbackOfAnAccessPointThatIsGoneReportsNotFound() throws Exception { + when(efs.describeAccessPoints(REGION, null, AP_ID)).thenReturn(List.of(accessPoint(AP_ID))); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", "AccessPointTags": [{"Key": "a", "Value": "b"}]}"""); + StackResource r = resource("AWS::EFS::AccessPoint", "Ap"); + provisioner.provision(r, props, ctx(AP_ID, null)); + when(efs.describeAccessPoints(REGION, null, AP_ID)).thenReturn(List.of()); + + AwsException e = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)); + + assertEquals("AccessPointNotFound", e.getErrorCode()); + } + + @Test + void accessPointReplacementThatKeepsItsClientTokenLeavesTheOldAccessPointUntouched() throws Exception { + when(efs.describeAccessPoints(REGION, null, AP_ID)).thenReturn(List.of(accessPoint(AP_ID))); + when(efs.createAccessPoint(eq(REGION), any())) + .thenThrow(EfsException.accessPointAlreadyExists("token-1", AP_ID)); + StackResource r = resource("AWS::EFS::AccessPoint", "Ap"); + r.setPhysicalId(AP_ID); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", "ClientToken": "token-1", + "RootDirectory": {"Path": "/other"}}"""); + + EfsException e = assertThrows(EfsException.class, () -> provisioner.provision(r, props, ctx(AP_ID, null))); + + assertEquals("AccessPointAlreadyExists", e.getErrorCode()); + assertEquals(AP_ID, r.getPhysicalId()); + verify(efs, never()).deleteAccessPoint(any(), any()); + } + + @Test + void accessPointPosixUserChangeReplacesTheAccessPoint() throws Exception { + AccessPointDescription prior = accessPoint(AP_ID); + when(efs.describeAccessPoints(REGION, null, AP_ID)).thenReturn(List.of(prior)); + when(efs.createAccessPoint(eq(REGION), any())).thenReturn(accessPoint("fsap-new")); + StackResource r = resource("AWS::EFS::AccessPoint", "Ap"); + r.setPhysicalId(AP_ID); + ObjectNode props = (ObjectNode) mapper.readTree(""" + {"FileSystemId": "fs-0123456789abcdef0", "PosixUser": {"Uid": "1", "Gid": "1"}}"""); + + provisioner.provision(r, props, ctx(AP_ID, null)); + + assertEquals("fsap-new", r.getPhysicalId()); + assertEquals(AP_ID, provisioner.updateCleanupPhysicalId(r)); + } + + @Test + void accessPointDeleteToleratesAlreadyGone() { + doThrow(EfsException.accessPointNotFound(AP_ID)).when(efs).deleteAccessPoint(REGION, AP_ID); + + provisioner.delete("AWS::EFS::AccessPoint", AP_ID, REGION); + } + + @Test + void servesTheThreeEfsTypes() { + assertEquals(Set.of("AWS::EFS::FileSystem", "AWS::EFS::MountTarget", "AWS::EFS::AccessPoint"), + provisioner.resourceTypes()); + } +} diff --git a/src/test/java/io/floci/aws/testing/CfnRequests.java b/src/test/java/io/floci/aws/testing/CfnRequests.java index c4144b20a6..3f7fb00582 100644 --- a/src/test/java/io/floci/aws/testing/CfnRequests.java +++ b/src/test/java/io/floci/aws/testing/CfnRequests.java @@ -1,6 +1,7 @@ package io.floci.aws.testing; import io.floci.aws.core.common.XmlParser; +import io.restassured.path.xml.XmlPath; import io.restassured.specification.RequestSpecification; import java.util.Map; @@ -47,6 +48,20 @@ public final class CfnRequests { .extract().xmlPath().getString("**.find { it.name() == 'PhysicalResourceId' }"); } + /** Returns the parsed DescribeStacks response for {@code stackName}. */ + public static XmlPath describe(String stackName, String authorization) { + return cfn("DescribeStacks", stackName) + .header("Authorization", authorization) + .when().post("/") + .then().statusCode(200) + .extract().xmlPath(); + } + + /** Returns the value of the stack output {@code key} in a {@link #describe} response. */ + public static String output(XmlPath stack, String key) { + return stack.getString("**.findAll { it.OutputKey == '" + key + "' }.OutputValue"); + } + /** Returns the stack-level tags reported by DescribeStacks. */ public static Map tags(String stackName) { String xml = cfn("DescribeStacks", stackName).when().post("/") diff --git a/src/test/resources/cloudformation/schema-surface.tsv b/src/test/resources/cloudformation/schema-surface.tsv index 17a13db03b..19282d4b8c 100644 --- a/src/test/resources/cloudformation/schema-surface.tsv +++ b/src/test/resources/cloudformation/schema-surface.tsv @@ -101,6 +101,9 @@ AWS::ECS::Cluster Arn CapacityProviders,ClusterName,ClusterSettings,Configuratio AWS::ECS::ClusterCapacityProviderAssociations CapacityProviders,Cluster,DefaultCapacityProviderStrategy AWS::ECS::Service Name,ServiceArn AvailabilityZoneRebalancing,CapacityProviderStrategy,Cluster,DeploymentConfiguration,DeploymentController,DesiredCount,EnableECSManagedTags,EnableExecuteCommand,ForceNewDeployment,GatewayConnectors,HealthCheckGracePeriodSeconds,LaunchType,LoadBalancers,Monitoring,NetworkConfiguration,PlacementConstraints,PlacementStrategies,PlatformVersion,PropagateTags,Role,SchedulingStrategy,ServiceConnectConfiguration,ServiceName,ServiceRegistries,Tags,TaskDefinition,VolumeConfigurations,VpcLatticeConfigurations AWS::ECS::TaskDefinition TaskDefinitionArn ContainerDefinitions,Cpu,EnableFaultInjection,EphemeralStorage,ExecutionRoleArn,Family,IpcMode,Memory,NetworkMode,PidMode,PlacementConstraints,ProxyConfiguration,RequiresCompatibilities,RuntimePlatform,Tags,TaskRoleArn,Volumes +AWS::EFS::AccessPoint AccessPointId,Arn AccessPointTags,ClientToken,FileSystemId,PosixUser,RootDirectory +AWS::EFS::FileSystem Arn,FileSystemId AvailabilityZoneName,BackupPolicy,BypassPolicyLockoutSafetyCheck,Encrypted,FileSystemPolicy,FileSystemProtection,FileSystemTags,KmsKeyId,LifecyclePolicies,PerformanceMode,ProvisionedThroughputInMibps,ReplicationConfiguration,ThroughputMode +AWS::EFS::MountTarget Id FileSystemId,IpAddress,IpAddressType,Ipv6Address,SecurityGroups,SubnetId AWS::EKS::Cluster Arn,CertificateAuthorityData,ClusterSecurityGroupId,EncryptionConfigKeyArn,Endpoint,Id,OpenIdConnectIssuerUrl AccessConfig,ActiveCertificateAuthorityId,BootstrapSelfManagedAddons,CertificateAuthority,ComputeConfig,ControlPlaneScalingConfig,DeletionProtection,EncryptionConfig,Force,KubeApiServerConfig,KubeControllerManagerConfig,KubeSchedulerConfig,KubernetesNetworkConfig,Logging,Name,OutpostConfig,RemoteNetworkConfig,ResourcesVpcConfig,RoleArn,RollbackConfig,StorageConfig,Tags,UpgradePolicy,Version,ZonalShiftConfig AWS::EKS::Nodegroup Arn,Id AmiType,CapacityType,ClusterName,DiskSize,ForceUpdateEnabled,InstanceTypes,Labels,LaunchTemplate,NodeRepairConfig,NodeRole,NodegroupName,ReleaseVersion,RemoteAccess,ScalingConfig,Subnets,Tags,Taints,UpdateConfig,Version,WarmPoolConfig AWS::ElastiCache::CacheCluster ConfigurationEndpoint,RedisEndpoint AZMode,AutoMinorVersionUpgrade,CacheNodeType,CacheParameterGroupName,CacheSubnetGroupName,ClusterName,Engine,EngineVersion,IpDiscovery,LogDeliveryConfigurations,NetworkType,NotificationTopicArn,NumCacheNodes,Port,PreferredAvailabilityZone,PreferredAvailabilityZones,PreferredMaintenanceWindow,SnapshotArns,SnapshotName,SnapshotRetentionLimit,SnapshotWindow,Tags,TransitEncryptionEnabled,VpcSecurityGroupIds diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 2de5c6cc80..2de18f78e0 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -102,6 +102,9 @@ AWS::ECS::Cluster EcsCfnProvisioner AWS::ECS::ClusterCapacityProviderAssociations EcsCapacityCfnProvisioner AWS::ECS::Service EcsCfnProvisioner AWS::ECS::TaskDefinition EcsCfnProvisioner +AWS::EFS::AccessPoint EfsCfnProvisioner +AWS::EFS::FileSystem EfsCfnProvisioner +AWS::EFS::MountTarget EfsCfnProvisioner AWS::EKS::Cluster EksCfnProvisioner AWS::EKS::Nodegroup EksCfnProvisioner AWS::ElastiCache::CacheCluster ElastiCacheCfnProvisioner diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index 495989b7ed..852366e119 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -289,6 +289,8 @@ AWS::ECS::TaskDefinition PlacementConstraints accepted and ignored AWS::ECS::TaskDefinition ProxyConfiguration accepted and ignored AWS::ECS::TaskDefinition Tags accepted and ignored AWS::ECS::TaskDefinition Volumes accepted and ignored +AWS::EFS::FileSystem BypassPolicyLockoutSafetyCheck Floci's EFS service applies a file system policy without a lockout check, so there is nothing to bypass +AWS::EFS::FileSystem ReplicationConfiguration not modeled: Floci has no EFS replication, so the destination file system is not created AWS::EKS::Cluster AccessConfig accepted and ignored AWS::EKS::Cluster ActiveCertificateAuthorityId accepted and ignored AWS::EKS::Cluster BootstrapSelfManagedAddons accepted and ignored diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index f3eb5b14e5..b4e247fd11 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -25,6 +25,7 @@ order: - AWS::SecretsManager - AWS::ECR - AWS::ECS + - AWS::EFS - AWS::EKS - AWS::RDS - AWS::DSQL @@ -92,6 +93,7 @@ type_order: AWS::KMS: [Key, Alias] AWS::SecretsManager: [Secret, SecretTargetAttachment] AWS::ECS: [Cluster, TaskDefinition, Service] + AWS::EFS: [FileSystem, MountTarget, AccessPoint] AWS::EKS: [Cluster, Nodegroup] AWS::RDS: [DBInstance, DBCluster, DBSubnetGroup, DBParameterGroup, DBClusterParameterGroup] @@ -148,6 +150,7 @@ service_labels: AWS::EC2: EC2 AWS::ECR: ECR AWS::ECS: ECS + AWS::EFS: EFS AWS::EKS: EKS AWS::ElasticLoadBalancingV2: Elastic Load Balancing v2 AWS::Events: EventBridge @@ -193,6 +196,9 @@ notes: AWS::Lambda::EventInvokeConfig: also what a SAM function's `EventInvokeConfig` expands into AWS::Lambda::WebFunction: control plane only; the endpoint domain does not serve requests yet AWS::Lambda::WebFunctionRevision: every property is createOnly, so a change mints a new revision + AWS::EFS::FileSystem: 'metadata only, there is no NFS data plane' + AWS::EFS::MountTarget: '`SecurityGroups` update in place, every other property replaces' + AWS::EFS::AccessPoint: '`AccessPointTags` update in place, every other property replaces' AWS::EC2::VPC: '`Tags` update in place, keeping tags added outside the stack; deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS' AWS::EC2::SecurityGroup: 'inline `SecurityGroupIngress`/`SecurityGroupEgress` supported; `Tags` update in place, keeping tags added outside the stack; a failed stack update puts the rules and tags of a group it changed in place back' AWS::EC2::Instance: '`Tags` update in place, keeping tags added outside the stack'