Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(cloudformation): add AWS::EFS::FileSystem, MountTarget and AccessPoint (merge after #1949) (#1956)

Fábio André Ramos Rodrigues17e92a43aef0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0faffa80..51f5660c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,11 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+
+- **CloudFormation — stack updates replace resources** — a change to a property the change set reports as `RequiresRecreation: Always` now creates a new resource under a new generated name, points its dependents at it and deletes the old one after the update succeeds (a rollback deletes the new one instead). With an explicit, unchanged name the update fails with the AWS message naming the physical id; this now also covers `AWS::Lambda::Function`. A named SQS queue or SNS topic fails with AWS's already-exists error instead and keeps its messages or subscriptions.
+- **CloudFormation — `AWS::EFS::FileSystem`, `AWS::EFS::MountTarget` and `AWS::EFS::AccessPoint`** — a template with an EFS resource failed validation with `Unrecognized resource types`. The three types now create, update and delete through the EFS store, so CDK `efs.FileSystem` stacks deploy. `Ref` and `Fn::GetAtt` follow the CloudFormation reference; `FileSystemPolicy`, `LifecyclePolicies`, `BackupPolicy`, `ThroughputMode`, `ProvisionedThroughputInMibps`, `FileSystemTags`, mount target `SecurityGroups` and `AccessPointTags` update in place, and the create-only properties replace the resource. `FileSystemProtection`, `ReplicationConfiguration` and `BypassPolicyLockoutSafetyCheck` are supported too.
+- **EFS — policy, protection and replication operations; stricter mount targets** — added `PutFileSystemPolicy` (rejects malformed policies and an unconditional Deny of `PutFileSystemPolicy` with `InvalidPolicyException` unless `BypassPolicyLockoutSafetyCheck` is set; fills in `Id`, `Sid` and `Resource` as the API reference examples show), `DescribeFileSystemPolicy` (`PolicyNotFound` when none is set), `DeleteFileSystemPolicy`, `UpdateFileSystemProtection`, and `CreateReplicationConfiguration` / `DescribeReplicationConfigurations` / `DeleteReplicationConfiguration` (the destination file system is created, or an existing one with protection `DISABLED` used, and is `REPLICATING` until the configuration is deleted). File systems report `FileSystemProtection` (default `ENABLED`) and `AvailabilityZoneName`, and a file system in a replication configuration cannot be deleted. `CreateMountTarget` now checks the subnet (`SubnetNotFound`), security groups in the subnet's VPC (`SecurityGroupNotFound`, default group when none given), one mount target per zone and VPC (`MountTargetConflict`), One Zone file systems (`AvailabilityZonesMismatch`), and takes `IpAddress` from the subnet range (`IpAddressInUse`, `NoFreeAddressesInSubnet`); `IpAddressType` other than `IPV4_ONLY` needs a subnet with an IPv6 CIDR block, which MiniStack's EC2 subnets do not have yet. `DeleteFileSystem` with mount targets now answers 409, as the API reference says, and a deleted file system no longer leaves its lifecycle and backup settings behind.
### Fixed
- **STS — role trust denies and conditions are enforced** — with `AUTH=true`, `AssumeRole` now rejects matching explicit denies, including `NotAction` exclusions, and evaluates `sts:ExternalId` and `sts:RoleSessionName` conditions before issuing credentials. A denied call registers no session. Local JSON requests use the supplied role ARN for authorization and receive JSON trust-denial errors; Query requests retain XML responses. With `AUTH=false`, trust denies and conditions remain permissive.
diff --git a/README.md b/README.md
index db1125f1..e8fd6af6 100644
--- a/README.md
+++ b/README.md
@@ -557,6 +557,9 @@ subnet = ec2.create_subnet(
| `AWS::ECS::Cluster` | Cluster name | Arn, ClusterName |
| `AWS::ECS::TaskDefinition` | Task def ARN | TaskDefinitionArn |
| `AWS::ECS::Service` | Service ARN | ServiceArn, Name |
+| `AWS::EFS::FileSystem` | File system ID | Arn, FileSystemId |
+| `AWS::EFS::MountTarget` | Mount target ID | IpAddress, Id |
+| `AWS::EFS::AccessPoint` | Access point ID | AccessPointId, Arn |
| `AWS::ElasticLoadBalancingV2::LoadBalancer` | LB ARN | Arn, DNSName, LoadBalancerFullName, CanonicalHostedZoneID, SecurityGroups |
| `AWS::ElasticLoadBalancingV2::Listener` | Listener ARN | ListenerArn, Arn |
| `AWS::Lambda::LayerVersion` | Layer version ARN | LayerVersionArn, Arn |
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 77ee11ea..6f2a7a61 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -36,6 +36,7 @@ import ministack.services.dynamodb as _dynamodb
import ministack.services.ec2 as _ec2
import ministack.services.ecr as _ecr
import ministack.services.ecs as _ecs
+import ministack.services.efs as _efs
import ministack.services.elasticache as _ec
import ministack.services.eventbridge as _eb
import ministack.services.firehose as _firehose
@@ -663,6 +664,10 @@ def _requires_replacement_pipes(old_props, new_props):
# custom-named resource (you must rename it first), so MiniStack must fail the
# update instead of silently executing the replacement and destroying data
# (issue #1433).
+# A replacement is a change to a property of the type's _REPLACING_PROPERTIES
+# row, or one ``requires_replacement`` adds. A type with an ``exists`` message
+# is not refused up front: AWS runs the create, which fails with that message
+# because the predecessor still holds the name.
# An ``exists`` entry is not refused up front: the replacement's create fails on the name.
_CUSTOM_NAME_REPLACEMENT = {
"AWS::DynamoDB::Table": {
@@ -916,6 +921,14 @@ def _delete_predecessor(delete_fn, *args, **kwargs):
retaining set): the engine then records the DELETE_SKIPPED event and the
predecessor stays, as on AWS. Every update handler that creates the
replacement itself removes the old resource through this, so the policy
+ cannot be forgotten at one site, with five exceptions. Four have a
+ deterministic generated name (the DynamoDB table, the IoT thing type and
+ the ElastiCache cache cluster and replication group): the replacement
+ takes the name back, so there is nothing left to retain. The fifth is the
+ Lambda permission's degenerate ``Id`` branch,
+ which removes and re-puts one statement under a Sid that cannot change:
+ the physical id is kept, nothing is replaced, and the policy does not
+ apply.
cannot be forgotten at one site.
"""
if _RETAIN_REPLACED.get():
@@ -1052,12 +1065,14 @@ def _reconcile_tag_map(store: dict, old_props: dict, new_props: dict,
def _reconcile_tag_list(store: list, old_props: dict, new_props: dict,
- key: str = "Key", value: str = "Value") -> None:
+ key: str = "Key", value: str = "Value",
+ prop: str = "Tags") -> None:
"""The list-store twin of ``_reconcile_tag_map``: entries the template
dropped are removed, the new ones set, entries from elsewhere kept. The
- list is changed in place; ``key``/``value`` name the entry fields."""
- old_tags = _tag_map(old_props.get("Tags"))
- new_tags = _tag_map(new_props.get("Tags"))
+ list is changed in place; ``key``/``value`` name the entry fields and
+ ``prop`` the template property that carries the tags."""
+ old_tags = _tag_map(old_props.get(prop))
+ new_tags = _tag_map(new_props.get(prop))
if old_tags == new_tags:
return
store[:] = [
@@ -1104,6 +1119,8 @@ _STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {
"AWS::ECR::Repository": ("Tags", "list"),
"AWS::ECS::Cluster": ("Tags", "list"),
"AWS::ECS::Service": ("Tags", "list"),
+ "AWS::EFS::AccessPoint": ("AccessPointTags", "list"),
+ "AWS::EFS::FileSystem": ("FileSystemTags", "list"),
"AWS::EKS::Cluster": ("Tags", "list"),
"AWS::EKS::Nodegroup": ("Tags", "map"),
"AWS::ElasticLoadBalancingV2::Listener": ("Tags", "list"),
@@ -2196,6 +2213,10 @@ def _lambda_update(physical_id, old_props, new_props, stack_name, logical_id=Non
published versions, aliases, the resource policy, tags, event invoke
configs. Going through the Lambda module's own update paths keeps them.
+ FunctionName, PackageType and TenancyConfig changes are replaced in
+ ``_update_resource`` before this runs. A DurableConfig change may require
+ replacement on AWS; under the same physical name the closest local
+ equivalent is the full re-provision the create fallback always did.
FunctionName, PackageType and TenancyConfig are replaced in ``_update_resource``;
a DurableConfig change re-provisions under the same name.
"""
@@ -2697,6 +2718,10 @@ def _iam_ip_roles(props):
def _iam_ip_create(logical_id, props, stack_name):
name = props.get("InstanceProfileName") or _physical_name(stack_name, logical_id, max_len=128)
path = props.get("Path", "/")
+ # A generated name belongs to this stack resource, so a profile left under
+ # it is taken over; a custom name goes through CreateInstanceProfile as it
+ # is, and its EntityAlreadyExists keeps one stack from writing over a
+ # profile another stack or the API owns.
# A generated name is this stack's to take over; a custom one meets EntityAlreadyExists.
if not props.get("InstanceProfileName"):
_iam._instance_profiles.pop(name, None)
@@ -9290,6 +9315,260 @@ def _sd_instance_delete(physical_id, props):
}), "AWS::ServiceDiscovery::Instance deregister", missing_ok=True)
+# ---------------------------------------------------------------------------
+# EFS (AWS::EFS::*)
+#
+# Every handler goes through efs.py's own functions, so a stack-created file
+# system, mount target or access point is the record the EFS API writes. Ref,
+# Fn::GetAtt and the replacement properties follow the CloudFormation Template
+# Reference pages for the three types. A replacement property is listed in
+# _REPLACING_PROPERTIES and replaced by the engine before these update handlers
+# run, so the handlers only change what updates in place.
+# ---------------------------------------------------------------------------
+
+def _efs_result(response, what, missing_ok=False):
+ """The parsed body of an efs call, or ValueError naming ``what``. With
+ ``missing_ok`` a 404 (resource already gone) returns None."""
+ status, _, body = response
+ if status == 404 and missing_ok:
+ return None
+ if status >= 400:
+ raise ValueError(f"{what} failed: {body!r}")
+ return json.loads(body) if body else {}
+
+
+def _efs_file_system_id(value):
+ """A file system id from an id or a ``...:file-system/fs-...`` ARN."""
+ return str(value or "").rsplit("/", 1)[-1]
+
+
+def _efs_policy_json(policy):
+ return policy if isinstance(policy, str) else json.dumps(policy)
+
+
+def _efs_refresh_name(record):
+ """``Name`` follows the ``Name`` tag, as at create."""
+ record["Name"] = next(
+ (t["Value"] for t in record.get("Tags", []) if t.get("Key") == "Name"), "")
+
+
+def _efs_file_system_attrs(fs):
+ return {"Arn": fs["FileSystemArn"], "FileSystemId": fs["FileSystemId"]}
+
+
+def _efs_put_backup_policy(fs_id, policy):
+ _efs_result(_efs._put_backup_policy(fs_id, {"BackupPolicy": policy}),
+ "AWS::EFS::FileSystem BackupPolicy")
+
+
+def _efs_put_lifecycle_policies(fs_id, policies):
+ _efs_result(_efs._put_lifecycle_configuration(fs_id, {"LifecyclePolicies": policies}),
+ "AWS::EFS::FileSystem LifecyclePolicies")
+
+
+def _efs_put_file_system_policy(fs_id, props):
+ body = {"Policy": _efs_policy_json(props["FileSystemPolicy"])}
+ if "BypassPolicyLockoutSafetyCheck" in props:
+ body["BypassPolicyLockoutSafetyCheck"] = _cfn_bool(props["BypassPolicyLockoutSafetyCheck"])
+ _efs_result(_efs._put_file_system_policy(fs_id, body), "AWS::EFS::FileSystem FileSystemPolicy")
+
+
+def _efs_put_protection(fs_id, protection):
+ _efs_result(_efs._update_file_system_protection(fs_id, dict(protection or {})),
+ "AWS::EFS::FileSystem FileSystemProtection")
+
+
+def _efs_replication_destinations(configuration):
+ """The Destinations a ReplicationConfiguration property sends to the API:
+ Status and StatusMessage describe the destination, they do not configure it."""
+ return [
+ {k: v for k, v in destination.items() if k not in ("Status", "StatusMessage")}
+ for destination in (configuration or {}).get("Destinations") or []
+ ]
+
+
+def _efs_create_replication(fs_id, configuration):
+ _efs_result(
+ _efs._create_replication_configuration(
+ fs_id, {"Destinations": _efs_replication_destinations(configuration)}),
+ "AWS::EFS::FileSystem ReplicationConfiguration")
+
+
+def _efs_delete_replication(fs_id):
+ _efs_result(_efs._delete_replication_configuration(fs_id, {}),
+ "AWS::EFS::FileSystem ReplicationConfiguration delete", missing_ok=True)
+
+
+def _efs_file_system_create(logical_id, props, stack_name):
+ # No CreationToken: efs.py returns the existing file system for a repeated
+ # token, which would turn a replacement into a no-op.
+ body = {
+ key: props[key]
+ for key in ("PerformanceMode", "ThroughputMode", "KmsKeyId",
+ "ProvisionedThroughputInMibps", "AvailabilityZoneName")
+ if key in props
+ }
+ if "Encrypted" in props:
+ body["Encrypted"] = _cfn_bool(props["Encrypted"])
+ if "FileSystemTags" in props:
+ body["Tags"] = props["FileSystemTags"]
+ fs = _efs_result(_efs._create_file_system(body), "AWS::EFS::FileSystem create")
+ fs_id = fs["FileSystemId"]
+ if props.get("LifecyclePolicies"):
+ _efs_put_lifecycle_policies(fs_id, props["LifecyclePolicies"])
+ if props.get("BackupPolicy"):
+ _efs_put_backup_policy(fs_id, props["BackupPolicy"])
+ if props.get("FileSystemPolicy"):
+ _efs_put_file_system_policy(fs_id, props)
+ if props.get("FileSystemProtection"):
+ _efs_put_protection(fs_id, props["FileSystemProtection"])
+ if props.get("ReplicationConfiguration"):
+ _efs_create_replication(fs_id, props["ReplicationConfiguration"])
+ return fs_id, _efs_file_system_attrs(fs)
+
+
+def _efs_file_system_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """AvailabilityZoneName, Encrypted, KmsKeyId and PerformanceMode replace
+ the file system in the engine. Everything else changes in place."""
+ fs = _efs._file_systems.get(physical_id)
+ if fs is None:
+ return _efs_file_system_create(logical_id or physical_id, new_props, stack_name)
+ throughput = {}
+ for key, default in (("ThroughputMode", "bursting"), ("ProvisionedThroughputInMibps", None)):
+ if new_props.get(key) != old_props.get(key):
+ if key in new_props:
+ throughput[key] = new_props[key]
+ elif default is not None:
+ throughput[key] = default
+ if throughput:
+ _efs_result(_efs._update_file_system(physical_id, throughput),
+ "AWS::EFS::FileSystem update")
+ if new_props.get("LifecyclePolicies") != old_props.get("LifecyclePolicies"):
+ _efs_put_lifecycle_policies(physical_id, new_props.get("LifecyclePolicies") or [])
+ if new_props.get("BackupPolicy") != old_props.get("BackupPolicy"):
+ _efs_put_backup_policy(physical_id, new_props.get("BackupPolicy") or {"Status": "DISABLED"})
+ if new_props.get("FileSystemPolicy") != old_props.get("FileSystemPolicy"):
+ if new_props.get("FileSystemPolicy"):
+ _efs_put_file_system_policy(physical_id, new_props)
+ else:
+ _efs_result(_efs._delete_file_system_policy(physical_id),
+ "AWS::EFS::FileSystem FileSystemPolicy")
+ if new_props.get("FileSystemProtection") != old_props.get("FileSystemProtection"):
+ _efs_put_protection(physical_id, new_props.get("FileSystemProtection")
+ or {"ReplicationOverwriteProtection": "ENABLED"})
+ if new_props.get("ReplicationConfiguration") != old_props.get("ReplicationConfiguration"):
+ _efs_delete_replication(physical_id)
+ if new_props.get("ReplicationConfiguration"):
+ _efs_create_replication(physical_id, new_props["ReplicationConfiguration"])
+ _reconcile_tag_list(fs.setdefault("Tags", []), old_props, new_props, prop="FileSystemTags")
+ _efs_refresh_name(fs)
+ return physical_id, _efs_file_system_attrs(fs)
+
+
+def _efs_file_system_delete(physical_id, props):
+ # A file system in a replication configuration cannot be deleted; the
+ # destination it created stays, as on AWS.
+ _efs_delete_replication(physical_id)
+ _efs_result(_efs._delete_file_system(physical_id),
+ "AWS::EFS::FileSystem delete", missing_ok=True)
+
+
+def _efs_mount_target_attrs(mount_target):
+ # Id is the file system id, as the CloudFormation reference documents.
+ # An IPV6_ONLY mount target has no IPv4 address.
+ attrs = {"Id": mount_target["FileSystemId"]}
+ if "IpAddress" in mount_target:
+ attrs["IpAddress"] = mount_target["IpAddress"]
+ return attrs
+
+
+def _efs_mount_target_create(logical_id, props, stack_name):
+ body = {
+ "FileSystemId": _efs_file_system_id(props.get("FileSystemId")),
+ "SubnetId": props.get("SubnetId", ""),
+ "SecurityGroups": list(props.get("SecurityGroups") or []),
+ }
+ for key in ("IpAddress", "Ipv6Address", "IpAddressType"):
+ if props.get(key):
+ body[key] = props[key]
+ mount_target = _efs_result(_efs._create_mount_target(body), "AWS::EFS::MountTarget create")
+ return mount_target["MountTargetId"], _efs_mount_target_attrs(mount_target)
+
+
+def _efs_mount_target_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """FileSystemId, SubnetId, IpAddress, IpAddressType and Ipv6Address replace
+ the mount target in the engine; SecurityGroups change in place."""
+ mount_target = _efs._mount_targets.get(physical_id)
+ if mount_target is None:
+ return _efs_mount_target_create(logical_id or physical_id, new_props, stack_name)
+ if new_props.get("SecurityGroups") != old_props.get("SecurityGroups"):
+ _efs_result(_efs._modify_mount_target_security_groups(
+ physical_id, {"SecurityGroups": list(new_props.get("SecurityGroups") or [])}),
+ "AWS::EFS::MountTarget SecurityGroups")
+ return physical_id, _efs_mount_target_attrs(mount_target)
+
+
+def _efs_mount_target_delete(physical_id, props):
+ _efs_result(_efs._delete_mount_target(physical_id),
+ "AWS::EFS::MountTarget delete", missing_ok=True)
+
+
+def _efs_posix_user(user):
+ """The API types Uid, Gid and SecondaryGids as numbers; templates write strings."""
+ user = copy.deepcopy(user)
+ for key in ("Uid", "Gid"):
+ if key in user:
+ user[key] = int(user[key])
+ if "SecondaryGids" in user:
+ user["SecondaryGids"] = [int(gid) for gid in user["SecondaryGids"]]
+ return user
+
+
+def _efs_root_directory(root):
+ root = copy.deepcopy(root)
+ info = root.get("CreationInfo")
+ if info:
+ for key in ("OwnerUid", "OwnerGid"):
+ if key in info:
+ info[key] = int(info[key])
+ return root
+
+
+def _efs_access_point_attrs(access_point):
+ return {"AccessPointId": access_point["AccessPointId"], "Arn": access_point["AccessPointArn"]}
+
+
+def _efs_access_point_create(logical_id, props, stack_name):
+ body = {"FileSystemId": _efs_file_system_id(props.get("FileSystemId"))}
+ if props.get("PosixUser"):
+ body["PosixUser"] = _efs_posix_user(props["PosixUser"])
+ if props.get("RootDirectory"):
+ body["RootDirectory"] = _efs_root_directory(props["RootDirectory"])
+ if props.get("ClientToken"):
+ body["ClientToken"] = props["ClientToken"]
+ if "AccessPointTags" in props:
+ body["Tags"] = props["AccessPointTags"]
+ access_point = _efs_result(_efs._create_access_point(body), "AWS::EFS::AccessPoint create")
+ return access_point["AccessPointId"], _efs_access_point_attrs(access_point)
+
+
+def _efs_access_point_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """FileSystemId, ClientToken, PosixUser and RootDirectory replace the access
+ point in the engine; AccessPointTags change in place."""
+ access_point = _efs._access_points.get(physical_id)
+ if access_point is None:
+ return _efs_access_point_create(logical_id or physical_id, new_props, stack_name)
+ _reconcile_tag_list(access_point.setdefault("Tags", []), old_props, new_props,
+ prop="AccessPointTags")
+ _efs_refresh_name(access_point)
+ return physical_id, _efs_access_point_attrs(access_point)
+
+
+def _efs_access_point_delete(physical_id, props):
+ _efs_result(_efs._delete_access_point(physical_id),
+ "AWS::EFS::AccessPoint delete", missing_ok=True)
+
+
# ---------------------------------------------------------------------------
# Route53 HostedZone
# ---------------------------------------------------------------------------
@@ -12796,6 +13075,14 @@ def _location_tracker_delete(physical_id, props):
_location._delete_tracker(physical_id)
+# CloudFormation replacement rules, checked against DescribeType and change
+# sets. A row lists the schema's createOnlyProperties (Always); the conditional
+# table below lists its conditionalCreateOnlyProperties (Conditionally). Any
+# other property of a listed type is in place (Never), as AWS reports it. A
+# stack update replaces the resource when an Always property changes. Service
+# API immutability is different: an update may fail without being reported as
+# a replacement (for example Cognito sign-in attributes). Types without a row
+# keep the conservative Conditionally answer and their handler's behavior.
# Per type, the create-only properties (Always): a change replaces the resource.
_REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
"AWS::DynamoDB::Table": ("TableName", "ImportSourceSpecification"),
@@ -12860,6 +13147,11 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
"AWS::Glue::Crawler": ("Name",),
"AWS::Glue::Job": ("Name",),
"AWS::Glue::Trigger": ("Name", "WorkflowName", "Type"),
+ "AWS::EFS::FileSystem": ("AvailabilityZoneName", "Encrypted", "KmsKeyId", "PerformanceMode"),
+ "AWS::EFS::MountTarget": (
+ "FileSystemId", "IpAddress", "IpAddressType", "Ipv6Address", "SubnetId",
+ ),
+ "AWS::EFS::AccessPoint": ("ClientToken", "FileSystemId", "PosixUser", "RootDirectory"),
}
@@ -13445,6 +13737,24 @@ _RESOURCE_HANDLERS = {
"update": _ecs_service_update,
"delete": _ecs_service_delete,
},
+ "AWS::EFS::FileSystem": {
+ "create": _efs_file_system_create,
+ "update": _efs_file_system_update,
+ "update_with_logical_id": True,
+ "delete": _efs_file_system_delete,
+ },
+ "AWS::EFS::MountTarget": {
+ "create": _efs_mount_target_create,
+ "update": _efs_mount_target_update,
+ "update_with_logical_id": True,
+ "delete": _efs_mount_target_delete,
+ },
+ "AWS::EFS::AccessPoint": {
+ "create": _efs_access_point_create,
+ "update": _efs_access_point_update,
+ "update_with_logical_id": True,
+ "delete": _efs_access_point_delete,
+ },
"AWS::EC2::LaunchTemplate": {
"create": _ec2_launch_template_create,
"update": _ec2_launch_template_update,
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index 2d136a84..2e895865 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -89,6 +89,7 @@ def _runs_on_worker_thread(resource_type: str) -> bool:
def _update_keeping_seed(*args):
+ """Return _update_resource's result and the name seed it left, which a worker thread would lose."""
"""_update_resource's result and the name seed it left."""
return _update_resource(*args), _NAME_SEED.get()
diff --git a/ministack/services/efs.py b/ministack/services/efs.py
index 73c279a3..08a6d82a 100644
--- a/ministack/services/efs.py
+++ b/ministack/services/efs.py
@@ -14,10 +14,16 @@ Supports:
CreateTags (legacy), DeleteTags (legacy), DescribeTags (legacy)
Lifecycle: PutLifecycleConfiguration, DescribeLifecycleConfiguration
Backup Policy: PutBackupPolicy, DescribeBackupPolicy
+ FS Policy: PutFileSystemPolicy, DescribeFileSystemPolicy, DeleteFileSystemPolicy
+ Protection: UpdateFileSystemProtection
+ Replication: CreateReplicationConfiguration, DescribeReplicationConfigurations,
+ DeleteReplicationConfiguration
Account: DescribeAccountPreferences, PutAccountPreferences
"""
import copy
+import fnmatch
+import ipaddress
import json
import logging
import os
@@ -25,6 +31,7 @@ import random
import re
import string
import time
+import uuid
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.responses import (
@@ -32,6 +39,7 @@ from ministack.core.responses import (
AccountScopedDict,
get_account_id,
get_region,
+ request_scope,
)
logger = logging.getLogger("efs")
@@ -45,6 +53,11 @@ REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
_file_systems = AccountRegionScopedDict() # fs_id -> fs record
_mount_targets = AccountRegionScopedDict() # mt_id -> mount target record
_access_points = AccountRegionScopedDict() # ap_id -> access point record
+_replication_configs = AccountRegionScopedDict() # source fs_id -> replication configuration
+
+_PROTECTION_DEFAULT = "ENABLED"
+_IP_ADDRESS_TYPES = ("IPV4_ONLY", "IPV6_ONLY", "DUAL_STACK")
+_POLICY_MAX_LENGTH = 20000
# ---------------------------------------------------------------------------
# ID generators
@@ -99,9 +112,15 @@ def _create_file_system(body):
"Tags": tags,
"OwnerId": get_account_id(),
"Name": next((t["Value"] for t in tags if t["Key"] == "Name"), ""),
+ "FileSystemProtection": {"ReplicationOverwriteProtection": _PROTECTION_DEFAULT},
}
if provisioned_throughput:
record["ProvisionedThroughputInMibps"] = provisioned_throughput
+ if body.get("AvailabilityZoneName"):
+ from ministack.services import ec2
+
+ record["AvailabilityZoneName"] = body["AvailabilityZoneName"]
+ record["AvailabilityZoneId"] = ec2._az_id_for_zone_name(body["AvailabilityZoneName"])
_file_systems[fs_id] = record
return _json(201, _fs_response(record))
@@ -131,9 +150,17 @@ def _delete_file_system(fs_id):
if not fs:
return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")
if fs["NumberOfMountTargets"] > 0:
- return _error(400, "FileSystemInUse",
+ return _error(409, "FileSystemInUse",
f"File system '{fs_id}' has mount targets and cannot be deleted.")
+ if _replication_of(fs_id):
+ # "You cannot delete a file system that is part of an EFS replication
+ # configuration." The documentation names no error code for it.
+ return _error(409, "FileSystemInUse",
+ f"File system '{fs_id}' is part of a replication configuration; "
+ "delete the replication configuration first.")
del _file_systems[fs_id]
+ _lifecycle_configs.pop(fs_id, None)
+ _backup_policies.pop(fs_id, None)
return _json(204, {})
@@ -149,42 +176,309 @@ def _update_file_system(fs_id, body):
def _fs_response(fs):
- r = {k: v for k, v in fs.items()}
- return r
+ response = {k: v for k, v in fs.items() if k != "FileSystemPolicy"}
+ response.setdefault("FileSystemProtection", {"ReplicationOverwriteProtection": _PROTECTION_DEFAULT})
+ return response
+
+
+def _fs_id_from(value):
+ """A file system id from an id or a ``...:file-system/fs-...`` ARN."""
+ return str(value or "").rsplit("/", 1)[-1]
+
+
+def _update_file_system_protection(fs_id, body):
+ fs = _file_systems.get(fs_id)
+ if not fs:
+ return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")
+ value = body.get("ReplicationOverwriteProtection")
+ if value is None:
+ return _json(200, {"ReplicationOverwriteProtection": _fs_response(fs)["FileSystemProtection"][
+ "ReplicationOverwriteProtection"]})
+ if _replication_of(fs_id):
+ return _error(409, "ReplicationAlreadyExists",
+ f"File system '{fs_id}' is already included in a replication configuration.")
+ # REPLICATING marks a destination and is set by replication only; the
+ # documentation does not say what a caller setting it gets back.
+ if value not in ("ENABLED", "DISABLED"):
+ return _error(400, "BadRequest",
+ "ReplicationOverwriteProtection must be ENABLED or DISABLED.")
+ fs["FileSystemProtection"] = {"ReplicationOverwriteProtection": value}
+ return _json(200, {"ReplicationOverwriteProtection": value})
+
+
+# ---------------------------------------------------------------------------
+# Replication
+# ---------------------------------------------------------------------------
+
+def _replication_of(fs_id):
+ """The replication configuration that has the file system as its source or
+ destination, from any region of the account, else None."""
+ account = get_account_id()
+ for (acct, _region, _source), config in _replication_configs.all_items():
+ if acct != account:
+ continue
+ if config["SourceFileSystemId"] == fs_id or any(
+ d["FileSystemId"] == fs_id for d in config["Destinations"]):
+ return config
+ return None
+
+
+def _create_replication_configuration(source_id, body):
+ source_id = _fs_id_from(source_id)
+ source = _file_systems.get(source_id)
+ if not source:
+ return _error(404, "FileSystemNotFound", f"File system '{source_id}' does not exist.")
+ destinations = body.get("Destinations")
+ if not isinstance(destinations, list) or len(destinations) != 1:
+ return _error(400, "BadRequest", "Exactly one destination is supported.")
+ # "This file system cannot already be a source or destination file system in
+ # another replication configuration." The documentation names no error code.
+ if _replication_of(source_id):
+ return _error(400, "BadRequest",
+ f"File system '{source_id}' is already part of a replication configuration.")
+ destination = destinations[0]
+ account = get_account_id()
+ source_region = get_region()
+ destination_region = destination.get("Region") or source_region
+ destination_id = _fs_id_from(destination["FileSystemId"]) if destination.get("FileSystemId") else None
+ with request_scope(account, destination_region):
+ if destination_id:
+ target = _file_systems.get(destination_id)
+ if not target:
+ return _error(404, "FileSystemNotFound",
+ f"File system '{destination_id}' does not exist.")
+ if destination_id == source_id or _replication_of(destination_id):
+ return _error(400, "BadRequest",
+ f"File system '{destination_id}' is already part of a replication configuration.")
+ if _fs_response(target)["FileSystemProtection"]["ReplicationOverwriteProtection"] != "DISABLED":
+ return _error(400, "BadRequest",
+ "The destination file system's replication overwrite protection must be DISABLED.")
+ if source.get("Encrypted") and not target.get("Encrypted"):
+ return _error(409, "ConflictException",
+ "The source file system is encrypted but the destination file system is not.")
+ else:
+ create = {
+ "PerformanceMode": source["PerformanceMode"],
+ "Encrypted": bool(source.get("Encrypted")),
+ }
+ if destination.get("KmsKeyId"):
+ create["KmsKeyId"] = destination["KmsKeyId"]
+ create["Encrypted"] = True
+ if destination.get("AvailabilityZoneName"):
+ create["AvailabilityZoneName"] = destination["AvailabilityZoneName"]
+ created = json.loads(_create_file_system(create)[2])
+ destination_id = created["FileSystemId"]
+ target = _file_systems[destination_id]
+ target["FileSystemProtection"] = {"ReplicationOverwriteProtection": "REPLICATING"}
+ now = _now_iso()
+ entry = {
+ "Status": "ENABLED",
+ "FileSystemId": destination_id,
+ "Region": destination_region,
+ "LastReplicatedTimestamp": now,
+ "OwnerId": account,
+ }
+ if destination.get("RoleArn"):
+ entry["RoleArn"] = destination["RoleArn"]
+ config = {
+ "SourceFileSystemId": source_id,
+ "SourceFileSystemRegion": source_region,
+ "SourceFileSystemArn": source["FileSystemArn"],
+ "OriginalSourceFileSystemArn": source["FileSystemArn"],
+ "CreationTime": now,
+ "Destinations": [entry],
+ "SourceFileSystemOwnerId": account,
+ }
+ _replication_configs[source_id] = config
+ return _json(200, config)
+
+
+def _describe_replication_configurations(query):
+ fs_id = _fs_id_from(query.get("FileSystemId")) or None
+ if fs_id and fs_id not in _file_systems:
+ return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")
+ account = get_account_id()
+ region = get_region()
+ results = []
+ for (acct, _region, _source), config in _replication_configs.all_items():
+ if acct != account:
+ continue
+ if fs_id:
+ if config["SourceFileSystemId"] != fs_id and not any(
+ d["FileSystemId"] == fs_id for d in config["Destinations"]):
+ continue
+ elif config["SourceFileSystemRegion"] != region and not any(
+ d["Region"] == region for d in config["Destinations"]):
+ continue
+ results.append(config)
+ if fs_id and not results:
+ return _error(404, "ReplicationNotFound",
+ f"File system '{fs_id}' does not have a replication configuration.")
+ results.sort(key=lambda c: c["SourceFileSystemId"])
+ try:
+ offset = int(query.get("NextToken") or 0)
+ limit = int(query.get("MaxResults") or 100)
+ except ValueError:
+ return _error(400, "BadRequest", "NextToken or MaxResults is not valid.")
+ page = results[offset:offset + limit]
+ response = {"Replications": page}
+ if offset + limit < len(results):
+ response["NextToken"] = str(offset + limit)
+ return _json(200, response)
+
+
+def _delete_replication_configuration(source_id, query):
+ source_id = _fs_id_from(source_id)
+ if source_id not in _file_systems:
+ return _error(404, "FileSystemNotFound", f"File system '{source_id}' does not exist.")
+ config = _replication_configs.get(source_id)
+ if not config:
+ return _error(404, "ReplicationNotFound",
+ f"File system '{source_id}' does not have a replication configuration.")
+ mode = query.get("deletionMode") or query.get("DeletionMode") or "ALL_CONFIGURATIONS"
+ if mode not in ("ALL_CONFIGURATIONS", "LOCAL_CONFIGURATION_ONLY"):
+ return _error(400, "BadRequest", "DeletionMode must be ALL_CONFIGURATIONS or LOCAL_CONFIGURATION_ONLY.")
+ if mode == "LOCAL_CONFIGURATION_ONLY" and all(
+ d["Region"] == get_region() for d in config["Destinations"]):
+ return _error(400, "BadRequest",
+ "LOCAL_CONFIGURATION_ONLY is not valid for same-account, same-region replication.")
+ # "After a replication configuration is deleted, the destination file system
+ # becomes writeable and its replication overwrite protection is re-enabled."
+ for destination in config["Destinations"]:
+ with request_scope(get_account_id(), destination["Region"]):
+ target = _file_systems.get(destination["FileSystemId"])
+ if target:
+ target["FileSystemProtection"] = {"ReplicationOverwriteProtection": _PROTECTION_DEFAULT}
+ del _replication_configs[source_id]
+ return _json(204, {})
# ---------------------------------------------------------------------------
# Mount Targets
# ---------------------------------------------------------------------------
+def _pick_address(cidr, used, requested, kind):
+ """The address a mount target takes in the subnet range: the requested one
+ when it lies in the range and is free, else the first free host after the
+ four addresses a subnet reserves at its start. Returns (address, error)."""
+ network = ipaddress.ip_network(cidr, strict=False)
+ if requested:
+ try:
+ address = ipaddress.ip_address(requested)
+ except ValueError:
+ return None, _error(400, "BadRequest", f"'{requested}' is not a valid {kind} address.")
+ if address.version != network.version or address not in network:
+ return None, _error(400, "BadRequest",
+ f"{kind} address '{requested}' is not in the subnet range {cidr}.")
+ if str(address) in used:
+ return None, _error(409, "IpAddressInUse", f"{kind} address '{requested}' is already in use.")
+ return str(address), None
+ for host in network.hosts():
+ if int(host) - int(network.network_address) < 4:
+ continue
+ if str(host) not in used:
+ return str(host), None
+ return None, _error(409, "NoFreeAddressesInSubnet", f"The subnet has no free {kind} addresses.")
+
+
+def _security_groups_in_vpc(security_groups, vpc_id):
+ """The security groups for a mount target: the ones given, which must exist
+ in the subnet's VPC, else the VPC's default group. Returns (ids, error)."""
+ from ministack.services import ec2
+
+ if not security_groups:
+ default = next(
+ (g["GroupId"] for g in ec2._security_groups.values()
+ if g.get("VpcId") == vpc_id and g.get("GroupName") == "default"), None)
+ return ([default] if default else []), None
+ for group_id in security_groups:
+ group = ec2._security_groups.get(group_id)
+ if not group or group.get("VpcId") != vpc_id:
+ return None, _error(400, "SecurityGroupNotFound",
+ f"Security group '{group_id}' does not exist in VPC '{vpc_id}'.")
+ return list(security_groups), None
+
+
def _create_mount_target(body):
- fs_id = body.get("FileSystemId")
+ from ministack.services import ec2
+
+ fs_id = _fs_id_from(body.get("FileSystemId"))
subnet_id = body.get("SubnetId", "")
- ip_address = body.get("IpAddress", f"10.0.{random.randint(0,255)}.{random.randint(1,254)}")
- security_groups = body.get("SecurityGroups", [])
+ address_type = body.get("IpAddressType") or "IPV4_ONLY"
fs = _file_systems.get(fs_id)
if not fs:
return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")
+ if fs.get("LifeCycleState") != "available":
+ return _error(409, "IncorrectFileSystemLifeCycleState",
+ f"File system '{fs_id}' is not in the available state.")
+ if address_type not in _IP_ADDRESS_TYPES:
+ return _error(400, "BadRequest", f"IpAddressType must be one of {', '.join(_IP_ADDRESS_TYPES)}.")
+ wants_v4 = address_type in ("IPV4_ONLY", "DUAL_STACK")
+ wants_v6 = address_type in ("IPV6_ONLY", "DUAL_STACK")
+ if body.get("IpAddress") and not wants_v4:
+ return _error(400, "BadRequest", "IpAddress requires an IpAddressType of IPV4_ONLY or DUAL_STACK.")
+ if body.get("Ipv6Address") and not wants_v6:
+ return _error(400, "BadRequest", "Ipv6Address requires an IpAddressType of IPV6_ONLY or DUAL_STACK.")
+
+ ec2._ensure_defaults_initialized()
+ subnet = ec2._subnets.get(subnet_id)
+ if not subnet:
+ return _error(400, "SubnetNotFound", f"The subnet '{subnet_id}' does not exist.")
+ ipv6_cidr = subnet.get("Ipv6CidrBlock")
+ if wants_v6 and not ipv6_cidr:
+ return _error(400, "BadRequest",
+ f"Subnet '{subnet_id}' has no IPv6 CIDR block; the subnet type must match the IpAddressType.")
+ zone = subnet["AvailabilityZone"]
+ if fs.get("AvailabilityZoneName") and fs["AvailabilityZoneName"] != zone:
+ return _error(400, "AvailabilityZonesMismatch",
+ f"The subnet is in {zone}, but the One Zone file system is in {fs['AvailabilityZoneName']}.")
+ for other in _mount_targets.values():
+ if other["FileSystemId"] != fs_id:
+ continue
+ if other["VpcId"] != subnet["VpcId"]:
+ return _error(409, "MountTargetConflict",
+ "A file system can have mount targets in only one VPC.")
+ if other["AvailabilityZoneName"] == zone:
+ return _error(409, "MountTargetConflict",
+ f"The file system already has a mount target in {zone}.")
+ groups, err = _security_groups_in_vpc(body.get("SecurityGroups") or [], subnet["VpcId"])
+ if err:
+ return err
+
+ in_subnet = [mt for mt in _mount_targets.values() if mt["SubnetId"] == subnet_id]
+ ipv4 = ipv6 = None
+ if wants_v4:
+ ipv4, err = _pick_address(subnet["CidrBlock"], {mt.get("IpAddress") for mt in in_subnet},
+ body.get("IpAddress"), "IPv4")
+ if err:
+ return err
+ if wants_v6:
+ ipv6, err = _pick_address(ipv6_cidr, {mt.get("Ipv6Address") for mt in in_subnet},
+ body.get("Ipv6Address"), "IPv6")
+ if err:
+ return err
mt_id = _mt_id()
arn = f"arn:aws:elasticfilesystem:{get_region()}:{get_account_id()}:file-system/{fs_id}/mount-target/{mt_id}"
- now = _now_iso()
-
record = {
"MountTargetId": mt_id,
"FileSystemId": fs_id,
"SubnetId": subnet_id,
- "AvailabilityZoneId": f"use1-az{random.randint(1,3)}",
- "AvailabilityZoneName": f"{get_region()}a",
- "VpcId": "vpc-00000001",
+ "AvailabilityZoneId": subnet["AvailabilityZoneId"],
+ "AvailabilityZoneName": zone,
+ "VpcId": subnet["VpcId"],
"LifeCycleState": "available",
- "IpAddress": ip_address,
- "NetworkInterfaceId": f"eni-{random.choices(string.hexdigits[:16], k=17)}",
+ "NetworkInterfaceId": "eni-" + "".join(random.choices(string.hexdigits[:16], k=17)),
"OwnerId": get_account_id(),
"MountTargetArn": arn,
- "SecurityGroups": security_groups,
+ "SecurityGroups": groups,
+ "IpAddressType": address_type,
}
+ if ipv4:
+ record["IpAddress"] = ipv4
+ if ipv6:
+ record["Ipv6Address"] = ipv6
_mount_targets[mt_id] = record
fs["NumberOfMountTargets"] = fs.get("NumberOfMountTargets", 0) + 1
@@ -232,12 +526,15 @@ def _modify_mount_target_security_groups(mt_id, body):
mt = _mount_targets.get(mt_id)
if not mt:
return _error(404, "MountTargetNotFound", f"Mount target '{mt_id}' does not exist.")
- mt["SecurityGroups"] = body.get("SecurityGroups", [])
+ groups, err = _security_groups_in_vpc(body.get("SecurityGroups") or [], mt["VpcId"])
+ if err:
+ return err
+ mt["SecurityGroups"] = groups
return _json(204, {})
def _mt_response(mt):
- return {k: v for k, v in mt.items() if k != "SecurityGroups"}
+ return {k: v for k, v in mt.items() if k not in ("SecurityGroups", "IpAddressType")}
# ---------------------------------------------------------------------------
@@ -398,6 +695,7 @@ def _clear_state():
_file_systems.clear()
_mount_targets.clear()
_access_points.clear()
+ _replication_configs.clear()
_lifecycle_configs.clear()
_backup_policies.clear()
@@ -407,6 +705,7 @@ def get_state():
"file_systems": _file_systems,
"mount_targets": _mount_targets,
"access_points": _access_points,
+ "replication_configs": _replication_configs,
"lifecycle_configs": _lifecycle_configs,
"backup_policies": _backup_policies,
})
@@ -423,6 +722,7 @@ def _restore_state(data):
_file_systems.update(data.get("file_systems", {}))
_mount_targets.update(data.get("mount_targets", {}))
_access_points.update(data.get("access_points", {}))
+ _replication_configs.update(data.get("replication_configs", {}))
fs_regions = {
(account_id, fs_id): region
for (account_id, region, fs_id), _fs in _file_systems.all_items()
@@ -490,6 +790,83 @@ def _describe_backup_policy(fs_id):
return _json(200, {"BackupPolicy": _backup_policies.get(fs_id, {"Status": "DISABLED"})})
+def _policy_locks_out_caller(statements):
+ """Whether a statement denies PutFileSystemPolicy to every principal with no
+ condition: the lockout the safety check refuses. Allow statements never
+ lock out a same-account caller, and a conditional Deny cannot be evaluated
+ here, so only the unconditional Deny counts (inference: the documentation
+ describes the check by its purpose, not its rules)."""
+ for statement in statements:
+ if statement.get("Effect") != "Deny" or statement.get("Condition"):
+ continue
+ principal = statement.get("Principal")
+ if isinstance(principal, dict):
+ values = [v for value in principal.values() for v in (value if isinstance(value, list) else [value])]
+ else:
+ values = [principal]
+ if "*" not in values:
+ continue
+ actions = statement.get("Action") or []
+ actions = [actions] if isinstance(actions, str) else actions
+ if any(fnmatch.fnmatchcase("elasticfilesystem:putfilesystempolicy", str(a).lower()) for a in actions):
+ return True
+ return False
+
+
+def _put_file_system_policy(fs_id, body):
+ fs = _file_systems.get(fs_id)
+ if not fs:
+ return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")
+ raw = body.get("Policy")
+ if not isinstance(raw, str) or not 1 <= len(raw) <= _POLICY_MAX_LENGTH:
+ return _error(400, "BadRequest", f"Policy must be between 1 and {_POLICY_MAX_LENGTH} characters.")
+ try:
+ policy = json.loads(raw)
+ except ValueError:
+ return _error(400, "InvalidPolicyException", "The file system policy is not valid JSON.")
+ statements = policy.get("Statement") if isinstance(policy, dict) else None
+ if isinstance(statements, dict):
+ statements = [statements]
+ if not statements or not all(
+ isinstance(s, dict) and s.get("Effect") in ("Allow", "Deny") and ("Action" in s or "NotAction" in s)
+ for s in statements):
+ return _error(400, "InvalidPolicyException",
+ "The file system policy needs a Statement list whose entries have an Effect and an Action.")
+ if not body.get("BypassPolicyLockoutSafetyCheck") and _policy_locks_out_caller(statements):
+ return _error(400, "InvalidPolicyException",
+ "The policy would lock out the caller from PutFileSystemPolicy; "
+ "set BypassPolicyLockoutSafetyCheck to override.")
+ # The documentation's example responses carry an Id, a Sid per statement and
+ # the file system ARN as Resource where the request left them out.
+ policy["Statement"] = statements
+ policy.setdefault("Id", "1")
+ for statement in statements:
+ statement.setdefault("Sid", f"efs-statement-{uuid.uuid4()}")
+ if "Resource" not in statement and "NotResource" not in statement:
+ statement["Resource"] = fs["FileSystemArn"]
+ stored = json.dumps(policy)
+ fs["FileSystemPolicy"] = stored
+ return _json(200, {"FileSystemId": fs_id, "Policy": stored})
+
+
+def _describe_file_system_policy(fs_id):
+ fs = _file_systems.get(fs_id)
+ if not fs:
+ return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")
+ policy = fs.get("FileSystemPolicy")
+ if not policy:
+ return _error(404, "PolicyNotFound", f"File system '{fs_id}' has no file system policy.")
+ return _json(200, {"FileSystemId": fs_id, "Policy": policy})
+
+
+def _delete_file_system_policy(fs_id):
+ fs = _file_systems.get(fs_id)
+ if not fs:
+ return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")
+ fs.pop("FileSystemPolicy", None)
+ return _json(200, {})
+
+
def _describe_account_preferences():
return _json(200, {"ResourceIdPreference": {"ResourceIdType": "LONG_ID", "Resources": ["FILE_SYSTEM", "MOUNT_TARGET"]}})
@@ -593,6 +970,32 @@ async def handle_request(method, path, headers, body_bytes, query_params):
if method == "GET":
return await _a(_describe_backup_policy(fs_id))
+ # Replication and protection
+ if p == "/file-systems/replication-configurations" and method == "GET":
+ return await _a(_describe_replication_configurations(query))
+
+ m = re.fullmatch(r"/file-systems/([^/]+)/replication-configuration", p)
+ if m:
+ if method == "POST":
+ return await _a(_create_replication_configuration(m.group(1), body))
+ if method == "DELETE":
+ return await _a(_delete_replication_configuration(m.group(1), query))
+
+ m = re.fullmatch(r"/file-systems/([^/]+)/protection", p)
+ if m and method == "PUT":
+ return await _a(_update_file_system_protection(_fs_id_from(m.group(1)), body))
+
+ # File System Policy
+ m = re.fullmatch(r"/file-systems/([^/]+)/policy", p)
+ if m:
+ fs_id = m.group(1)
+ if method == "PUT":
+ return await _a(_put_file_system_policy(fs_id, body))
+ if method == "GET":
+ return await _a(_describe_file_system_policy(fs_id))
+ if method == "DELETE":
+ return await _a(_delete_file_system_policy(fs_id))
+
# Account Preferences
if p == "/account-preferences":
if method == "GET":
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 7b11f6f9..10d1ee27 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -6766,6 +6766,404 @@ def test_cfn_servicediscovery_cdk_ecs_shape(cfn, sd):
_wait_stack(cfn, stack_name)
+# ---------------------------------------------------------------------------
+# AWS::EFS::* (#1873). Ref, Fn::GetAtt and replacement properties follow the
+# CloudFormation Template Reference pages for the three types.
+# ---------------------------------------------------------------------------
+
+_efs_physical_ids = _sd_physical_ids
+
+
+def _efs_client_for_region(region):
+ return boto3.client(
+ "efs",
+ endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),
+ aws_access_key_id="test",
+ aws_secret_access_key="test",
+ region_name=region,
+ )
+
+_EFS_POLICY = {
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Allow",
+ "Principal": {"AWS": "*"},
+ "Action": ["elasticfilesystem:ClientMount"],
+ }],
+}
+
+
+def _efs_stack_template(performance_mode="generalPurpose", throughput_mode="bursting",
+ provisioned=None, lifecycle=None, backup="ENABLED", policy=None,
+ fs_tags=None, security_groups=("Sg",), ap_tags=None):
+ """A file system, one mount target per subnet and an access point."""
+ fs_props = {
+ "Encrypted": True,
+ "PerformanceMode": performance_mode,
+ "ThroughputMode": throughput_mode,
+ "LifecyclePolicies": lifecycle if lifecycle is not None else [{"TransitionToIA": "AFTER_30_DAYS"}],
+ "BackupPolicy": {"Status": backup},
+ "FileSystemPolicy": policy or _EFS_POLICY,
+ "FileSystemTags": fs_tags if fs_tags is not None else [
+ {"Key": "Name", "Value": "efs-test"}, {"Key": "team", "Value": "a"}],
+ }
+ if provisioned is not None:
+ fs_props["ProvisionedThroughputInMibps"] = provisioned
+ mount_target = lambda subnet: { # noqa: E731
+ "Type": "AWS::EFS::MountTarget",
+ "Properties": {
+ "FileSystemId": {"Ref": "Fs"},
+ "SubnetId": {"Ref": subnet},
+ "SecurityGroups": [{"Ref": sg} for sg in security_groups],
+ },
+ }
+ return {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.0.0.0/16"}},
+ "Subnet1": {"Type": "AWS::EC2::Subnet", "Properties": {
+ "VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.0.1.0/24", "AvailabilityZone": "us-east-1a"}},
+ "Subnet2": {"Type": "AWS::EC2::Subnet", "Properties": {
+ "VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.0.2.0/24", "AvailabilityZone": "us-east-1b"}},
+ "Sg": {"Type": "AWS::EC2::SecurityGroup", "Properties": {
+ "GroupDescription": "efs", "VpcId": {"Ref": "Vpc"}}},
+ "Sg2": {"Type": "AWS::EC2::SecurityGroup", "Properties": {
+ "GroupDescription": "efs2", "VpcId": {"Ref": "Vpc"}}},
+ "Fs": {"Type": "AWS::EFS::FileSystem", "Properties": fs_props},
+ "Mt1": mount_target("Subnet1"),
+ "Mt2": mount_target("Subnet2"),
+ "Ap": {
+ "Type": "AWS::EFS::AccessPoint",
+ "Properties": {
+ "FileSystemId": {"Ref": "Fs"},
+ "PosixUser": {"Uid": "13234", "Gid": "1322", "SecondaryGids": ["1344", "1452"]},
+ "RootDirectory": {
+ "Path": "/app",
+ "CreationInfo": {"OwnerUid": "7987", "OwnerGid": "708", "Permissions": "0755"},
+ },
+ "AccessPointTags": ap_tags if ap_tags is not None else [
+ {"Key": "Name", "Value": "ap-test"}],
+ },
+ },
+ },
+ }
+
+
+def _efs_error_code(call, **kwargs):
+ with pytest.raises(ClientError) as exc:
+ call(**kwargs)
+ return exc.value.response["Error"]["Code"]
+
+
+def test_cfn_efs_validate_template(cfn):
+ response = cfn.validate_template(TemplateBody=json.dumps(_efs_stack_template()))
+ assert "Parameters" in response
+
+
+def test_cfn_efs_create(cfn, efs):
+ stack_name = f"cfn-efs-{_uuid_mod.uuid4().hex[:8]}"
+ template = _efs_stack_template()
+ template["Outputs"] = {
+ "FsRef": {"Value": {"Ref": "Fs"}},
+ "FsArn": {"Value": {"Fn::GetAtt": ["Fs", "Arn"]}},
+ "FsId": {"Value": {"Fn::GetAtt": ["Fs", "FileSystemId"]}},
+ "MtRef": {"Value": {"Ref": "Mt1"}},
+ "MtIp": {"Value": {"Fn::GetAtt": ["Mt1", "IpAddress"]}},
+ "MtId": {"Value": {"Fn::GetAtt": ["Mt1", "Id"]}},
+ "ApRef": {"Value": {"Ref": "Ap"}},
+ "ApId": {"Value": {"Fn::GetAtt": ["Ap", "AccessPointId"]}},
+ "ApArn": {"Value": {"Fn::GetAtt": ["Ap", "Arn"]}},
+ }
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template),
+ Tags=[{"Key": "env", "Value": "test"}])
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ out = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}
+
+ fs_id = out["FsRef"]
+ assert fs_id.startswith("fs-") and out["FsId"] == fs_id
+ fs = efs.describe_file_systems(FileSystemId=fs_id)["FileSystems"][0]
+ assert fs["FileSystemArn"] == out["FsArn"]
+ assert fs["Encrypted"] is True
+ assert fs["PerformanceMode"] == "generalPurpose"
+ assert fs["Name"] == "efs-test"
+ assert fs["NumberOfMountTargets"] == 2
+ tags = {t["Key"]: t["Value"] for t in efs.list_tags_for_resource(ResourceId=fs_id)["Tags"]}
+ assert tags["team"] == "a" and tags["env"] == "test"
+ assert tags["aws:cloudformation:stack-name"] == stack_name
+ assert efs.describe_lifecycle_configuration(FileSystemId=fs_id)["LifecyclePolicies"] == [
+ {"TransitionToIA": "AFTER_30_DAYS"}]
+ assert efs.describe_backup_policy(FileSystemId=fs_id)["BackupPolicy"]["Status"] == "ENABLED"
+ stored_policy = json.loads(efs.describe_file_system_policy(FileSystemId=fs_id)["Policy"])
+ assert stored_policy["Statement"][0]["Action"] == _EFS_POLICY["Statement"][0]["Action"]
+ assert stored_policy["Statement"][0]["Resource"] == out["FsArn"]
+ assert fs["FileSystemProtection"]["ReplicationOverwriteProtection"] == "ENABLED"
+
+ mt = efs.describe_mount_targets(MountTargetId=out["MtRef"])["MountTargets"][0]
+ assert mt["FileSystemId"] == fs_id
+ assert mt["IpAddress"] == out["MtIp"]
+ assert out["MtId"] == fs_id
+ assert len(efs.describe_mount_targets(FileSystemId=fs_id)["MountTargets"]) == 2
+
+ assert out["ApRef"] == out["ApId"] and out["ApRef"].startswith("fsap-")
+ ap = efs.describe_access_points(AccessPointId=out["ApRef"])["AccessPoints"][0]
+ assert ap["AccessPointArn"] == out["ApArn"]
+ assert ap["PosixUser"] == {"Uid": 13234, "Gid": 1322, "SecondaryGids": [1344, 1452]}
+ assert ap["RootDirectory"]["CreationInfo"] == {
+ "OwnerUid": 7987, "OwnerGid": 708, "Permissions": "0755"}
+ assert ap["Name"] == "ap-test"
+ ap_tags = {t["Key"] for t in efs.list_tags_for_resource(ResourceId=out["ApRef"])["Tags"]}
+ assert {"Name", "aws:cloudformation:stack-name"} <= ap_tags
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
+def test_cfn_efs_update_in_place(cfn, efs):
+ stack_name = f"cfn-efs-upd-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_efs_stack_template()))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ before = _efs_physical_ids(cfn, stack_name)
+
+ new_policy = {**_EFS_POLICY, "Id": "updated"}
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(_efs_stack_template(
+ throughput_mode="provisioned", provisioned=5,
+ lifecycle=[{"TransitionToIA": "AFTER_60_DAYS"}], backup="DISABLED", policy=new_policy,
+ fs_tags=[{"Key": "Name", "Value": "efs-renamed"}, {"Key": "owner", "Value": "b"}],
+ security_groups=("Sg2",), ap_tags=[{"Key": "Name", "Value": "ap-renamed"}],
+ )))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ after = _efs_physical_ids(cfn, stack_name)
+ for logical_id in ("Fs", "Mt1", "Mt2", "Ap"):
+ assert after[logical_id] == before[logical_id]
+
+ fs_id = before["Fs"]
+ fs = efs.describe_file_systems(FileSystemId=fs_id)["FileSystems"][0]
+ assert fs["ThroughputMode"] == "provisioned"
+ assert fs["ProvisionedThroughputInMibps"] == 5
+ assert fs["Name"] == "efs-renamed"
+ tags = {t["Key"]: t["Value"] for t in efs.list_tags_for_resource(ResourceId=fs_id)["Tags"]}
+ assert tags["owner"] == "b" and "team" not in tags
+ assert efs.describe_lifecycle_configuration(FileSystemId=fs_id)["LifecyclePolicies"] == [
+ {"TransitionToIA": "AFTER_60_DAYS"}]
+ assert efs.describe_backup_policy(FileSystemId=fs_id)["BackupPolicy"]["Status"] == "DISABLED"
+ assert json.loads(efs.describe_file_system_policy(FileSystemId=fs_id)["Policy"])["Id"] == "updated"
+
+ sg2 = before["Sg2"]
+ for mt_logical_id in ("Mt1", "Mt2"):
+ groups = efs.describe_mount_target_security_groups(
+ MountTargetId=before[mt_logical_id])["SecurityGroups"]
+ assert groups == [sg2]
+
+ ap = efs.describe_access_points(AccessPointId=before["Ap"])["AccessPoints"][0]
+ assert ap["Name"] == "ap-renamed"
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
+def test_cfn_efs_update_replacement(cfn, efs):
+ stack_name = f"cfn-efs-repl-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_efs_stack_template()))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ before = _efs_physical_ids(cfn, stack_name)
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(
+ _efs_stack_template(performance_mode="maxIO")))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ after = _efs_physical_ids(cfn, stack_name)
+
+ # PerformanceMode replaces the file system; the mount targets and the access
+ # point follow because their FileSystemId changed.
+ for logical_id in ("Fs", "Mt1", "Mt2", "Ap"):
+ assert after[logical_id] != before[logical_id]
+ assert efs.describe_file_systems(FileSystemId=after["Fs"])["FileSystems"][0]["PerformanceMode"] == "maxIO"
+
+ assert _efs_error_code(efs.describe_file_systems, FileSystemId=before["Fs"]) == "FileSystemNotFound"
+ for logical_id in ("Mt1", "Mt2"):
+ assert _efs_error_code(efs.describe_mount_targets, MountTargetId=before[logical_id]) == "MountTargetNotFound"
+ assert efs.describe_access_points(AccessPointId=before["Ap"])["AccessPoints"] == []
+ assert len(efs.describe_mount_targets(FileSystemId=after["Fs"])["MountTargets"]) == 2
+
+ events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
+ assert any(
+ e["LogicalResourceId"] == "Fs" and "creation of a new physical resource" in e.get("ResourceStatusReason", "")
+ for e in events
+ )
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
+def test_cfn_efs_delete_stack(cfn, efs):
+ stack_name = f"cfn-efs-del-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_efs_stack_template()))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ ids = _efs_physical_ids(cfn, stack_name)
+
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
+
+ assert _efs_error_code(efs.describe_file_systems, FileSystemId=ids["Fs"]) == "FileSystemNotFound"
+ for logical_id in ("Mt1", "Mt2"):
+ assert _efs_error_code(efs.describe_mount_targets, MountTargetId=ids[logical_id]) == "MountTargetNotFound"
+ assert efs.describe_access_points(AccessPointId=ids["Ap"])["AccessPoints"] == []
+
+
+def test_cfn_efs_cdk_shape(cfn, efs):
+ """The shape the CDK ``efs.FileSystem`` emits (taken from the construct
+ library, not a synthesized app): a retained, encrypted file system, one
+ mount target per subnet and an access point from ``addAccessPoint``."""
+ stack_name = f"cfn-efs-cdk-{_uuid_mod.uuid4().hex[:8]}"
+ template = _efs_stack_template()
+ template["Resources"]["Fs"].update({"DeletionPolicy": "Retain", "UpdateReplacePolicy": "Retain"})
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ ids = _efs_physical_ids(cfn, stack_name)
+
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
+
+ # The retained file system outlives the stack; its dependents do not.
+ assert efs.describe_file_systems(FileSystemId=ids["Fs"])["FileSystems"][0]["FileSystemId"] == ids["Fs"]
+ for logical_id in ("Mt1", "Mt2"):
+ assert _efs_error_code(efs.describe_mount_targets, MountTargetId=ids[logical_id]) == "MountTargetNotFound"
+ assert efs.describe_access_points(AccessPointId=ids["Ap"])["AccessPoints"] == []
+ efs.delete_file_system(FileSystemId=ids["Fs"])
+
+
+def _efs_single_file_system_template(**properties):
+ return {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {"Fs": {"Type": "AWS::EFS::FileSystem", "Properties": properties}},
+ }
+
+
+def test_cfn_efs_file_system_protection(cfn, efs):
+ stack_name = f"cfn-efs-prot-{_uuid_mod.uuid4().hex[:8]}"
+ protection = lambda value: {"ReplicationOverwriteProtection": value} # noqa: E731
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(
+ _efs_single_file_system_template(FileSystemProtection=protection("DISABLED"))))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ fs_id = _efs_physical_ids(cfn, stack_name)["Fs"]
+
+ def current():
+ return efs.describe_file_systems(FileSystemId=fs_id)["FileSystems"][0][
+ "FileSystemProtection"]["ReplicationOverwriteProtection"]
+
+ assert current() == "DISABLED"
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(
+ _efs_single_file_system_template(FileSystemProtection=protection("ENABLED"))))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert _efs_physical_ids(cfn, stack_name)["Fs"] == fs_id and current() == "ENABLED"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(
+ _efs_single_file_system_template(FileSystemProtection=protection("DISABLED"))))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(
+ _efs_single_file_system_template(ThroughputMode="bursting")))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert current() == "ENABLED" # the dropped property reverts to the default
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
+def test_cfn_efs_replication_configuration(cfn, efs):
+ west = _efs_client_for_region("us-west-2")
+ stack_name = f"cfn-efs-repl-cfg-{_uuid_mod.uuid4().hex[:8]}"
+ template = _efs_single_file_system_template(
+ Encrypted=True,
+ ReplicationConfiguration={"Destinations": [{"Region": "us-west-2"}]},
+ )
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ fs_id = _efs_physical_ids(cfn, stack_name)["Fs"]
+
+ config = efs.describe_replication_configurations(FileSystemId=fs_id)["Replications"][0]
+ destination_id = config["Destinations"][0]["FileSystemId"]
+ assert config["Destinations"][0]["Region"] == "us-west-2"
+ destination = west.describe_file_systems(FileSystemId=destination_id)["FileSystems"][0]
+ assert destination["Encrypted"] is True
+ assert destination["FileSystemProtection"]["ReplicationOverwriteProtection"] == "REPLICATING"
+
+ # Dropping the property ends the replication; the destination stays, writeable again.
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(
+ _efs_single_file_system_template(Encrypted=True)))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert _efs_physical_ids(cfn, stack_name)["Fs"] == fs_id
+ assert _efs_error_code(efs.describe_replication_configurations, FileSystemId=fs_id) == "ReplicationNotFound"
+ destination = west.describe_file_systems(FileSystemId=destination_id)["FileSystems"][0]
+ assert destination["FileSystemProtection"]["ReplicationOverwriteProtection"] == "ENABLED"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ second = efs.describe_replication_configurations(FileSystemId=fs_id)["Replications"][0]
+ second_destination = second["Destinations"][0]["FileSystemId"]
+
+ # Stack delete ends the replication first, which a file system in one cannot do without.
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
+ assert _efs_error_code(efs.describe_file_systems, FileSystemId=fs_id) == "FileSystemNotFound"
+ for leftover in (destination_id, second_destination):
+ west.delete_file_system(FileSystemId=leftover)
+
+
+def test_cfn_efs_policy_lockout_check_and_bypass(cfn, efs):
+ lockout = {
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Deny", "Principal": {"AWS": "*"},
+ "Action": "elasticfilesystem:PutFileSystemPolicy", "Resource": "*",
+ }],
+ }
+ refused = f"cfn-efs-lock-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=refused, TemplateBody=json.dumps(
+ _efs_single_file_system_template(FileSystemPolicy=lockout)), OnFailure="DO_NOTHING")
+ assert _wait_stack(cfn, refused)["StackStatus"] == "CREATE_FAILED"
+ events = cfn.describe_stack_events(StackName=refused)["StackEvents"]
+ assert any("InvalidPolicyException" in e.get("ResourceStatusReason", "") for e in events)
+ cfn.delete_stack(StackName=refused)
+ _wait_stack(cfn, refused)
+
+ allowed = f"cfn-efs-bypass-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=allowed, TemplateBody=json.dumps(
+ _efs_single_file_system_template(FileSystemPolicy=lockout, BypassPolicyLockoutSafetyCheck=True)))
+ assert _wait_stack(cfn, allowed)["StackStatus"] == "CREATE_COMPLETE"
+ fs_id = _efs_physical_ids(cfn, allowed)["Fs"]
+ assert json.loads(efs.describe_file_system_policy(FileSystemId=fs_id)["Policy"])["Statement"][0]["Effect"] == "Deny"
+ cfn.delete_stack(StackName=allowed)
+ _wait_stack(cfn, allowed)
+
+
+def test_cfn_efs_mount_target_ip_properties(cfn, efs):
+ stack_name = f"cfn-efs-ip-{_uuid_mod.uuid4().hex[:8]}"
+ template = _efs_stack_template()
+ template["Resources"]["Mt1"]["Properties"].update({"IpAddress": "10.0.1.50", "IpAddressType": "IPV4_ONLY"})
+ template["Outputs"] = {"MtIp": {"Value": {"Fn::GetAtt": ["Mt1", "IpAddress"]}}}
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ assert {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}["MtIp"] == "10.0.1.50"
+ ids = _efs_physical_ids(cfn, stack_name)
+ mt = efs.describe_mount_targets(MountTargetId=ids["Mt1"])["MountTargets"][0]
+ assert mt["IpAddress"] == "10.0.1.50" and mt["SubnetId"] == ids["Subnet1"] and mt["VpcId"] == ids["Vpc"]
+ # Mt2 takes the first free address of its own subnet.
+ assert efs.describe_mount_targets(MountTargetId=ids["Mt2"])["MountTargets"][0]["IpAddress"] == "10.0.2.4"
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+ # The subnets here have no IPv6 CIDR block, so an IPv6 address type fails the stack.
+ failing = _efs_stack_template()
+ failing["Resources"]["Mt1"]["Properties"]["IpAddressType"] = "DUAL_STACK"
+ failed_name = f"cfn-efs-ipv6-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=failed_name, TemplateBody=json.dumps(failing), OnFailure="DO_NOTHING")
+ assert _wait_stack(cfn, failed_name)["StackStatus"] == "CREATE_FAILED"
+ cfn.delete_stack(StackName=failed_name)
+ _wait_stack(cfn, failed_name)
+
+
# ---------------------------------------------------------------------------
# Update handlers, batch 5: the twelve types of #1601 C1 whose stack update
# fell through to the create handler and lost what the resource was holding.
diff --git a/tests/test_efs.py b/tests/test_efs.py
index fc394af4..73c80fd5 100644
--- a/tests/test_efs.py
+++ b/tests/test_efs.py
@@ -1,3 +1,5 @@
+import ipaddress
+import json
import os
import uuid as _uuid_mod
@@ -339,6 +341,72 @@ def test_efs_backup_policy(efs):
resp = efs.describe_backup_policy(FileSystemId=fs_id)
assert resp["BackupPolicy"]["Status"] == "ENABLED"
+def test_efs_file_system_policy(efs):
+ policy = (
+ '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"*"},'
+ '"Action":"elasticfilesystem:ClientMount"}]}'
+ )
+ fs_id = efs.create_file_system()["FileSystemId"]
+ with pytest.raises(ClientError) as exc:
+ efs.describe_file_system_policy(FileSystemId=fs_id)
+ assert exc.value.response["Error"]["Code"] == "PolicyNotFound"
+
+ put = efs.put_file_system_policy(FileSystemId=fs_id, Policy=policy)
+ assert put["FileSystemId"] == fs_id
+ # The documented example responses fill in an Id, a Sid per statement and
+ # the file system ARN as Resource.
+ stored = json.loads(put["Policy"])
+ arn = efs.describe_file_systems(FileSystemId=fs_id)["FileSystems"][0]["FileSystemArn"]
+ assert stored["Id"] == "1"
+ assert stored["Statement"][0]["Sid"].startswith("efs-statement-")
+ assert stored["Statement"][0]["Resource"] == arn
+ assert stored["Statement"][0]["Action"] == "elasticfilesystem:ClientMount"
+ assert efs.describe_file_system_policy(FileSystemId=fs_id)["Policy"] == put["Policy"]
+ assert "FileSystemPolicy" not in efs.describe_file_systems(FileSystemId=fs_id)["FileSystems"][0]
+
+ efs.delete_file_system_policy(FileSystemId=fs_id)
+ with pytest.raises(ClientError) as exc:
+ efs.describe_file_system_policy(FileSystemId=fs_id)
+ assert exc.value.response["Error"]["Code"] == "PolicyNotFound"
+
+ missing = "fs-00000000000000000"
+ for call, kwargs in (
+ (efs.put_file_system_policy, {"FileSystemId": missing, "Policy": policy}),
+ (efs.describe_file_system_policy, {"FileSystemId": missing}),
+ (efs.delete_file_system_policy, {"FileSystemId": missing}),
+ ):
+ with pytest.raises(ClientError) as exc:
+ call(**kwargs)
+ assert exc.value.response["Error"]["Code"] == "FileSystemNotFound"
+ efs.delete_file_system(FileSystemId=fs_id)
+
+
+def test_efs_availability_zone_name(efs):
+ fs = efs.create_file_system(AvailabilityZoneName="us-east-1a")
+ assert fs["AvailabilityZoneName"] == "us-east-1a"
+ desc = efs.describe_file_systems(FileSystemId=fs["FileSystemId"])["FileSystems"][0]
+ assert desc["AvailabilityZoneName"] == "us-east-1a"
+ efs.delete_file_system(FileSystemId=fs["FileSystemId"])
+
+
+def test_efs_delete_clears_lifecycle_and_backup_state():
+ from ministack.services import efs as service
+
+ service.reset()
+ try:
+ fs_id = json.loads(service._create_file_system({})[2])["FileSystemId"]
+ service._put_lifecycle_configuration(fs_id, {"LifecyclePolicies": [{"TransitionToIA": "AFTER_30_DAYS"}]})
+ service._put_backup_policy(fs_id, {"BackupPolicy": {"Status": "ENABLED"}})
+ assert fs_id in service._lifecycle_configs
+ assert fs_id in service._backup_policies
+
+ assert service._delete_file_system(fs_id)[0] == 204
+ assert fs_id not in service._lifecycle_configs
+ assert fs_id not in service._backup_policies
+ finally:
+ service.reset()
+
+
def _uid():
return _uuid_mod.uuid4().hex[:8]
@@ -365,39 +433,53 @@ def test_efs_update_file_system(efs):
efs.delete_file_system(FileSystemId=fs_id)
-def test_efs_describe_mount_target_security_groups(efs):
+def _default_vpc_security_groups(ec2, count):
+ return [
+ ec2.create_security_group(
+ GroupName=f"efs-{_uid()}", Description="efs test", VpcId="vpc-00000001")["GroupId"]
+ for _ in range(count)
+ ]
+
+
+def test_efs_describe_mount_target_security_groups(efs, ec2):
fs = efs.create_file_system(CreationToken=f"sg-desc-{_uid()}")
fs_id = fs["FileSystemId"]
+ groups = _default_vpc_security_groups(ec2, 2)
mt = efs.create_mount_target(
FileSystemId=fs_id,
SubnetId="subnet-00000001",
- SecurityGroups=["sg-aaa111aaa", "sg-bbb222bbb"],
+ SecurityGroups=groups,
)
mt_id = mt["MountTargetId"]
resp = efs.describe_mount_target_security_groups(MountTargetId=mt_id)
- assert set(resp["SecurityGroups"]) == {"sg-aaa111aaa", "sg-bbb222bbb"}
+ assert set(resp["SecurityGroups"]) == set(groups)
efs.delete_mount_target(MountTargetId=mt_id)
efs.delete_file_system(FileSystemId=fs_id)
-def test_efs_modify_mount_target_security_groups(efs):
+def test_efs_modify_mount_target_security_groups(efs, ec2):
fs = efs.create_file_system(CreationToken=f"sg-mod-{_uid()}")
fs_id = fs["FileSystemId"]
+ old, new1, new2 = _default_vpc_security_groups(ec2, 3)
mt = efs.create_mount_target(
FileSystemId=fs_id,
SubnetId="subnet-00000001",
- SecurityGroups=["sg-old111old"],
+ SecurityGroups=[old],
)
mt_id = mt["MountTargetId"]
efs.modify_mount_target_security_groups(
MountTargetId=mt_id,
- SecurityGroups=["sg-new111new", "sg-new222new"],
+ SecurityGroups=[new1, new2],
)
resp = efs.describe_mount_target_security_groups(MountTargetId=mt_id)
- assert set(resp["SecurityGroups"]) == {"sg-new111new", "sg-new222new"}
+ assert set(resp["SecurityGroups"]) == {new1, new2}
+
+ with pytest.raises(ClientError) as exc:
+ efs.modify_mount_target_security_groups(MountTargetId=mt_id, SecurityGroups=["sg-0123abcd"])
+ assert exc.value.response["Error"]["Code"] == "SecurityGroupNotFound"
efs.delete_mount_target(MountTargetId=mt_id)
efs.delete_file_system(FileSystemId=fs_id)
@@ -415,3 +497,246 @@ def test_efs_put_account_preferences(efs):
assert pref["ResourceIdType"] == "LONG_ID"
assert "FILE_SYSTEM" in pref["Resources"]
assert "MOUNT_TARGET" in pref["Resources"]
+
+
+# ---------------------------------------------------------------------------
+# File system policy validation, protection, replication and mount target
+# validation. Behavior follows the EFS API reference pages (documentation, not a
+# run against an AWS account).
+# ---------------------------------------------------------------------------
+
+_LOCKOUT_POLICY = json.dumps({
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Deny",
+ "Principal": {"AWS": "*"},
+ "Action": "elasticfilesystem:PutFileSystemPolicy",
+ "Resource": "*",
+ }],
+})
+
+
+def _error_code(call, **kwargs):
+ with pytest.raises(ClientError) as exc:
+ call(**kwargs)
+ return exc.value.response["Error"]["Code"]
+
+
+def test_efs_file_system_policy_validation_and_lockout_check(efs):
+ fs_id = efs.create_file_system()["FileSystemId"]
+ assert _error_code(efs.put_file_system_policy, FileSystemId=fs_id, Policy="not json") == "InvalidPolicyException"
+ assert _error_code(efs.put_file_system_policy, FileSystemId=fs_id, Policy="{}") == "InvalidPolicyException"
+ assert _error_code(
+ efs.put_file_system_policy, FileSystemId=fs_id, Policy=_LOCKOUT_POLICY) == "InvalidPolicyException"
+ assert _error_code(efs.describe_file_system_policy, FileSystemId=fs_id) == "PolicyNotFound"
+
+ efs.put_file_system_policy(
+ FileSystemId=fs_id, Policy=_LOCKOUT_POLICY, BypassPolicyLockoutSafetyCheck=True)
+ assert json.loads(efs.describe_file_system_policy(FileSystemId=fs_id)["Policy"])["Statement"][0]["Effect"] == "Deny"
+
+ # A Deny with a condition cannot be evaluated here and is not treated as a lockout.
+ conditional = json.loads(_LOCKOUT_POLICY)
+ conditional["Statement"][0]["Condition"] = {"Bool": {"aws:SecureTransport": "false"}}
+ efs.put_file_system_policy(FileSystemId=fs_id, Policy=json.dumps(conditional))
+ efs.delete_file_system(FileSystemId=fs_id)
+
+
+def test_efs_file_system_protection_defaults_and_updates(efs):
+ fs = efs.create_file_system()
+ fs_id = fs["FileSystemId"]
+ assert fs["FileSystemProtection"] == {"ReplicationOverwriteProtection": "ENABLED"}
+ described = efs.describe_file_systems(FileSystemId=fs_id)["FileSystems"][0]
+ assert described["FileSystemProtection"]["ReplicationOverwriteProtection"] == "ENABLED"
+
+ resp = efs.update_file_system_protection(FileSystemId=fs_id, ReplicationOverwriteProtection="DISABLED")
+ assert resp["ReplicationOverwriteProtection"] == "DISABLED"
+ described = efs.describe_file_systems(FileSystemId=fs_id)["FileSystems"][0]
+ assert described["FileSystemProtection"]["ReplicationOverwriteProtection"] == "DISABLED"
+
+ assert _error_code(
+ efs.update_file_system_protection, FileSystemId=fs_id,
+ ReplicationOverwriteProtection="REPLICATING") == "BadRequest"
+ assert _error_code(
+ efs.update_file_system_protection, FileSystemId="fs-00000000000000000",
+ ReplicationOverwriteProtection="ENABLED") == "FileSystemNotFound"
+ efs.delete_file_system(FileSystemId=fs_id)
+
+
+def test_efs_replication_lifecycle_in_one_region(efs):
+ source = efs.create_file_system(Encrypted=True)
+ source_id = source["FileSystemId"]
+ assert _error_code(efs.describe_replication_configurations, FileSystemId=source_id) == "ReplicationNotFound"
+ assert _error_code(efs.describe_replication_configurations, FileSystemId="fs-00000000000000000") == "FileSystemNotFound"
+ assert _error_code(efs.delete_replication_configuration, SourceFileSystemId=source_id) == "ReplicationNotFound"
+
+ config = efs.create_replication_configuration(SourceFileSystemId=source_id, Destinations=[{}])
+ destination = config["Destinations"][0]
+ destination_id = destination["FileSystemId"]
+ assert config["SourceFileSystemId"] == source_id
+ assert config["SourceFileSystemArn"] == source["FileSystemArn"]
+ assert destination["Status"] == "ENABLED"
+ assert destination["Region"] == efs.meta.region_name
+
+ target = efs.describe_file_systems(FileSystemId=destination_id)["FileSystems"][0]
+ assert target["FileSystemProtection"]["ReplicationOverwriteProtection"] == "REPLICATING"
+ assert target["Encrypted"] is True
+
+ by_source = efs.describe_replication_configurations(FileSystemId=source_id)["Replications"]
+ by_destination = efs.describe_replication_configurations(FileSystemId=destination_id)["Replications"]
+ assert by_source == by_destination and by_source[0]["SourceFileSystemId"] == source_id
+ assert source_id in {r["SourceFileSystemId"] for r in efs.describe_replication_configurations()["Replications"]}
+
+ # One configuration per file system, as source or destination; both are undeletable meanwhile.
+ assert _error_code(
+ efs.create_replication_configuration, SourceFileSystemId=source_id, Destinations=[{}]) == "BadRequest"
+ assert _error_code(
+ efs.create_replication_configuration, SourceFileSystemId=destination_id, Destinations=[{}]) == "BadRequest"
+ assert _error_code(efs.delete_file_system, FileSystemId=source_id) == "FileSystemInUse"
+ assert _error_code(efs.delete_file_system, FileSystemId=destination_id) == "FileSystemInUse"
+ assert _error_code(
+ efs.update_file_system_protection, FileSystemId=destination_id,
+ ReplicationOverwriteProtection="ENABLED") == "ReplicationAlreadyExists"
+ assert _error_code(
+ efs.delete_replication_configuration, SourceFileSystemId=source_id,
+ DeletionMode="LOCAL_CONFIGURATION_ONLY") == "BadRequest"
+
+ efs.delete_replication_configuration(SourceFileSystemId=source_id)
+ assert _error_code(efs.describe_replication_configurations, FileSystemId=source_id) == "ReplicationNotFound"
+ target = efs.describe_file_systems(FileSystemId=destination_id)["FileSystems"][0]
+ assert target["FileSystemProtection"]["ReplicationOverwriteProtection"] == "ENABLED"
+ efs.delete_file_system(FileSystemId=source_id)
+ efs.delete_file_system(FileSystemId=destination_id)
+
+
+def test_efs_replication_to_another_region_and_existing_destination():
+ east = _efs_client("us-east-1")
+ west = _efs_client("us-west-2")
+ source_id = east.create_file_system()["FileSystemId"]
+ config = east.create_replication_configuration(
+ SourceFileSystemId=source_id, Destinations=[{"Region": "us-west-2"}])
+ destination_id = config["Destinations"][0]["FileSystemId"]
+ try:
+ assert config["SourceFileSystemRegion"] == "us-east-1"
+ assert config["Destinations"][0]["Region"] == "us-west-2"
+ # The destination lives in its own region and sees the configuration from there.
+ assert west.describe_file_systems(FileSystemId=destination_id)["FileSystems"][0][
+ "FileSystemProtection"]["ReplicationOverwriteProtection"] == "REPLICATING"
+ assert west.describe_replication_configurations(
+ FileSystemId=destination_id)["Replications"][0]["SourceFileSystemId"] == source_id
+ finally:
+ east.delete_replication_configuration(SourceFileSystemId=source_id)
+
+ # An existing destination needs overwrite protection DISABLED, and may not be less encrypted.
+ other_id = east.create_file_system()["FileSystemId"]
+ assert _error_code(
+ east.create_replication_configuration, SourceFileSystemId=other_id,
+ Destinations=[{"FileSystemId": destination_id, "Region": "us-west-2"}]) == "BadRequest"
+ west.update_file_system_protection(FileSystemId=destination_id, ReplicationOverwriteProtection="DISABLED")
+ encrypted_id = east.create_file_system(Encrypted=True)["FileSystemId"]
+ assert _error_code(
+ east.create_replication_configuration, SourceFileSystemId=encrypted_id,
+ Destinations=[{"FileSystemId": destination_id, "Region": "us-west-2"}]) == "ConflictException"
+ east.create_replication_configuration(
+ SourceFileSystemId=other_id, Destinations=[{"FileSystemId": destination_id, "Region": "us-west-2"}])
+ east.delete_replication_configuration(SourceFileSystemId=other_id)
+
+ for client, fs_id in ((east, source_id), (east, other_id), (east, encrypted_id), (west, destination_id)):
+ client.delete_file_system(FileSystemId=fs_id)
+
+
+def test_efs_mount_target_validates_subnet_security_groups_and_zone(efs, ec2):
+ fs_id = efs.create_file_system()["FileSystemId"]
+ assert _error_code(
+ efs.create_mount_target, FileSystemId=fs_id, SubnetId="subnet-0123abcd") == "SubnetNotFound"
+ assert _error_code(
+ efs.create_mount_target, FileSystemId="fs-00000000000000000",
+ SubnetId="subnet-00000001") == "FileSystemNotFound"
+
+ other_vpc = ec2.create_vpc(CidrBlock="10.77.0.0/16")["Vpc"]["VpcId"]
+ foreign_group = ec2.create_security_group(
+ GroupName=f"efs-{_uid()}", Description="other vpc", VpcId=other_vpc)["GroupId"]
+ assert _error_code(
+ efs.create_mount_target, FileSystemId=fs_id, SubnetId="subnet-00000001",
+ SecurityGroups=[foreign_group]) == "SecurityGroupNotFound"
+
+ # No security group given: the subnet's VPC default group.
+ mt = efs.create_mount_target(FileSystemId=fs_id, SubnetId="subnet-00000001")
+ assert efs.describe_mount_target_security_groups(MountTargetId=mt["MountTargetId"])["SecurityGroups"] == [
+ "sg-00000001"]
+ assert mt["VpcId"] == "vpc-00000001"
+ assert mt["AvailabilityZoneName"].endswith("a")
+ assert mt["AvailabilityZoneId"]
+ assert mt["NetworkInterfaceId"].startswith("eni-") and "[" not in mt["NetworkInterfaceId"]
+ assert ipaddress.ip_address(mt["IpAddress"]) in ipaddress.ip_network("172.31.0.0/20")
+ assert "Ipv6Address" not in mt
+
+ # One mount target per Availability Zone; a second subnet in another zone is fine.
+ assert _error_code(
+ efs.create_mount_target, FileSystemId=fs_id, SubnetId="subnet-00000001") == "MountTargetConflict"
+ second = efs.create_mount_target(FileSystemId=fs_id, SubnetId="subnet-00000002")
+ assert second["AvailabilityZoneName"].endswith("b")
+
+ # A One Zone file system takes only its own zone.
+ one_zone = efs.create_file_system(AvailabilityZoneName=mt["AvailabilityZoneName"])
+ assert one_zone["AvailabilityZoneName"] == mt["AvailabilityZoneName"]
+ assert _error_code(
+ efs.create_mount_target, FileSystemId=one_zone["FileSystemId"],
+ SubnetId="subnet-00000002") == "AvailabilityZonesMismatch"
+
+ for mount_target in (mt, second):
+ efs.delete_mount_target(MountTargetId=mount_target["MountTargetId"])
+ for file_system in (fs_id, one_zone["FileSystemId"]):
+ efs.delete_file_system(FileSystemId=file_system)
+
+
+def test_efs_mount_target_ip_addresses(efs, ec2):
+ vpc_id = ec2.create_vpc(CidrBlock="10.78.0.0/16")["Vpc"]["VpcId"]
+ subnet_id = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.78.1.0/29")["Subnet"]["SubnetId"]
+ file_systems = [efs.create_file_system()["FileSystemId"] for _ in range(4)]
+ created = []
+ try:
+ # The first four addresses and the last are reserved, so a /29 holds three mount targets.
+ for fs_id in file_systems[:3]:
+ created.append(efs.create_mount_target(FileSystemId=fs_id, SubnetId=subnet_id))
+ assert [mt["IpAddress"] for mt in created] == ["10.78.1.4", "10.78.1.5", "10.78.1.6"]
+ assert _error_code(
+ efs.create_mount_target, FileSystemId=file_systems[3],
+ SubnetId=subnet_id) == "NoFreeAddressesInSubnet"
+ assert _error_code(
+ efs.create_mount_target, FileSystemId=file_systems[3], SubnetId=subnet_id,
+ IpAddress="10.78.1.5") == "IpAddressInUse"
+ assert _error_code(
+ efs.create_mount_target, FileSystemId=file_systems[3], SubnetId=subnet_id,
+ IpAddress="10.99.1.5") == "BadRequest"
+ finally:
+ for mt in created:
+ efs.delete_mount_target(MountTargetId=mt["MountTargetId"])
+ for fs_id in file_systems:
+ efs.delete_file_system(FileSystemId=fs_id)
+
+ # An address in range is taken as given.
+ fs_id = efs.create_file_system()["FileSystemId"]
+ mt = efs.create_mount_target(FileSystemId=fs_id, SubnetId="subnet-00000003", IpAddress="172.31.32.200")
+ assert mt["IpAddress"] == "172.31.32.200"
+ efs.delete_mount_target(MountTargetId=mt["MountTargetId"])
+ efs.delete_file_system(FileSystemId=fs_id)
+
+
+def test_efs_mount_target_ip_address_type_must_match_the_subnet(efs):
+ fs_id = efs.create_file_system()["FileSystemId"]
+ # The default subnets have no IPv6 CIDR block, so the IPv6 types do not match them.
+ for address_type in ("IPV6_ONLY", "DUAL_STACK"):
+ assert _error_code(
+ efs.create_mount_target, FileSystemId=fs_id, SubnetId="subnet-00000001",
+ IpAddressType=address_type) == "BadRequest"
+ assert _error_code(
+ efs.create_mount_target, FileSystemId=fs_id, SubnetId="subnet-00000001",
+ IpAddressType="IPV4_ONLY", Ipv6Address="2001:db8::10") == "BadRequest"
+ assert _error_code(
+ efs.create_mount_target, FileSystemId=fs_id, SubnetId="subnet-00000001",
+ IpAddressType="IPV6_ONLY", IpAddress="172.31.0.9") == "BadRequest"
+ mt = efs.create_mount_target(
+ FileSystemId=fs_id, SubnetId="subnet-00000001", IpAddressType="IPV4_ONLY")
+ assert "Ipv6Address" not in mt
+ efs.delete_mount_target(MountTargetId=mt["MountTargetId"])
+ efs.delete_file_system(FileSystemId=fs_id)
\ No newline at end of file