Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(s3files): align routes and shapes with AWS s3files-2025-05-05 spec (#550)
Nahuel Nucera0d82bc0e87e0
diff --git a/ministack/services/s3files.py b/ministack/services/s3files.pyindex c9c5fc50..8d4f2d42 100644--- a/ministack/services/s3files.py+++ b/ministack/services/s3files.py@@ -1,6 +1,6 @@"""-Amazon S3 Files Service Emulator.-REST/JSON API — file systems, mount targets, access points.+Amazon S3 Files Service Emulator (s3files-2025-05-05).+REST/JSON API. Routes, payloads, and response shapes match the AWS spec.Supports:File Systems: CreateFileSystem, GetFileSystem, ListFileSystems, DeleteFileSystem@@ -12,25 +12,35 @@ Supports:Tags: TagResource, UntagResource, ListTagsForResource"""+import base64import copyimport jsonimport logging-import os+import reimport time+from urllib.parse import unquote-from ministack.core.persistence import PERSIST_STATE, load_state+from ministack.core.persistence import load_statefrom ministack.core.responses import (AccountScopedDict,error_response_json,get_account_id,get_region,- json_response,new_uuid,)-logger = logging.getLogger("s3files")+_JSON_CT = "application/json"+++def _json(body, status=200):+ """restJson1 response: spec mandates Content-Type: application/json."""+ return status, {"Content-Type": _JSON_CT}, json.dumps(body, ensure_ascii=False).encode("utf-8")-REGION = os.environ.get("MINISTACK_REGION", "us-east-1")++def _empty_200():+ return 200, {"Content-Type": _JSON_CT}, b""++logger = logging.getLogger("s3files")_file_systems = AccountScopedDict()_mount_targets = AccountScopedDict()@@ -67,10 +77,7 @@ try:if _restored:restore_state(_restored)except Exception:- import logging- logging.getLogger(__name__).exception(- "Failed to restore persisted state; continuing with fresh store"- )+ logger.exception("Failed to restore persisted state; continuing with fresh store")def reset():@@ -82,158 +89,293 @@ def reset():_tags.clear()-def _arn(resource_type, resource_id):- return f"arn:aws:s3files:{get_region()}:{get_account_id()}:{resource_type}/{resource_id}"+# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+_FS_ARN_RE = re.compile(r"^arn:aws[-a-z]*:s3files:[^:]*:[^:]*:file-system/(fs-[0-9a-f]{17,40})(?:/access-point/(fsap-[0-9a-f]{17,40}))?$")-def _now_iso():- return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())+def _hex_id(prefix):+ return prefix + new_uuid().replace("-", "")[:20]-# ----------------------------------------------------------------------------# Request handler-# ----------------------------------------------------------------------------async def handle_request(method, path, headers, body, query_params):- try:- data = json.loads(body) if body else {}- except (json.JSONDecodeError, TypeError):- data = {}+def _resolve_id(value, prefer="fs"):+ """Normalize a bare ID or full ARN to the bare ID.+ `prefer="fs"` returns the file-system ID; `prefer="ap"` returns the+ access-point ID (falling back to file-system ID); `prefer="any"` returns+ whichever is most specific (access-point if present, else file-system).+ """+ if not value:+ return ""+ m = _FS_ARN_RE.match(value)+ if not m:+ return value+ if prefer == "fs":+ return m.group(1)+ if prefer == "ap":+ return m.group(2) or m.group(1)+ return m.group(2) or m.group(1)- parts = [p for p in path.strip("/").split("/") if p]- # POST /file-systems- if method == "POST" and parts == ["file-systems"]:- return _create_file_system(data)+def _fs_arn(fs_id):+ return f"arn:aws:s3files:{get_region()}:{get_account_id()}:file-system/{fs_id}"- # GET /file-systems- if method == "GET" and parts == ["file-systems"]:- return _list_file_systems(data, query_params)- # GET /file-systems/{id}- if method == "GET" and len(parts) == 2 and parts[0] == "file-systems":- return _get_file_system(parts[1])+def _ap_arn(fs_id, ap_id):+ return f"arn:aws:s3files:{get_region()}:{get_account_id()}:file-system/{fs_id}/access-point/{ap_id}"- # DELETE /file-systems/{id}- if method == "DELETE" and len(parts) == 2 and parts[0] == "file-systems":- return _delete_file_system(parts[1])- # GET /file-systems/{id}/policy- if method == "GET" and len(parts) == 3 and parts[0] == "file-systems" and parts[2] == "policy":- return _get_file_system_policy(parts[1])+def _name_from_tags(tags):+ for t in tags or ():+ if t.get("key") == "Name":+ return t.get("value", "")+ return ""- # PUT /file-systems/{id}/policy- if method == "PUT" and len(parts) == 3 and parts[0] == "file-systems" and parts[2] == "policy":- return _put_file_system_policy(parts[1], data)- # DELETE /file-systems/{id}/policy- if method == "DELETE" and len(parts) == 3 and parts[0] == "file-systems" and parts[2] == "policy":- return _delete_file_system_policy(parts[1])+def _now_epoch():+ return int(time.time())- # POST /mount-targets- if method == "POST" and parts == ["mount-targets"]:- return _create_mount_target(data)- # GET /mount-targets- if method == "GET" and parts == ["mount-targets"]:- return _list_mount_targets(data, query_params)+def _qp_str(query_params, key, default=""):+ v = query_params.get(key)+ if isinstance(v, list):+ return v[0] if v else default+ return v if v is not None else default- # GET /mount-targets/{id}- if method == "GET" and len(parts) == 2 and parts[0] == "mount-targets":- return _get_mount_target(parts[1])- # PUT /mount-targets/{id}- if method == "PUT" and len(parts) == 2 and parts[0] == "mount-targets":- return _update_mount_target(parts[1], data)+def _qp_int(query_params, key, default=None):+ raw = _qp_str(query_params, key, "")+ if raw == "":+ return default+ try:+ return int(raw)+ except ValueError:+ return default+++def _qp_list(query_params, key):+ v = query_params.get(key)+ if v is None:+ return []+ return v if isinstance(v, list) else [v]+++def _opaque_encode(offset):+ return base64.urlsafe_b64encode(str(offset).encode()).decode().rstrip("=")+++def _opaque_decode(token):+ if not token:+ return 0+ try:+ pad = "=" * (-len(token) % 4)+ return int(base64.urlsafe_b64decode(token + pad).decode())+ except Exception:+ return 0+- # DELETE /mount-targets/{id}- if method == "DELETE" and len(parts) == 2 and parts[0] == "mount-targets":- return _delete_mount_target(parts[1])+def _paginate(items, max_results, next_token):+ start = _opaque_decode(next_token)+ end = start + max_results+ page = items[start:end]+ nxt = _opaque_encode(end) if end < len(items) else None+ return page, nxt- # POST /access-points- if method == "POST" and parts == ["access-points"]:- return _create_access_point(data)- # GET /access-points- if method == "GET" and parts == ["access-points"]:- return _list_access_points(data, query_params)+def _error(code, message, status):+ """restJson1 error: shared helper uses application/x-amz-json-1.0 — override+ Content-Type to application/json while keeping the __type body and+ x-amzn-errortype header (which boto3/Java/Go SDK v2 all read)."""+ s, headers, body = error_response_json(code, message, status)+ return s, {**headers, "Content-Type": _JSON_CT}, body- # GET /access-points/{id}- if method == "GET" and len(parts) == 2 and parts[0] == "access-points":- return _get_access_point(parts[1])- # DELETE /access-points/{id}- if method == "DELETE" and len(parts) == 2 and parts[0] == "access-points":- return _delete_access_point(parts[1])+def _VALIDATION(msg):+ return _error("ValidationException", msg, 400)- # GET /file-systems/{id}/synchronization-configuration- if method == "GET" and len(parts) == 3 and parts[2] == "synchronization-configuration":- return _get_sync_config(parts[1])- # PUT /file-systems/{id}/synchronization-configuration- if method == "PUT" and len(parts) == 3 and parts[2] == "synchronization-configuration":- return _put_sync_config(parts[1], data)+def _NOT_FOUND(msg):+ return _error("ResourceNotFoundException", msg, 404)- # POST /tags/{arn}- if method == "POST" and len(parts) >= 2 and parts[0] == "tags":- resource_arn = "/".join(parts[1:])- return _tag_resource(resource_arn, data)- # DELETE /tags/{arn}- if method == "DELETE" and len(parts) >= 2 and parts[0] == "tags":- resource_arn = "/".join(parts[1:])- tag_keys = query_params.get("tagKeys", [])- if isinstance(tag_keys, str):- tag_keys = [tag_keys]- return _untag_resource(resource_arn, tag_keys)+def _CONFLICT(msg):+ return _error("ConflictException", msg, 409)- # GET /tags/{arn}- if method == "GET" and len(parts) >= 2 and parts[0] == "tags":- resource_arn = "/".join(parts[1:])- return _list_tags(resource_arn)- return error_response_json("InvalidRequest", f"Unknown S3 Files route: {method} {path}", 400)+# ---------------------------------------------------------------------------+# Request handler+# ---------------------------------------------------------------------------++async def handle_request(method, path, headers, body, query_params):+ try:+ data = json.loads(body) if body else {}+ except (json.JSONDecodeError, TypeError):+ data = {}++ parts = [unquote(p) for p in path.strip("/").split("/") if p]++ # /file-systems+ if parts and parts[0] == "file-systems":+ if len(parts) == 1:+ if method == "PUT":+ return _create_file_system(data)+ if method == "GET":+ return _list_file_systems(query_params)+ elif len(parts) == 2:+ fs_id = _resolve_id(parts[1])+ if method == "GET":+ return _get_file_system(fs_id)+ if method == "DELETE":+ return _delete_file_system(fs_id)+ elif len(parts) == 3 and parts[2] == "policy":+ fs_id = _resolve_id(parts[1])+ if method == "GET":+ return _get_file_system_policy(fs_id)+ if method == "PUT":+ return _put_file_system_policy(fs_id, data)+ if method == "DELETE":+ return _delete_file_system_policy(fs_id)+ elif len(parts) == 3 and parts[2] == "synchronization-configuration":+ fs_id = _resolve_id(parts[1])+ if method == "GET":+ return _get_sync_config(fs_id)+ if method == "PUT":+ return _put_sync_config(fs_id, data)++ # /mount-targets+ if parts and parts[0] == "mount-targets":+ if len(parts) == 1:+ if method == "PUT":+ return _create_mount_target(data)+ if method == "GET":+ return _list_mount_targets(query_params)+ elif len(parts) == 2:+ mt_id = parts[1]+ if method == "GET":+ return _get_mount_target(mt_id)+ if method == "PUT":+ return _update_mount_target(mt_id, data)+ if method == "DELETE":+ return _delete_mount_target(mt_id)++ # /access-points+ if parts and parts[0] == "access-points":+ if len(parts) == 1:+ if method == "PUT":+ return _create_access_point(data)+ if method == "GET":+ return _list_access_points(query_params)+ elif len(parts) == 2:+ ap_id = _resolve_id(parts[1], prefer="ap")+ if method == "GET":+ return _get_access_point(ap_id)+ if method == "DELETE":+ return _delete_access_point(ap_id)++ # /resource-tags/{resourceId}+ if parts and parts[0] == "resource-tags" and len(parts) >= 2:+ resource_id = _resolve_id("/".join(parts[1:]), prefer="any")+ if method == "POST":+ return _tag_resource(resource_id, data)+ if method == "DELETE":+ keys = _qp_list(query_params, "tagKeys")+ return _untag_resource(resource_id, keys)+ if method == "GET":+ return _list_tags_for_resource(resource_id, query_params)++ return _VALIDATION(f"Unknown S3 Files route: {method} {path}")# ---------------------------------------------------------------------------# File Systems# ---------------------------------------------------------------------------+def _file_system_record(fs_id):+ return _file_systems.get(fs_id)++def _create_file_system(data):- fs_id = "fs-" + new_uuid().replace("-", "")[:17]- bucket_name = data.get("BucketName", "")- arn = _arn("file-system", fs_id)+ bucket = data.get("bucket")+ role_arn = data.get("roleArn")+ if not bucket:+ return _VALIDATION("bucket is required")+ if not role_arn:+ return _VALIDATION("roleArn is required")++ fs_id = _hex_id("fs-")+ arn = _fs_arn(fs_id)+ tags = list(data.get("tags") or [])+ name = _name_from_tags(tags)+fs = {- "FileSystemId": fs_id,- "FileSystemArn": arn,- "BucketName": bucket_name,- "LifeCycleState": "available",- "CreationTime": _now_iso(),- "OwnerId": get_account_id(),+ "fileSystemId": fs_id,+ "fileSystemArn": arn,+ "bucket": bucket,+ "roleArn": role_arn,+ "prefix": data.get("prefix", ""),+ "kmsKeyId": data.get("kmsKeyId", ""),+ "clientToken": data.get("clientToken", ""),+ "name": name,+ "ownerId": get_account_id(),+ "creationTime": _now_epoch(),+ "status": "available",+ "statusMessage": "",+ "tags": tags,}_file_systems[fs_id] = fs- logger.info("Created S3 file system %s for bucket %s", fs_id, bucket_name)- return json_response(fs, 201)+ if tags:+ _tags[fs_id] = list(tags)+ logger.info("Created S3 Files file system %s for bucket %s", fs_id, bucket)+ return _json(fs, 201)def _get_file_system(fs_id):- fs = _file_systems.get(fs_id)+ fs = _file_system_record(fs_id)if not fs:- return error_response_json("FileSystemNotFound", f"File system {fs_id} not found", 404)- return json_response(fs)+ return _NOT_FOUND(f"File system {fs_id} not found")+ out = dict(fs)+ out["tags"] = list(_tags.get(fs_id, fs.get("tags", [])))+ return _json(out)-def _list_file_systems(data, query_params):+def _list_file_systems(query_params):+ bucket = _qp_str(query_params, "bucket")+ max_results = _qp_int(query_params, "maxResults", 100) or 100+ next_token = _qp_str(query_params, "nextToken")+items = list(_file_systems.values())- return json_response({"FileSystems": items})+ if bucket:+ items = [fs for fs in items if fs.get("bucket") == bucket]++ summaries = [+ {+ "fileSystemId": fs["fileSystemId"],+ "fileSystemArn": fs["fileSystemArn"],+ "bucket": fs["bucket"],+ "roleArn": fs["roleArn"],+ "name": fs.get("name", ""),+ "ownerId": fs["ownerId"],+ "creationTime": fs["creationTime"],+ "status": fs["status"],+ "statusMessage": fs.get("statusMessage", ""),+ }+ for fs in items+ ]+ page, nxt = _paginate(summaries, max_results, next_token)+ out = {"fileSystems": page}+ if nxt:+ out["nextToken"] = nxt+ return _json(out)def _delete_file_system(fs_id):if fs_id not in _file_systems:- return error_response_json("FileSystemNotFound", f"File system {fs_id} not found", 404)+ return _NOT_FOUND(f"File system {fs_id} not found")del _file_systems[fs_id]_policies.pop(fs_id, None)_sync_configs.pop(fs_id, None)+ _tags.pop(fs_id, None)return 204, {}, b""@@ -241,52 +383,100 @@ def _delete_file_system(fs_id):# Mount Targets# ---------------------------------------------------------------------------+def _mt_response(mt):+ return {+ "mountTargetId": mt["mountTargetId"],+ "fileSystemId": mt["fileSystemId"],+ "subnetId": mt["subnetId"],+ "vpcId": mt.get("vpcId", "vpc-00000000"),+ "availabilityZoneId": mt.get("availabilityZoneId", f"{get_region()}-az1"),+ "ipv4Address": mt.get("ipv4Address", "10.0.0.10"),+ "ipv6Address": mt.get("ipv6Address", ""),+ "networkInterfaceId": mt.get("networkInterfaceId", ""),+ "ownerId": mt.get("ownerId", get_account_id()),+ "securityGroups": list(mt.get("securityGroups", [])),+ "status": mt.get("status", "available"),+ "statusMessage": mt.get("statusMessage", ""),+ }++def _create_mount_target(data):- mt_id = "fsmt-" + new_uuid().replace("-", "")[:17]- fs_id = data.get("FileSystemId", "")- subnet_id = data.get("SubnetId", "")+ fs_ref = data.get("fileSystemId")+ subnet_id = data.get("subnetId")+ if not fs_ref:+ return _VALIDATION("fileSystemId is required")+ if not subnet_id:+ return _VALIDATION("subnetId is required")+ fs_id = _resolve_id(fs_ref)+ if fs_id not in _file_systems:+ return _NOT_FOUND(f"File system {fs_id} not found")++ mt_id = _hex_id("fsmt-")mt = {- "MountTargetId": mt_id,- "FileSystemId": fs_id,- "SubnetId": subnet_id,- "LifeCycleState": "available",- "IpAddress": data.get("IpAddress", "10.0.0.1"),- "VpcId": data.get("VpcId", "vpc-00000001"),- "AvailabilityZone": data.get("AvailabilityZone", f"{get_region()}a"),+ "mountTargetId": mt_id,+ "fileSystemId": fs_id,+ "subnetId": subnet_id,+ "vpcId": "vpc-00000000",+ "availabilityZoneId": f"{get_region()}-az1",+ "ipv4Address": data.get("ipv4Address") or "10.0.0.10",+ "ipv6Address": data.get("ipv6Address", ""),+ "networkInterfaceId": "eni-" + new_uuid().replace("-", "")[:17],+ "ownerId": get_account_id(),+ "securityGroups": list(data.get("securityGroups") or []),+ "status": "available",+ "statusMessage": "",}_mount_targets[mt_id] = mtlogger.info("Created mount target %s for fs %s", mt_id, fs_id)- return json_response(mt, 201)+ return _json(_mt_response(mt))def _get_mount_target(mt_id):mt = _mount_targets.get(mt_id)if not mt:- return error_response_json("MountTargetNotFound", f"Mount target {mt_id} not found", 404)- return json_response(mt)+ return _NOT_FOUND(f"Mount target {mt_id} not found")+ return _json(_mt_response(mt))-def _list_mount_targets(data, query_params):- fs_id = query_params.get("FileSystemId", [""])[0] if isinstance(query_params.get("FileSystemId"), list) else query_params.get("FileSystemId", "")+def _list_mount_targets(query_params):+ fs_ref = _qp_str(query_params, "fileSystemId")+ ap_ref = _qp_str(query_params, "accessPointId")+ max_results = _qp_int(query_params, "maxResults", 100) or 100+ next_token = _qp_str(query_params, "nextToken")+items = list(_mount_targets.values())- if fs_id:- items = [mt for mt in items if mt.get("FileSystemId") == fs_id]- return json_response({"MountTargets": items})+ if fs_ref:+ fs_id = _resolve_id(fs_ref)+ items = [mt for mt in items if mt.get("fileSystemId") == fs_id]+ if ap_ref:+ ap_id = _resolve_id(ap_ref, prefer="ap")+ ap = _access_points.get(ap_id)+ if ap:+ items = [mt for mt in items if mt.get("fileSystemId") == ap.get("fileSystemId")]+ else:+ items = []++ summaries = [_mt_response(mt) for mt in items]+ page, nxt = _paginate(summaries, max_results, next_token)+ out = {"mountTargets": page}+ if nxt:+ out["nextToken"] = nxt+ return _json(out)def _update_mount_target(mt_id, data):mt = _mount_targets.get(mt_id)if not mt:- return error_response_json("MountTargetNotFound", f"Mount target {mt_id} not found", 404)- for key in ("SubnetId", "IpAddress", "SecurityGroups"):- if key in data:- mt[key] = data[key]- return json_response(mt)+ return _NOT_FOUND(f"Mount target {mt_id} not found")+ if "securityGroups" not in data:+ return _VALIDATION("securityGroups is required")+ mt["securityGroups"] = list(data["securityGroups"])+ return _json(_mt_response(mt))def _delete_mount_target(mt_id):if mt_id not in _mount_targets:- return error_response_json("MountTargetNotFound", f"Mount target {mt_id} not found", 404)+ return _NOT_FOUND(f"Mount target {mt_id} not found")del _mount_targets[mt_id]return 204, {}, b""@@ -295,98 +485,215 @@ def _delete_mount_target(mt_id):# Access Points# ---------------------------------------------------------------------------+def _ap_response(ap):+ return {+ "accessPointId": ap["accessPointId"],+ "accessPointArn": ap["accessPointArn"],+ "fileSystemId": ap["fileSystemId"],+ "name": ap.get("name", ""),+ "ownerId": ap.get("ownerId", get_account_id()),+ "clientToken": ap.get("clientToken", ""),+ "posixUser": ap.get("posixUser") or {},+ "rootDirectory": ap.get("rootDirectory") or {},+ "status": ap.get("status", "available"),+ "tags": list(_tags.get(ap["accessPointId"], ap.get("tags", []))),+ }++def _create_access_point(data):- ap_id = "fsap-" + new_uuid().replace("-", "")[:17]- fs_id = data.get("FileSystemId", "")- arn = _arn("access-point", ap_id)+ fs_ref = data.get("fileSystemId")+ if not fs_ref:+ return _VALIDATION("fileSystemId is required")+ fs_id = _resolve_id(fs_ref)+ if fs_id not in _file_systems:+ return _NOT_FOUND(f"File system {fs_id} not found")++ ap_id = _hex_id("fsap-")+ arn = _ap_arn(fs_id, ap_id)+ tags = list(data.get("tags") or [])+ name = _name_from_tags(tags)+ap = {- "AccessPointId": ap_id,- "AccessPointArn": arn,- "FileSystemId": fs_id,- "Name": data.get("Name", ""),- "LifeCycleState": "available",+ "accessPointId": ap_id,+ "accessPointArn": arn,+ "fileSystemId": fs_id,+ "name": name,+ "ownerId": get_account_id(),+ "clientToken": data.get("clientToken", ""),+ "posixUser": data.get("posixUser") or {},+ "rootDirectory": data.get("rootDirectory") or {},+ "status": "available",+ "tags": tags,}_access_points[ap_id] = ap- return json_response(ap, 201)+ if tags:+ _tags[ap_id] = list(tags)+ return _json(_ap_response(ap))def _get_access_point(ap_id):ap = _access_points.get(ap_id)if not ap:- return error_response_json("AccessPointNotFound", f"Access point {ap_id} not found", 404)- return json_response(ap)---def _list_access_points(data, query_params):- items = list(_access_points.values())- return json_response({"AccessPoints": items})+ return _NOT_FOUND(f"Access point {ap_id} not found")+ return _json(_ap_response(ap))+++def _list_access_points(query_params):+ fs_ref = _qp_str(query_params, "fileSystemId")+ if not fs_ref:+ return _VALIDATION("fileSystemId is required")+ fs_id = _resolve_id(fs_ref)+ max_results = _qp_int(query_params, "maxResults", 1000) or 1000+ next_token = _qp_str(query_params, "nextToken")++ items = [ap for ap in _access_points.values() if ap.get("fileSystemId") == fs_id]+ summaries = [+ {+ "accessPointId": ap["accessPointId"],+ "accessPointArn": ap["accessPointArn"],+ "fileSystemId": ap["fileSystemId"],+ "name": ap.get("name", ""),+ "ownerId": ap.get("ownerId", get_account_id()),+ "posixUser": ap.get("posixUser") or {},+ "rootDirectory": ap.get("rootDirectory") or {},+ "status": ap.get("status", "available"),+ }+ for ap in items+ ]+ page, nxt = _paginate(summaries, max_results, next_token)+ out = {"accessPoints": page}+ if nxt:+ out["nextToken"] = nxt+ return _json(out)def _delete_access_point(ap_id):if ap_id not in _access_points:- return error_response_json("AccessPointNotFound", f"Access point {ap_id} not found", 404)+ return _NOT_FOUND(f"Access point {ap_id} not found")del _access_points[ap_id]+ _tags.pop(ap_id, None)return 204, {}, b""# ----------------------------------------------------------------------------# Policies+# File-system policy# ---------------------------------------------------------------------------def _get_file_system_policy(fs_id):+ if fs_id not in _file_systems:+ return _NOT_FOUND(f"File system {fs_id} not found")policy = _policies.get(fs_id)if not policy:- return error_response_json("PolicyNotFound", f"No policy for file system {fs_id}", 404)- return json_response({"FileSystemId": fs_id, "Policy": policy})+ return _NOT_FOUND(f"No policy for file system {fs_id}")+ return _json({"fileSystemId": fs_id, "policy": policy})def _put_file_system_policy(fs_id, data):if fs_id not in _file_systems:- return error_response_json("FileSystemNotFound", f"File system {fs_id} not found", 404)- _policies[fs_id] = data.get("Policy", "")- return json_response({"FileSystemId": fs_id, "Policy": _policies[fs_id]})+ return _NOT_FOUND(f"File system {fs_id} not found")+ policy = data.get("policy")+ if not policy:+ return _VALIDATION("policy is required")+ _policies[fs_id] = policy+ return _empty_200()def _delete_file_system_policy(fs_id):+ if fs_id not in _file_systems:+ return _NOT_FOUND(f"File system {fs_id} not found")_policies.pop(fs_id, None)return 204, {}, b""# ----------------------------------------------------------------------------# Synchronization Configuration+# Synchronization configuration# ---------------------------------------------------------------------------def _get_sync_config(fs_id):- config = _sync_configs.get(fs_id, {})- return json_response({"FileSystemId": fs_id, "SynchronizationConfiguration": config})+ if fs_id not in _file_systems:+ return _NOT_FOUND(f"File system {fs_id} not found")+ cfg = _sync_configs.get(fs_id)+ if not cfg:+ return _NOT_FOUND(f"No synchronization configuration for file system {fs_id}")+ return _json({+ "expirationDataRules": cfg.get("expirationDataRules", []),+ "importDataRules": cfg.get("importDataRules", []),+ "latestVersionNumber": cfg.get("latestVersionNumber", 1),+ })def _put_sync_config(fs_id, data):if fs_id not in _file_systems:- return error_response_json("FileSystemNotFound", f"File system {fs_id} not found", 404)- _sync_configs[fs_id] = data.get("SynchronizationConfiguration", data)- return json_response({"FileSystemId": fs_id, "SynchronizationConfiguration": _sync_configs[fs_id]})+ return _NOT_FOUND(f"File system {fs_id} not found")+ expiration = data.get("expirationDataRules")+ imports = data.get("importDataRules")+ if not expiration:+ return _VALIDATION("expirationDataRules is required")+ if not imports:+ return _VALIDATION("importDataRules is required")++ current = _sync_configs.get(fs_id)+ expected_version = data.get("latestVersionNumber")+ if current and expected_version is not None and expected_version != current.get("latestVersionNumber"):+ return _CONFLICT("latestVersionNumber does not match the current configuration")++ new_version = (current.get("latestVersionNumber", 0) + 1) if current else 1+ _sync_configs[fs_id] = {+ "expirationDataRules": list(expiration),+ "importDataRules": list(imports),+ "latestVersionNumber": new_version,+ }+ return _empty_200()# ----------------------------------------------------------------------------# Tags+# Tagging# ----------------------------------------------------------------------------def _tag_resource(resource_arn, data):- tags = _tags.setdefault(resource_arn, [])- for tag in data.get("Tags", []):- existing = next((t for t in tags if t["Key"] == tag["Key"]), None)- if existing:- existing["Value"] = tag["Value"]- else:- tags.append(tag)- return json_response({})---def _untag_resource(resource_arn, tag_keys):- _tags[resource_arn] = [t for t in _tags.get(resource_arn, []) if t["Key"] not in tag_keys]- return json_response({})---def _list_tags(resource_arn):- return json_response({"Tags": _tags.get(resource_arn, [])})+def _resource_exists(resource_id):+ return resource_id in _file_systems or resource_id in _access_points+++def _tag_resource(resource_id, data):+ if not _resource_exists(resource_id):+ return _NOT_FOUND(f"Resource {resource_id} not found")+ incoming = data.get("tags")+ if not incoming:+ return _VALIDATION("tags is required")+ existing = _tags.get(resource_id, [])+ by_key = {t["key"]: t for t in existing if "key" in t}+ for t in incoming:+ k = t.get("key")+ if not k:+ continue+ by_key[k] = {"key": k, "value": t.get("value", "")}+ _tags[resource_id] = list(by_key.values())+ return _empty_200()+++def _untag_resource(resource_id, tag_keys):+ if not _resource_exists(resource_id):+ return _NOT_FOUND(f"Resource {resource_id} not found")+ if not tag_keys:+ return _VALIDATION("tagKeys is required")+ existing = _tags.get(resource_id, [])+ _tags[resource_id] = [t for t in existing if t.get("key") not in set(tag_keys)]+ return _empty_200()+++def _list_tags_for_resource(resource_id, query_params):+ if not _resource_exists(resource_id):+ return _NOT_FOUND(f"Resource {resource_id} not found")+ # AWS URI shows both `MaxResults` and `maxResults`; accept either.+ max_results = (+ _qp_int(query_params, "maxResults", None)+ or _qp_int(query_params, "MaxResults", 50)+ or 50+ )+ next_token = _qp_str(query_params, "nextToken") or _qp_str(query_params, "NextToken")+ tags = list(_tags.get(resource_id, []))+ page, nxt = _paginate(tags, max_results, next_token)+ out = {"tags": page}+ if nxt:+ out["nextToken"] = nxt+ return _json(out)diff --git a/tests/test_s3files.py b/tests/test_s3files.pynew file mode 100644index 00000000..9854a734--- /dev/null+++ b/tests/test_s3files.py@@ -0,0 +1,422 @@+"""S3 Files (s3files-2025-05-05) tests.++Driven via raw HTTP since botocore doesn't ship `s3files` in the version+pinned for the rest of the suite. The wire format here is exactly what+the AWS CLI / SDKs send: REST/JSON with camelCase fields and the routes+documented at docs.aws.amazon.com/AmazonS3/.../API_Operations_Amazon_S3_Files.html.+"""++import json+import urllib.error+import urllib.parse+import urllib.request+import uuid+++ENDPOINT = "http://localhost:4566"+BUCKET_ARN = "arn:aws:s3:::test-bucket"+ROLE_ARN = "arn:aws:iam::000000000000:role/s3files-role"+++def _auth(account="000000000000"):+ return (+ f"AWS4-HMAC-SHA256 "+ f"Credential={account}/20260504/us-east-1/s3files/aws4_request, "+ f"SignedHeaders=host, Signature=00"+ )+++_AUTH = _auth()+++def _req(method, path, body=None, query=None, account=None):+ url = ENDPOINT + path+ if query:+ url += "?" + urllib.parse.urlencode(query, doseq=True)+ data = None+ headers = {"Authorization": _auth(account) if account else _AUTH}+ if body is not None:+ data = json.dumps(body).encode()+ headers["Content-Type"] = "application/json"+ req = urllib.request.Request(url, data=data, headers=headers, method=method)+ try:+ resp = urllib.request.urlopen(req, timeout=10)+ raw = resp.read()+ return resp.status, json.loads(raw) if raw else {}+ except urllib.error.HTTPError as e:+ raw = e.read()+ try:+ return e.code, json.loads(raw)+ except Exception:+ return e.code, {"raw": raw.decode("latin-1", "replace")}+++def _uid():+ return uuid.uuid4().hex[:6]+++# ---------------------------------------------------------------------------+# File systems+# ---------------------------------------------------------------------------++def test_create_file_system_uses_put_and_camel_case():+ status, body = _req("PUT", "/file-systems", {+ "bucket": BUCKET_ARN,+ "roleArn": ROLE_ARN,+ "tags": [{"key": "Name", "value": f"fs-{_uid()}"}],+ })+ assert status == 201, body+ assert body["fileSystemId"].startswith("fs-")+ assert body["fileSystemArn"].startswith("arn:aws:s3files:")+ assert body["bucket"] == BUCKET_ARN+ assert body["roleArn"] == ROLE_ARN+ assert body["status"] == "available"+ assert isinstance(body["creationTime"], int)+ assert body["ownerId"] == "000000000000"+ fs_id = body["fileSystemId"]+ _req("DELETE", f"/file-systems/{fs_id}")+++def test_create_file_system_post_is_not_supported():+ status, body = _req("POST", "/file-systems", {+ "bucket": BUCKET_ARN,+ "roleArn": ROLE_ARN,+ })+ assert status == 400+ assert body.get("__type") == "ValidationException"+++def test_create_file_system_missing_required_fields():+ status, body = _req("PUT", "/file-systems", {})+ assert status == 400+ assert body.get("__type") == "ValidationException"+++def test_get_and_list_file_systems_camel_case():+ s, body = _req("PUT", "/file-systems", {"bucket": BUCKET_ARN, "roleArn": ROLE_ARN})+ fs_id = body["fileSystemId"]+ try:+ s, got = _req("GET", f"/file-systems/{fs_id}")+ assert s == 200+ assert got["fileSystemId"] == fs_id+ assert got["bucket"] == BUCKET_ARN++ s, listed = _req("GET", "/file-systems")+ assert s == 200+ assert any(fs["fileSystemId"] == fs_id for fs in listed["fileSystems"])++ s, filtered = _req("GET", "/file-systems", query={"bucket": BUCKET_ARN})+ assert s == 200+ assert all(fs["bucket"] == BUCKET_ARN for fs in filtered["fileSystems"])+ finally:+ _req("DELETE", f"/file-systems/{fs_id}")+++def test_get_file_system_not_found():+ s, body = _req("GET", "/file-systems/fs-deadbeefdeadbeefdead")+ assert s == 404+ assert body.get("__type") == "ResourceNotFoundException"+++def test_delete_file_system_returns_204():+ s, body = _req("PUT", "/file-systems", {"bucket": BUCKET_ARN, "roleArn": ROLE_ARN})+ fs_id = body["fileSystemId"]+ s, _ = _req("DELETE", f"/file-systems/{fs_id}")+ assert s == 204+++# ---------------------------------------------------------------------------+# Mount targets+# ---------------------------------------------------------------------------++def test_mount_target_lifecycle():+ s, fs = _req("PUT", "/file-systems", {"bucket": BUCKET_ARN, "roleArn": ROLE_ARN})+ fs_id = fs["fileSystemId"]+ try:+ s, mt = _req("PUT", "/mount-targets", {+ "fileSystemId": fs_id,+ "subnetId": "subnet-12345678",+ "securityGroups": ["sg-12345678"],+ })+ assert s == 200+ assert mt["mountTargetId"].startswith("fsmt-")+ assert mt["fileSystemId"] == fs_id+ assert mt["securityGroups"] == ["sg-12345678"]+ mt_id = mt["mountTargetId"]++ s, got = _req("GET", f"/mount-targets/{mt_id}")+ assert s == 200 and got["mountTargetId"] == mt_id++ s, listed = _req("GET", "/mount-targets", query={"fileSystemId": fs_id})+ assert s == 200+ assert any(m["mountTargetId"] == mt_id for m in listed["mountTargets"])++ s, updated = _req("PUT", f"/mount-targets/{mt_id}", {+ "securityGroups": ["sg-aaaaaaaa", "sg-bbbbbbbb"],+ })+ assert s == 200+ assert updated["securityGroups"] == ["sg-aaaaaaaa", "sg-bbbbbbbb"]++ s, _ = _req("DELETE", f"/mount-targets/{mt_id}")+ assert s == 204+ finally:+ _req("DELETE", f"/file-systems/{fs_id}")+++def test_create_mount_target_requires_filesystem():+ s, body = _req("PUT", "/mount-targets", {"subnetId": "subnet-12345678"})+ assert s == 400+ assert body.get("__type") == "ValidationException"+++def test_update_mount_target_requires_security_groups():+ s, fs = _req("PUT", "/file-systems", {"bucket": BUCKET_ARN, "roleArn": ROLE_ARN})+ fs_id = fs["fileSystemId"]+ try:+ s, mt = _req("PUT", "/mount-targets", {+ "fileSystemId": fs_id,+ "subnetId": "subnet-12345678",+ })+ s, body = _req("PUT", f"/mount-targets/{mt['mountTargetId']}", {})+ assert s == 400+ assert body.get("__type") == "ValidationException"+ finally:+ _req("DELETE", f"/file-systems/{fs_id}")+++# ---------------------------------------------------------------------------+# Access points+# ---------------------------------------------------------------------------++def test_access_point_lifecycle():+ s, fs = _req("PUT", "/file-systems", {"bucket": BUCKET_ARN, "roleArn": ROLE_ARN})+ fs_id = fs["fileSystemId"]+ try:+ s, ap = _req("PUT", "/access-points", {+ "fileSystemId": fs_id,+ "posixUser": {"uid": 1000, "gid": 1000},+ "rootDirectory": {"path": "/data"},+ "tags": [{"key": "Name", "value": "ap-test"}],+ })+ assert s == 200+ assert ap["accessPointId"].startswith("fsap-")+ assert ap["fileSystemId"] == fs_id+ assert ap["accessPointArn"].startswith(f"arn:aws:s3files:")+ assert "/access-point/" in ap["accessPointArn"]+ assert ap["name"] == "ap-test"++ s, listed = _req("GET", "/access-points", query={"fileSystemId": fs_id})+ assert s == 200+ assert any(a["accessPointId"] == ap["accessPointId"] for a in listed["accessPoints"])++ s, _ = _req("DELETE", f"/access-points/{ap['accessPointId']}")+ assert s == 204+ finally:+ _req("DELETE", f"/file-systems/{fs_id}")+++def test_list_access_points_requires_filesystem_id():+ s, body = _req("GET", "/access-points")+ assert s == 400+ assert body.get("__type") == "ValidationException"+++# ---------------------------------------------------------------------------+# File-system policy+# ---------------------------------------------------------------------------++def test_file_system_policy_lifecycle():+ s, fs = _req("PUT", "/file-systems", {"bucket": BUCKET_ARN, "roleArn": ROLE_ARN})+ fs_id = fs["fileSystemId"]+ try:+ policy_doc = json.dumps({"Version": "2012-10-17", "Statement": []})+ s, _ = _req("PUT", f"/file-systems/{fs_id}/policy", {"policy": policy_doc})+ assert s == 200++ s, got = _req("GET", f"/file-systems/{fs_id}/policy")+ assert s == 200+ assert got["fileSystemId"] == fs_id+ assert got["policy"] == policy_doc++ s, _ = _req("DELETE", f"/file-systems/{fs_id}/policy")+ assert s == 204++ s, body = _req("GET", f"/file-systems/{fs_id}/policy")+ assert s == 404+ finally:+ _req("DELETE", f"/file-systems/{fs_id}")+++# ---------------------------------------------------------------------------+# Synchronization configuration+# ---------------------------------------------------------------------------++def test_synchronization_configuration_lifecycle_and_optimistic_locking():+ s, fs = _req("PUT", "/file-systems", {"bucket": BUCKET_ARN, "roleArn": ROLE_ARN})+ fs_id = fs["fileSystemId"]+ try:+ s, _ = _req("PUT", f"/file-systems/{fs_id}/synchronization-configuration", {+ "expirationDataRules": [{"daysAfterLastAccess": 7}],+ "importDataRules": [{"prefix": "", "trigger": "NEW_OBJECTS"}],+ })+ assert s == 200++ s, got = _req("GET", f"/file-systems/{fs_id}/synchronization-configuration")+ assert s == 200+ assert got["latestVersionNumber"] == 1+ assert got["expirationDataRules"][0]["daysAfterLastAccess"] == 7++ # stale version → 409+ s, body = _req("PUT", f"/file-systems/{fs_id}/synchronization-configuration", {+ "expirationDataRules": [{"daysAfterLastAccess": 14}],+ "importDataRules": [{"prefix": "", "trigger": "NEW_OBJECTS"}],+ "latestVersionNumber": 99,+ })+ assert s == 409+ assert body.get("__type") == "ConflictException"++ # correct version → 200, bump+ s, _ = _req("PUT", f"/file-systems/{fs_id}/synchronization-configuration", {+ "expirationDataRules": [{"daysAfterLastAccess": 14}],+ "importDataRules": [{"prefix": "", "trigger": "NEW_OBJECTS"}],+ "latestVersionNumber": 1,+ })+ assert s == 200+ s, got = _req("GET", f"/file-systems/{fs_id}/synchronization-configuration")+ assert got["latestVersionNumber"] == 2+ finally:+ _req("DELETE", f"/file-systems/{fs_id}")+++# ---------------------------------------------------------------------------+# Tagging+# ---------------------------------------------------------------------------++def test_resource_tags_lifecycle_uses_resource_tags_path():+ s, fs = _req("PUT", "/file-systems", {"bucket": BUCKET_ARN, "roleArn": ROLE_ARN})+ fs_id = fs["fileSystemId"]+ try:+ s, _ = _req("POST", f"/resource-tags/{fs_id}", {+ "tags": [{"key": "Env", "value": "test"}, {"key": "Owner", "value": "ministack"}],+ })+ assert s == 200++ s, listed = _req("GET", f"/resource-tags/{fs_id}")+ assert s == 200+ tags = {t["key"]: t["value"] for t in listed["tags"]}+ assert tags == {"Env": "test", "Owner": "ministack"}++ s, _ = _req("DELETE", f"/resource-tags/{fs_id}", query={"tagKeys": ["Env"]})+ assert s == 200++ s, listed = _req("GET", f"/resource-tags/{fs_id}")+ assert {t["key"] for t in listed["tags"]} == {"Owner"}+ finally:+ _req("DELETE", f"/file-systems/{fs_id}")+++def test_tag_unknown_resource_returns_404():+ s, body = _req("POST", "/resource-tags/fs-deadbeefdeadbeefdead", {+ "tags": [{"key": "k", "value": "v"}],+ })+ assert s == 404+ assert body.get("__type") == "ResourceNotFoundException"+++# ---------------------------------------------------------------------------+# Multi-tenancy+# ---------------------------------------------------------------------------++def test_account_isolation_for_file_systems():+ a, b = "111111111111", "222222222222"+ s, fs = _req("PUT", "/file-systems",+ {"bucket": BUCKET_ARN, "roleArn": ROLE_ARN}, account=a)+ fs_id = fs["fileSystemId"]+ try:+ s, listed_a = _req("GET", "/file-systems", account=a)+ s, listed_b = _req("GET", "/file-systems", account=b)+ ids_a = {f["fileSystemId"] for f in listed_a["fileSystems"]}+ ids_b = {f["fileSystemId"] for f in listed_b["fileSystems"]}+ assert fs_id in ids_a+ assert fs_id not in ids_b++ s, body = _req("GET", f"/file-systems/{fs_id}", account=b)+ assert s == 404+ assert body.get("__type") == "ResourceNotFoundException"++ s, body = _req("DELETE", f"/file-systems/{fs_id}", account=b)+ assert s == 404+ finally:+ _req("DELETE", f"/file-systems/{fs_id}", account=a)+++# ---------------------------------------------------------------------------+# Pagination+# ---------------------------------------------------------------------------++def test_list_file_systems_pagination_walks_all_items():+ created = []+ try:+ for _ in range(7):+ _, fs = _req("PUT", "/file-systems",+ {"bucket": BUCKET_ARN, "roleArn": ROLE_ARN})+ created.append(fs["fileSystemId"])++ seen = []+ token = None+ for _ in range(10): # safety bound; real loop terminates by None+ q = {"maxResults": 3}+ if token:+ q["nextToken"] = token+ s, page = _req("GET", "/file-systems", query=q)+ assert s == 200+ assert len(page["fileSystems"]) <= 3+ seen.extend(f["fileSystemId"] for f in page["fileSystems"])+ token = page.get("nextToken")+ if not token:+ break+ else:+ raise AssertionError("pagination did not terminate")++ assert set(created).issubset(set(seen))+ # No duplicates across pages.+ assert len(seen) == len(set(seen))+ finally:+ for fs_id in created:+ _req("DELETE", f"/file-systems/{fs_id}")+++# ---------------------------------------------------------------------------+# ARN-form resourceId acceptance+# ---------------------------------------------------------------------------++def test_body_parameter_accepts_full_arn_form():+ """AWS shapes accept either a bare ID (`fs-xxx`) or a full ARN for+ `fileSystemId` request fields. Verify the ARN form is normalized so+ downstream lookups match the bare-ID storage key.++ Path-parameter ARNs are not exercised: ASGI delivers the path already+ URL-decoded, which collides with the `/` inside the ARN. Real SDKs+ typically pass the bare ID in the URI and only use the ARN form in the+ JSON body, which is the case covered here.+ """+ s, fs = _req("PUT", "/file-systems", {"bucket": BUCKET_ARN, "roleArn": ROLE_ARN})+ fs_id = fs["fileSystemId"]+ fs_arn = fs["fileSystemArn"]+ try:+ # CreateMountTarget with the ARN form of fileSystemId.+ s, mt = _req("PUT", "/mount-targets", {+ "fileSystemId": fs_arn,+ "subnetId": "subnet-12345678",+ })+ assert s == 200, mt+ assert mt["fileSystemId"] == fs_id # normalized back to bare ID+ _req("DELETE", f"/mount-targets/{mt['mountTargetId']}")++ # CreateAccessPoint with the ARN form too.+ s, ap = _req("PUT", "/access-points", {"fileSystemId": fs_arn})+ assert s == 200, ap+ assert ap["fileSystemId"] == fs_id+ _req("DELETE", f"/access-points/{ap['accessPointId']}")+ finally:+ _req("DELETE", f"/file-systems/{fs_id}")