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/iam cfn s3 glacier (#1479)
Nahuel Nucerab4265eb25d29
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 40d589dd..0818d8e9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **IAM — a CloudFormation-provisioned policy no longer breaks the read APIs** — `AWS::IAM::Role` with `ManagedPolicyArns`, and both policy resource types, wrote records the IAM API never produced: `AttachedPolicies` held `{PolicyName, PolicyArn}` dicts where every reader expects a bare ARN, so `GetAccountAuthorizationDetails` and `ListAttachedRolePolicies` answered 500 (`unhashable type: 'dict'`) and `ListEntitiesForPolicy` never matched; and `Versions` was a list rather than a dict keyed by version id, so `GetPolicyVersion` and `ListPolicyVersions` failed on any policy a stack created. Policies and attachments now go through the IAM module itself, so one shape reaches every reader and `AttachmentCount` tracks stack-created attachments as it does API ones. `AWS::IAM::ManagedPolicy` also honours its documented `Roles`, `Users` and `Groups` properties, which it previously ignored, and both resource types return the attributes CloudFormation documents — the eight on `ManagedPolicy`, `Id` on `Policy` — instead of answering the physical id for every `Fn::GetAtt`. `Ref` on `AWS::IAM::Policy` returns the policy name, matching AWS. `GetAccountAuthorizationDetails` now also lists an attached policy whose document it cannot read, agreeing with `ListAttachedRolePolicies` rather than silently dropping the row. Reported by @iot-rocket.- **Lambda — Node.js ESM handlers using top-level `await` load correctly** — the warm-worker and one-shot Node bootstraps `require()` the handler module and fall back to dynamic `import()` only on `ERR_REQUIRE_ESM`; a module whose graph contains a top-level `await` instead throws Node's `ERR_REQUIRE_ASYNC_MODULE` (since a synchronous `require()` can never wait on an async operation), which fell through to an uncaught `RuntimeError`. Both bootstraps now treat `ERR_REQUIRE_ASYNC_MODULE` the same as `ERR_REQUIRE_ESM`. This is AWS's own documented Lambda cold-start pattern (a module-scope `await` to force a client connection during Init, before the first invocation) and works unmodified on real Lambda already. Contributed by @ryan-bennett.- **Cognito — `ListUsers` `Filter` matches values case-insensitively, except where AWS documents otherwise** — every filter comparison was an exact string match, so `email = "[email protected]"` missed a profile stored as `[email protected]` and a `^=` prefix search was equally literal. Values are now matched case-insensitively for `email`, `phone_number`, `name`, `given_name`, `family_name`, `preferred_username` and `sub`, while `username` and `status` stay case-sensitive as the `ListUsers` API reference specifies. Contributed by @ppettitau.- **DynamoDB — an `UpdateExpression` alias is resolved before the key-attribute check** — `set #pk = :pk` with `#pk` mapped to a non-key attribute was refused with `Cannot update attribute pk. This attribute is part of the key`, because the check matched the key name as raw text inside the `#pk` alias and the `:pk` value reference. It now reads the alias-resolved attribute roots the update evaluator already reports, so only a path that resolves to the partition or sort key is rejected. Reported by @ppettitau.diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex e98153c1..55e9c869 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -165,6 +165,7 @@ _S3_QUERY_ACTIONS: dict[str, dict[str, str]] = {"DELETE": "DeleteReplicationConfiguration"},"location": {"GET": "GetBucketLocation"},"uploads": {"GET": "ListMultipartUploads", "POST": "CreateMultipartUpload"},+ "restore": {"POST": "RestoreObject"},}diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 45bc2436..19c74ded 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -990,13 +990,13 @@ def _iam_role_create(logical_id, props, stack_name):"Tags": [],}- # ManagedPolicyArns- managed = props.get("ManagedPolicyArns", [])- for policy_arn in managed:- role["AttachedPolicies"].append({- "PolicyName": policy_arn.split("/")[-1],- "PolicyArn": policy_arn,- })+ # ManagedPolicyArns. Attach through the IAM module so the record carries the+ # bare ARN every reader expects and AttachmentCount tracks, exactly as+ # AttachRolePolicy would: a dict here made GetAccountAuthorizationDetails+ # and ListAttachedRolePolicies fail on _policies.get(<dict>), and left the+ # attachment invisible to ListEntitiesForPolicy.+ for policy_arn in props.get("ManagedPolicyArns", []):+ _iam.attach_managed_policy(role, policy_arn)# Inline Policiespolicies = props.get("Policies", [])@@ -1022,6 +1022,22 @@ def _iam_role_delete(physical_id, props):# --- IAM Policy ---+def _attach_policy_to_entities(arn, props):+ """Attach a CFN-created policy to the Roles / Users / Groups it names.++ Both AWS::IAM::Policy and AWS::IAM::ManagedPolicy carry these three+ properties. Attaching through the IAM module keeps AttachedPolicies a list+ of bare ARNs and AttachmentCount in step, exactly as AttachRolePolicy does.+ """+ for prop, store in (("Roles", _iam._roles),+ ("Users", _iam._users),+ ("Groups", _iam._groups)):+ for entity_name in props.get(prop, []) or []:+ entity = store.get(entity_name)+ if entity is not None:+ _iam.attach_managed_policy(entity, arn)++def _iam_policy_create(logical_id, props, stack_name):name = props.get("PolicyName") or _physical_name(stack_name, logical_id, max_len=128)path = props.get("Path", "/")@@ -1030,43 +1046,27 @@ def _iam_policy_create(logical_id, props, stack_name):if isinstance(pol_doc, dict):pol_doc = json.dumps(pol_doc)- policy = {- "PolicyName": name,- "PolicyId": new_uuid().replace("-", "")[:21].upper(),- "Arn": arn,- "Path": path,- "DefaultVersionId": "v1",- "AttachmentCount": 0,- "IsAttachable": True,- "CreateDate": now_iso(),- "UpdateDate": now_iso(),- "Description": props.get("Description", ""),- "Versions": [{- "VersionId": "v1",- "IsDefaultVersion": True,- "Document": pol_doc,- "CreateDate": now_iso(),- }],- "Tags": [],- }- _iam._policies[arn] = policy-- # Attach to roles if Roles property specified- roles = props.get("Roles", [])- for role_name in roles:- role = _iam._roles.get(role_name)- if role:- role["AttachedPolicies"].append({- "PolicyName": name,- "PolicyArn": arn,- })- policy["AttachmentCount"] += 1-- return arn, {"PolicyArn": arn}+ record = _iam.store_policy(arn, name, path, pol_doc,+ description=props.get("Description", ""))+ _attach_policy_to_entities(arn, props)+ # "When the logical ID of this resource is provided to the Ref intrinsic+ # function, Ref returns the resource name" — so the physical id is the+ # policy name, not the ARN, and _iam_policy_delete resolves back from it.+ # AWS::IAM::Policy exposes exactly one attribute, Id; anything else falls+ # through to the engine's PhysicalResourceId fallback.+ return name, {"Id": record["PolicyId"]}def _iam_policy_delete(physical_id, props):- _iam._policies.pop(physical_id, None)+ # The physical id is the policy name (what Ref returns), so find the record+ # by name. Older stacks stored the ARN as the physical id; popping that+ # first keeps them deletable.+ if _iam._policies.pop(physical_id, None) is not None:+ return+ for arn, policy in list(_iam._policies.items()):+ if policy.get("PolicyName") == physical_id:+ _iam._policies.pop(arn, None)+ return# --- IAM InstanceProfile ---@@ -3599,22 +3599,24 @@ def _codebuild_project_delete(physical_id, props):def _iam_managed_policy_create(logical_id, props, stack_name):name = props.get("ManagedPolicyName", f"{stack_name}-{logical_id}")+ path = props.get("Path", "/")arn = f"arn:aws:iam::{get_account_id()}:policy/{name}"- policy_doc = props.get("PolicyDocument", {})- _iam._policies[arn] = {- "PolicyName": name,- "PolicyId": new_uuid().replace("-", "")[:21].upper(),- "Arn": arn,- "Path": props.get("Path", "/"),- "DefaultVersionId": "v1",- "AttachmentCount": 0,- "IsAttachable": True,- "Description": props.get("Description", ""),- "CreateDate": __import__("time").strftime("%Y-%m-%dT%H:%M:%SZ", __import__("time").gmtime()),- "UpdateDate": __import__("time").strftime("%Y-%m-%dT%H:%M:%SZ", __import__("time").gmtime()),- "PolicyVersions": [{"Document": json.dumps(policy_doc) if isinstance(policy_doc, dict) else policy_doc, "VersionId": "v1", "IsDefaultVersion": True}],+ record = _iam.store_policy(arn, name, path, props.get("PolicyDocument", {}),+ description=props.get("Description", ""))+ _attach_policy_to_entities(arn, props)+ # The eight attributes AWS::IAM::ManagedPolicy documents. Attachments are+ # counted after _attach_policy_to_entities has run, so AttachmentCount+ # reflects the Roles / Users / Groups this same resource named.+ return arn, {+ "PolicyArn": arn,+ "PolicyId": record["PolicyId"],+ "AttachmentCount": record["AttachmentCount"],+ "PermissionsBoundaryUsageCount": 0,+ "DefaultVersionId": record["DefaultVersionId"],+ "IsAttachable": record["IsAttachable"],+ "CreateDate": record["CreateDate"],+ "UpdateDate": record["UpdateDate"],}- return arn, {"Arn": arn}def _iam_managed_policy_delete(physical_id, props):diff --git a/ministack/services/iam.py b/ministack/services/iam.pyindex 3c8ca8cf..f446318a 100644--- a/ministack/services/iam.py+++ b/ministack/services/iam.py@@ -622,6 +622,45 @@ def _delete_role_permissions_boundary(p):# -------------------- Managed policy management --------------------+def store_policy(arn: str, name: str, path: str, document, *,+ description: str = "", tags=None) -> dict:+ """Create and store a customer-managed policy record, and return it.++ The record shape is not incidental: ``Versions`` is a dict keyed by version+ id because GetPolicyVersion, CreatePolicyVersion, DeletePolicyVersion and+ ListPolicyVersions all index it that way. Writers outside this module (the+ CloudFormation provisioners) build policies through here rather than+ assembling the dict themselves, which is what keeps those four operations+ working on a CFN-created policy.+ """+ version_id = "v1"+ if not isinstance(document, str):+ document = json.dumps(document)+ record = {+ "PolicyName": name,+ "Arn": arn,+ "PolicyId": _gen_id("ANPA"),+ "CreateDate": _now(),+ "UpdateDate": _now(),+ "DefaultVersionId": version_id,+ "AttachmentCount": 0,+ "IsAttachable": True,+ "Path": path,+ "Description": description,+ "Tags": list(tags or []),+ "Versions": {+ version_id: {+ "Document": document,+ "VersionId": version_id,+ "IsDefaultVersion": True,+ "CreateDate": _now(),+ }+ },+ }+ _policies[arn] = record+ return record++def _create_policy(p):name = _p(p, "PolicyName")path = _p(p, "Path") or "/"@@ -641,29 +680,7 @@ def _create_policy(p):description = _p(p, "Description", "")# #445 (follow-up): CreatePolicy accepts Tags — honour them on create.create_tags = _extract_tags(p)- policy_id = _gen_id("ANPA")- version_id = "v1"- _policies[arn] = {- "PolicyName": name,- "Arn": arn,- "PolicyId": policy_id,- "CreateDate": _now(),- "UpdateDate": _now(),- "DefaultVersionId": version_id,- "AttachmentCount": 0,- "IsAttachable": True,- "Path": path,- "Description": description,- "Tags": list(create_tags or []),- "Versions": {- version_id: {- "Document": doc,- "VersionId": version_id,- "IsDefaultVersion": True,- "CreateDate": _now(),- }- },- }+ store_policy(arn, name, path, doc, description=description, tags=create_tags)return _xml(200, "CreatePolicyResponse",f"<CreatePolicyResult><Policy>{_managed_policy_xml(arn)}</Policy></CreatePolicyResult>",ns="iam")@@ -865,6 +882,28 @@ def _list_entities_for_policy(p):# -------------------- Attached role policies --------------------+def attach_managed_policy(entity: dict, policy_arn: str) -> None:+ """Attach a managed policy to a role, user or group record.++ ``AttachedPolicies`` holds bare ARN strings. Every consumer reads it that+ way — GetAccountAuthorizationDetails and ListAttachedRolePolicies feed the+ entries to _lookup_policy, and ListEntitiesForPolicy tests membership with+ ``arn in ...`` — so a writer that stores anything else breaks all three.+ Callers outside this module (the CloudFormation provisioner) go through+ here rather than appending themselves, which is also what keeps+ AttachmentCount in step with the API path.+ """+ if policy_arn in entity.setdefault("AttachedPolicies", []):+ return+ entity["AttachedPolicies"].append(policy_arn)+ if _is_aws_managed_arn(policy_arn):+ _bump_aws_managed_attachment(policy_arn, +1)+ else:+ pol = _policies.get(policy_arn)+ if pol:+ pol["AttachmentCount"] = pol.get("AttachmentCount", 0) + 1++def _attach_role_policy(p):role_name = _p(p, "RoleName")policy_arn = _p(p, "PolicyArn")@@ -872,14 +911,7 @@ def _attach_role_policy(p):if not role:return _error(404, "NoSuchEntity",f"Role {role_name} not found.", ns="iam")- if policy_arn not in role["AttachedPolicies"]:- role["AttachedPolicies"].append(policy_arn)- if _is_aws_managed_arn(policy_arn):- _bump_aws_managed_attachment(policy_arn, +1)- else:- pol = _policies.get(policy_arn)- if pol:- pol["AttachmentCount"] = pol.get("AttachmentCount", 0) + 1+ attach_managed_policy(role, policy_arn)return _xml(200, "AttachRolePolicyResponse", "", ns="iam")@@ -1947,12 +1979,16 @@ def _get_account_authorization_details(p):# Attached managed policiesattached_xml = ""for arn in user.get("AttachedPolicies", []):+ # The attachment is reported whether or not the policy document+ # is readable here: AWS lists it either way, and an unseeded+ # AWS-managed ARN has no local record unless autovivify is on.+ # Same fallback ListAttachedRolePolicies already uses.pol = _lookup_policy(arn)- if pol:- attached_xml += (f"<member>"- f"<PolicyName>{pol['PolicyName']}</PolicyName>"- f"<PolicyArn>{arn}</PolicyArn>"- f"</member>")+ pname = pol["PolicyName"] if pol else arn.rsplit("/", 1)[-1]+ attached_xml += (f"<member>"+ f"<PolicyName>{pname}</PolicyName>"+ f"<PolicyArn>{arn}</PolicyArn>"+ f"</member>")# Groups the user belongs togroup_xml = "".join(f"<member>{g['GroupName']}</member>"@@ -1994,12 +2030,16 @@ def _get_account_authorization_details(p):# Attached managed policiesattached_xml = ""for arn in g.get("AttachedPolicies", []):+ # The attachment is reported whether or not the policy document+ # is readable here: AWS lists it either way, and an unseeded+ # AWS-managed ARN has no local record unless autovivify is on.+ # Same fallback ListAttachedRolePolicies already uses.pol = _lookup_policy(arn)- if pol:- attached_xml += (f"<member>"- f"<PolicyName>{pol['PolicyName']}</PolicyName>"- f"<PolicyArn>{arn}</PolicyArn>"- f"</member>")+ pname = pol["PolicyName"] if pol else arn.rsplit("/", 1)[-1]+ attached_xml += (f"<member>"+ f"<PolicyName>{pname}</PolicyName>"+ f"<PolicyArn>{arn}</PolicyArn>"+ f"</member>")group_detail_xml += (f"<member>"f"<GroupName>{g['GroupName']}</GroupName>"@@ -2028,12 +2068,16 @@ def _get_account_authorization_details(p):# Attached managed policiesattached_xml = ""for arn in role.get("AttachedPolicies", []):+ # The attachment is reported whether or not the policy document+ # is readable here: AWS lists it either way, and an unseeded+ # AWS-managed ARN has no local record unless autovivify is on.+ # Same fallback ListAttachedRolePolicies already uses.pol = _lookup_policy(arn)- if pol:- attached_xml += (f"<member>"- f"<PolicyName>{pol['PolicyName']}</PolicyName>"- f"<PolicyArn>{arn}</PolicyArn>"- f"</member>")+ pname = pol["PolicyName"] if pol else arn.rsplit("/", 1)[-1]+ attached_xml += (f"<member>"+ f"<PolicyName>{pname}</PolicyName>"+ f"<PolicyArn>{arn}</PolicyArn>"+ f"</member>")# Instance profilesip_xml = "".join(f"<member>{_instance_profile_xml(ipn)}</member>"diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex a6220a43..803f39be 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -56,6 +56,7 @@ from ministack.core.responses import (md5_hash,new_uuid,now_iso,+ set_request_account_id,set_request_region,)@@ -201,6 +202,251 @@ def _resolve_storage_class(headers: dict, default: str = "STANDARD"):return sc, None+# ---------------------------------------------------------------------------+# Glacier restore (RestoreObject, x-amz-restore, s3:ObjectRestore:* events)+# ---------------------------------------------------------------------------++# Storage classes whose objects are unreadable until restored. GLACIER_IR is+# deliberately absent: instant retrieval is an active tier, readable directly,+# and RestoreObject against it fails ObjectAlreadyInActiveTierError like any+# other active class.+_ARCHIVE_STORAGE_CLASSES = frozenset({"GLACIER", "DEEP_ARCHIVE"})++# Simulated retrieval latency. Fixed on purpose: every caller passes through+# the ongoing-request="true" state it must handle against real AWS, and the+# emulator compresses Glacier's hours to the same few seconds for everyone.+_RESTORE_DELAY_SECONDS = 2.0+++def _restore_expiry_epoch(start: float, days: int) -> float:+ """AWS expires the temporary copy at midnight UTC after the restore+ period (expiry-date always reads 00:00:00 GMT), not at an hour offset."""+ return float((int(start + days * 86400) // 86400 + 1) * 86400)+++def _restore_expiry_iso(expires_at: float) -> str:+ return _dt.datetime.fromtimestamp(+ expires_at, _dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")+++def _sync_restore(bucket_name: str, key: str, obj: dict | None) -> str | None:+ """Derive the object's restore phase from its timestamps.++ Returns "in_progress", "restored", or None (no active restore). State is+ derived rather than flipped by a timer so it survives a restart under+ S3_PERSIST=1. A lapsed temporary copy reverts the object to archived here,+ on the next touch, and fires s3:ObjectRestore:Delete — an expiry is Days+ out, so it rides this lazy sweep instead of a sleeping thread."""+ restore = (obj or {}).get("restore")+ if not restore:+ return None+ now = time.time()+ if now < restore["available_at"]:+ return "in_progress"+ if now < restore["expires_at"]:+ return "restored"+ obj.pop("restore", None)+ _fire_s3_event_async(bucket_name, key, "s3:ObjectRestore:Delete",+ size=obj.get("size", 0), etag=obj.get("etag", ""))+ return None+++def _invalid_object_state(bucket_name: str, key: str, storage_class: str) -> tuple:+ """403 InvalidObjectState, carrying the StorageClass member the error+ shape models."""+ root = Element("Error")+ SubElement(root, "Code").text = "InvalidObjectState"+ SubElement(root, "Message").text = (+ "The operation is not valid for the object's storage class")+ SubElement(root, "StorageClass").text = storage_class+ SubElement(root, "Resource").text = f"/{bucket_name}/{key}"+ SubElement(root, "RequestId").text = new_uuid()+ return 403, {"Content-Type": "application/xml"}, _xml_body(root)+++def _schedule_restore_completed(bucket_name: str, key: str,+ requested_at: float) -> None:+ """Fire s3:ObjectRestore:Completed once the simulated retrieval lands.++ Same copied-context daemon-thread shape as _fire_s3_event_async (#876).+ The requested_at stamp guards the sleep window: if the object is deleted,+ overwritten, or the restore superseded meanwhile, the timer wakes up,+ sees a different stamp, and fires nothing."""+ ctx = contextvars.copy_context()++ def _worker():+ bucket = _buckets.get(bucket_name)+ obj = bucket["objects"].get(key) if bucket else None+ restore = (obj or {}).get("restore")+ if not restore or restore.get("requested_at") != requested_at:+ return+ delay = restore["available_at"] - time.time()+ if delay > 0:+ time.sleep(delay)+ bucket = _buckets.get(bucket_name)+ obj = bucket["objects"].get(key) if bucket else None+ restore = (obj or {}).get("restore")+ if not restore or restore.get("requested_at") != requested_at:+ return+ restore["completed_fired"] = True+ _fire_s3_event(+ bucket_name, key, "s3:ObjectRestore:Completed",+ size=obj.get("size", 0), etag=obj.get("etag", ""),+ restore_event_data={+ "lifecycleRestorationExpiryTime":+ _restore_expiry_iso(restore["expires_at"]),+ "lifecycleRestoreStorageClass":+ obj.get("storage_class") or "GLACIER",+ })++ t = threading.Thread(target=ctx.run, args=(_worker,), daemon=True)+ t.start()+++def _schedule_restore_expiry(bucket_name: str, key: str,+ expires_at: float) -> None:+ """Fire s3:ObjectRestore:Delete when the temporary copy lapses.++ Real S3 removes the restored copy and emits the event at expiry time, not+ on the next read, so a non-polling consumer still hears it. The expires_at+ stamp guards the sleep: an extension re-arms a new timer and the stale one+ wakes, sees a different stamp, and exits. The lazy check in _sync_restore+ stays as a belt-and-braces path for reads that race the timer."""+ ctx = contextvars.copy_context()++ def _worker():+ delay = expires_at - time.time()+ if delay > 0:+ time.sleep(delay)+ bucket = _buckets.get(bucket_name)+ obj = bucket["objects"].get(key) if bucket else None+ restore = (obj or {}).get("restore")+ if not restore or restore.get("expires_at") != expires_at:+ return+ _sync_restore(bucket_name, key, obj)++ t = threading.Thread(target=ctx.run, args=(_worker,), daemon=True)+ t.start()+++def _restore_object(bucket_name: str, key: str, body: bytes) -> tuple:+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _no_such_bucket(bucket_name)+ obj = bucket["objects"].get(key)+ if obj is None:+ return _error("NoSuchKey", "The specified key does not exist.",+ 404, f"/{bucket_name}/{key}")++ sc = obj.get("storage_class") or "STANDARD"+ if sc == "GLACIER_IR":+ # Real AWS distinguishes instant retrieval from active tiers here:+ # restore on GLACIER_IR fails InvalidObjectState ("Restore is not+ # allowed..."), not ObjectAlreadyInActiveTierError.+ return _error(+ "InvalidObjectState",+ "Restore is not allowed for the object's current storage class.",+ 403, f"/{bucket_name}/{key}")+ if sc not in _ARCHIVE_STORAGE_CLASSES:+ return _error(+ "ObjectAlreadyInActiveTierError",+ "This action is not allowed against this storage tier.",+ 403, f"/{bucket_name}/{key}")++ days = None+ tier = "Standard"+ if body:+ try:+ root = fromstring(body)+ except ParseError:+ return _error(+ "MalformedXML",+ "The XML you provided was not well-formed or did not "+ "validate against our published schema",+ 400, f"/{bucket_name}/{key}")+ for el in root.iter():+ name = el.tag.rsplit("}", 1)[-1]+ if name == "Days" and el.text:+ try:+ days = int(el.text.strip())+ except ValueError:+ days = None+ elif name == "Tier" and el.text:+ # Covers both GlacierJobParameters/Tier and top-level Tier.+ tier = el.text.strip()+ if days is None:+ # The Days element is required for regular (non-select) restores.+ return _error(+ "MalformedXML",+ "The XML you provided was not well-formed or did not validate "+ "against our published schema",+ 400, f"/{bucket_name}/{key}")++ now = time.time()+ phase = _sync_restore(bucket_name, key, obj)+ if phase == "in_progress":+ return _error("RestoreAlreadyInProgress",+ "Object restore is already in progress.",+ 409, f"/{bucket_name}/{key}")+ if phase == "restored":+ # Re-request while the copy is live: only the expiry moves, relative+ # to now, and AWS answers 200 rather than 202.+ obj["restore"]["expires_at"] = _restore_expiry_epoch(now, days)+ obj["restore"]["days"] = days+ _schedule_restore_expiry(bucket_name, key, obj["restore"]["expires_at"])+ return 200, {}, b""++ obj["restore"] = {+ "requested_at": now,+ "available_at": now + _RESTORE_DELAY_SECONDS,+ "expires_at": _restore_expiry_epoch(now + _RESTORE_DELAY_SECONDS, days),+ "days": days,+ "tier": tier,+ "completed_fired": False,+ }+ _fire_s3_event_async(bucket_name, key, "s3:ObjectRestore:Post",+ size=obj.get("size", 0), etag=obj.get("etag", ""))+ _schedule_restore_completed(bucket_name, key, now)+ _schedule_restore_expiry(bucket_name, key, obj["restore"]["expires_at"])+ return 202, {}, b""+++def _reschedule_restores() -> None:+ """Re-arm pending s3:ObjectRestore:Completed timers after a restart.++ Invoked once at the end of module import, after persisted state loads:+ a restore in flight when the process died fires on schedule, and one that+ landed while the process was down (completed_fired still False) fires+ immediately — the consumer it exists for wasn't polling. A copy that+ lapsed entirely while down is left to the lazy sweep, which fires+ s3:ObjectRestore:Delete on the next touch."""+ try:+ entries = list(_buckets._data.items())+ except Exception:+ return+ now = time.time()+ for (account_id, bucket_name), bucket in entries:+ for key, obj in list((bucket.get("objects") or {}).items()):+ restore = obj.get("restore")+ if not restore:+ continue+ # The workers copy their context at schedule time, so pin the+ # owning account around the calls (#876 shape).+ set_request_account_id(account_id)+ try:+ if now >= restore["expires_at"]:+ # Lapsed while down: revert to archived and fire :Delete.+ _sync_restore(bucket_name, key, obj)+ continue+ if not restore.get("completed_fired"):+ _schedule_restore_completed(bucket_name, key,+ restore["requested_at"])+ _schedule_restore_expiry(bucket_name, key,+ restore["expires_at"])+ finally:+ set_request_account_id("")++# ---------------------------------------------------------------------------# Server-side encryption (SSE-S3 / SSE-KMS / SSE-C)#@@ -1119,6 +1365,16 @@ def _object_response_headers(obj: dict, bucket_name: str = "", key: str = "",if sc != "STANDARD":# AWS omits the header for STANDARD; SDKs default to STANDARD when absent.h["x-amz-storage-class"] = sc+ restore = obj.get("restore")+ if restore:+ now = time.time()+ if now < restore["available_at"]:+ h["x-amz-restore"] = 'ongoing-request="true"'+ elif now < restore["expires_at"]:+ expiry = time.strftime("%a, %d %b %Y %H:%M:%S GMT",+ time.gmtime(restore["expires_at"]))+ h["x-amz-restore"] = (+ f'ongoing-request="false", expiry-date="{expiry}"')if bucket_name and key:retention = _object_retention.get((bucket_name, key))if retention:@@ -1360,6 +1616,8 @@ def _dispatch(return _put_object(bucket, key, body, headers)if method == "POST":+ if "restore" in query_params:+ return _restore_object(bucket, key, body)if "uploads" in query_params:return _create_multipart_upload(bucket, key, headers)if "uploadId" in query_params:@@ -2641,6 +2899,13 @@ _S3_EVENTBRIDGE_DETAIL_TYPE = {"ObjectCreated": "Object Created","ObjectRemoved": "Object Deleted",}+# The restore family is the one family whose events map to distinct+# detail-types (and whose details carry no `reason` field).+_S3_EVENTBRIDGE_EVENT_DETAIL_TYPE = {+ "ObjectRestore:Post": "Object Restore Initiated",+ "ObjectRestore:Completed": "Object Restore Completed",+ "ObjectRestore:Delete": "Object Restore Expired",+}# `reason` reflects the S3 API that produced the event._S3_EVENTBRIDGE_REASON = {"Put": "PutObject",@@ -2651,13 +2916,17 @@ _S3_EVENTBRIDGE_REASON = {}-def _s3_event_to_eventbridge(event_name: str) -> tuple[str, str]:+def _s3_event_to_eventbridge(event_name: str) -> tuple[str, str | None]:"""Map an S3 notification event name (e.g. ``s3:ObjectCreated:Put``) to the EventBridge- ``detail-type`` and ``reason`` Amazon S3 emits. The detail-type is per-family, so any- sub-action of a family collapses to the same type, exactly as real S3 does."""+ ``detail-type`` and ``reason`` Amazon S3 emits. Created/Removed collapse per family+ exactly as real S3 does; the restore events each carry their own detail-type and no+ reason."""parts = event_name.split(":")family = parts[1] if len(parts) > 1 else ""action = parts[2] if len(parts) > 2 else ""+ per_event = _S3_EVENTBRIDGE_EVENT_DETAIL_TYPE.get(f"{family}:{action}")+ if per_event is not None:+ return per_event, Nonedetail_type = _S3_EVENTBRIDGE_DETAIL_TYPE.get(family, "Object Created")reason = _S3_EVENTBRIDGE_REASON.get(action, "DeleteObject" if family == "ObjectRemoved" else "PutObject"@@ -2672,6 +2941,7 @@ def _fire_s3_event(size: int = 0,etag: str = "",deletion_type: str | None = None,+ restore_event_data: dict | None = None,) -> None:"""Build and deliver an S3 event notification. Best-effort — errors are logged."""try:@@ -2719,6 +2989,11 @@ def _fire_s3_event(}],}+ if restore_event_data:+ # glacierEventData appears only on s3:ObjectRestore:Completed.+ event_payload["Records"][0]["glacierEventData"] = {+ "restoreEventData": restore_event_data,+ }for cfg in configs:try:@@ -2758,8 +3033,9 @@ def _fire_s3_event("request-id": request_id,"requester": get_account_id(),"source-ip-address": "127.0.0.1",- "reason": reason,}+ if reason is not None:+ detail["reason"] = reasonif detail_type == "Object Deleted":# AWS always carries a deletion-type on Object Deleted; default to the# unversioned/permanent case unless the caller created a delete marker.@@ -2934,14 +3210,6 @@ def _fire_s3_test_event(bucket_name: str) -> None:logger.exception("S3 test-event fire failed for %s", bucket_name)-def _fire_s3_test_event_async(bucket_name: str) -> None:- """Fire s3:TestEvent in a background thread (non-blocking)."""- # Carry the request's account/region context into the thread (issue #876).- ctx = contextvars.copy_context()- t = threading.Thread(target=ctx.run, args=(_fire_s3_test_event, bucket_name), daemon=True)- t.start()--# ---------------------------------------------------------------------------# Object operations# ---------------------------------------------------------------------------@@ -3335,6 +3603,18 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =sse_gate = _check_sse_read_headers(headers, vobj)if sse_gate is not None:return sse_gate+ vsc = vobj.get("storage_class") or "STANDARD"+ if vsc in _ARCHIVE_STORAGE_CLASSES:+ # Restore state lives on the current object record;+ # noncurrent archived versions are simply unreadable+ # (restore-by-versionId is not implemented).+ cur = bucket["objects"].get(key)+ cur_phase = (+ _sync_restore(bucket_name, key, cur)+ if cur is not None and cur.get("version_id") == version_id+ else None)+ if cur_phase != "restored":+ return _invalid_object_state(bucket_name, key, vsc)resp_headers = _object_response_headers(vobj, bucket_name, key, include_checksums=include_checksums)resp_headers.update(_object_tagging_count_header(bucket_name, key, version_id))@@ -3362,6 +3642,12 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =sse_gate = _check_sse_read_headers(headers, obj)if sse_gate is not None:return sse_gate+ restore_phase = _sync_restore(bucket_name, key, obj)+ sc = obj.get("storage_class") or "STANDARD"+ if sc in _ARCHIVE_STORAGE_CLASSES and restore_phase != "restored":+ # Archived objects are unreadable until a restore lands; HeadObject+ # deliberately keeps working — that asymmetry is how callers poll.+ return _invalid_object_state(bucket_name, key, sc)range_header = headers.get("range", "")# AWS returns whole-object checksums only on full-object responses (HTTP# 200). On a 206 Partial Content reply the bytes are a slice, and a@@ -3584,6 +3870,9 @@ def _head_object(bucket_name: str, key: str, headers: dict | None = None,err_headers.update(_delete_marker_404_headers(bucket_name, key))return status, err_headers, err_bodyobj = bucket["objects"][key]+ # Lazily lapse an expired restore so the x-amz-restore header (and the+ # s3:ObjectRestore:Delete event) reflect reality on the poll path.+ _sync_restore(bucket_name, key, obj)sse_gate = _check_sse_read_headers(headers, obj)if sse_gate is not None:@@ -5992,3 +6281,8 @@ def reset():_object_versions,):d.clear()+++# Re-arm restore-completion timers for state loaded from disk. Must run after+# every function above is defined: the workers resolve _fire_s3_event by name.+_reschedule_restores()diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex fe67053d..c7903a56 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -1005,6 +1005,7 @@ class TestActionExtraction:assert extract_iam_action("s3", "GET", "/", {}, b"", {}) == "s3:ListAllMyBuckets"assert extract_iam_action("s3", "PUT", "/bucket/key", {}, b"", {}) == "s3:PutObject"assert extract_iam_action("s3", "GET", "/bucket", {}, b"", {"versioning": [""]}) == "s3:GetBucketVersioning"+ assert extract_iam_action("s3", "POST", "/bucket/key", {}, b"", {"restore": [""]}) == "s3:RestoreObject"def test_lambda_rest(self):from ministack.core.iam_actions import extract_iam_actiondiff --git a/tests/test_s3.py b/tests/test_s3.pyindex be089446..0d0810c3 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -3268,7 +3268,9 @@ def test_s3_post_object_storage_class(s3):)r = requests.post(post["url"], data=post["fields"], files={"file": ("x", b"x")})assert r.status_code == 204- assert s3.get_object(Bucket="qa-s3-post-sc", Key="cold")["StorageClass"] == "GLACIER"+ # Read the class off HeadObject: a GetObject of an unrestored GLACIER+ # object is exactly the call AWS rejects with InvalidObjectState.+ assert s3.head_object(Bucket="qa-s3-post-sc", Key="cold")["StorageClass"] == "GLACIER"def test_s3_post_object_unquoted_field_names(s3):@@ -5531,3 +5533,114 @@ def test_s3_list_delimiter_next_marker_is_common_prefix(s3):full = s3.list_objects(Bucket=bkt, Delimiter="/")assert [c["Key"] for c in full.get("Contents", [])] == ["asdf"]assert [c["Prefix"] for c in full.get("CommonPrefixes", [])] == ["boo/", "cquux/"]+++# ---------------------------------------------------------------------------+# Glacier restore (RestoreObject / x-amz-restore / s3:ObjectRestore:*)+# ---------------------------------------------------------------------------++def test_s3_restore_object_glacier_flow(s3):+ s3.create_bucket(Bucket="qa-s3-restore")+ s3.put_object(Bucket="qa-s3-restore", Key="cold", Body=b"frozen",+ StorageClass="GLACIER")++ # Archived and unrestored: GetObject fails InvalidObjectState (403,+ # carrying StorageClass); HeadObject keeps working — that asymmetry is+ # how a caller polls for the copy to land.+ with pytest.raises(ClientError) as exc:+ s3.get_object(Bucket="qa-s3-restore", Key="cold")+ assert exc.value.response["Error"]["Code"] == "InvalidObjectState"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403+ assert exc.value.response["Error"]["StorageClass"] == "GLACIER"+ head = s3.head_object(Bucket="qa-s3-restore", Key="cold")+ assert head["StorageClass"] == "GLACIER"+ assert "Restore" not in head++ resp = s3.restore_object(+ Bucket="qa-s3-restore", Key="cold",+ RestoreRequest={"Days": 1, "GlacierJobParameters": {"Tier": "Bulk"}})+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 202+ assert s3.head_object(Bucket="qa-s3-restore", Key="cold")["Restore"] == \+ 'ongoing-request="true"'+ with pytest.raises(ClientError) as exc:+ s3.restore_object(Bucket="qa-s3-restore", Key="cold",+ RestoreRequest={"Days": 1})+ assert exc.value.response["Error"]["Code"] == "RestoreAlreadyInProgress"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409+ with pytest.raises(ClientError):+ s3.get_object(Bucket="qa-s3-restore", Key="cold")++ # After the fixed retrieval window the copy is readable and the header+ # flips to ongoing-request="false" with an expiry-date.+ time.sleep(2.5)+ head = s3.head_object(Bucket="qa-s3-restore", Key="cold")+ assert head["Restore"].startswith('ongoing-request="false", expiry-date="')+ got = s3.get_object(Bucket="qa-s3-restore", Key="cold")+ assert got["Body"].read() == b"frozen"+ assert got["Restore"].startswith('ongoing-request="false"')+ assert got["StorageClass"] == "GLACIER"++ # Re-requesting while the copy is live only extends the expiry: 200.+ resp = s3.restore_object(Bucket="qa-s3-restore", Key="cold",+ RestoreRequest={"Days": 3})+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200+++def test_s3_restore_object_active_tier_rejected(s3):+ s3.create_bucket(Bucket="qa-s3-restore-active")+ s3.put_object(Bucket="qa-s3-restore-active", Key="warm", Body=b"x")+ s3.put_object(Bucket="qa-s3-restore-active", Key="ir", Body=b"y",+ StorageClass="GLACIER_IR")+ # Active tier (STANDARD): ObjectAlreadyInActiveTierError.+ with pytest.raises(ClientError) as exc:+ s3.restore_object(Bucket="qa-s3-restore-active", Key="warm",+ RestoreRequest={"Days": 1})+ assert exc.value.response["Error"]["Code"] == \+ "ObjectAlreadyInActiveTierError"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403+ # GLACIER_IR: real AWS answers InvalidObjectState ("Restore is not+ # allowed for the object's current storage class."), not the+ # active-tier error.+ with pytest.raises(ClientError) as exc:+ s3.restore_object(Bucket="qa-s3-restore-active", Key="ir",+ RestoreRequest={"Days": 1})+ assert exc.value.response["Error"]["Code"] == "InvalidObjectState"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403+ # GLACIER_IR is instant retrieval: readable without any restore.+ got = s3.get_object(Bucket="qa-s3-restore-active", Key="ir")+ assert got["Body"].read() == b"y"+++def test_s3_restore_notifications_to_sqs(s3, sqs):+ s3.create_bucket(Bucket="qa-s3-restore-evt")+ queue_url = sqs.create_queue(QueueName="qa-s3-restore-evt-q")["QueueUrl"]+ queue_arn = sqs.get_queue_attributes(+ QueueUrl=queue_url, AttributeNames=["QueueArn"],+ )["Attributes"]["QueueArn"]+ s3.put_bucket_notification_configuration(+ Bucket="qa-s3-restore-evt",+ NotificationConfiguration={+ "QueueConfigurations": [+ {"QueueArn": queue_arn, "Events": ["s3:ObjectRestore:*"]}],+ },+ )+ s3.put_object(Bucket="qa-s3-restore-evt", Key="cold", Body=b"z",+ StorageClass="DEEP_ARCHIVE")+ s3.restore_object(Bucket="qa-s3-restore-evt", Key="cold",+ RestoreRequest={"Days": 1})+ time.sleep(3)+ msgs = sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=10,+ WaitTimeSeconds=2)+ records = [+ json.loads(m["Body"])["Records"][0]+ for m in msgs.get("Messages", [])+ if "Records" in json.loads(m["Body"])+ ]+ names = {r["eventName"] for r in records}+ assert "ObjectRestore:Post" in names+ assert "ObjectRestore:Completed" in names+ completed = next(r for r in records+ if r["eventName"] == "ObjectRestore:Completed")+ red = completed["glacierEventData"]["restoreEventData"]+ assert red["lifecycleRestoreStorageClass"] == "DEEP_ARCHIVE"+ assert red["lifecycleRestorationExpiryTime"].endswith("Z")