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(aws parity): fixes pre release (#1727)
Nahuel Nucera0da7946612c1
diff --git a/README.md b/README.mdindex 4a97e24d..2dd68232 100644--- a/README.md+++ b/README.md@@ -1139,7 +1139,7 @@ Existing clusters without a recorded creator also need an explicit Access Entry.With `AUTH=false`, neither IAM policies nor Access Entries restrict Kubernetesaccess. The CLI still needs credentials to generate its exec token, but MiniStackdoes not check their secret, registration, or permissions. Restart MiniStack to-change `AUTH`; k3s may retain previous authentication results for up to five minutes.+change `AUTH`; k3s caches authentication results for two minutes, the kube-apiserver default.> **Note:** EKS requires Docker socket access (`-v /var/run/docker.sock:/var/run/docker.sock`) to spawn k3s containers. The k3s image is pulled on first `CreateCluster` call.diff --git a/ministack/app.py b/ministack/app.pyindex 5705366b..901c6c80 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -2172,7 +2172,7 @@ async def _dispatch_service_request(method: str, path: str, headers: dict, body: bytes, query_params: dict, request_id: str):"""Dispatch AWS service requests and Kubernetes TokenReviews."""- if method == "POST" and path.startswith("/eks-auth/"):+ if method == "POST" and path.startswith("/_ministack/eks-auth/"):# TokenReview carries its own credentials; EKS authenticates the token.return await _get_module("eks").handle_request(method, path, headers, body, query_paramsdiff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex f17a37e5..0130603f 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -465,22 +465,7 @@ _BOTOCORE_SERVICE_MAP: dict[str, list[str]] = {_REST_ROUTE_CACHE: dict[str, list[tuple[str, re.Pattern, str, int, dict[str, str]]]] = {}-# A botocore path label is non-greedy ({x}) unless the model marks it greedy-# ({x+}), and the SDK percent-encodes any "/" the value carries so the label-# still matches one segment on the wire. We match against the decoded path the-# ASGI server hands us, where those separators are separators again, so a-# non-greedy label whose value may contain one never matches and the request-# resolves no action at all. An MQTT topic is multi-level by definition, which-# makes iot-data's the case that bites: without this, Publish and-# GetRetainedMessage are not authorized on any topic below the first level.-# Keyed by botocore service name, as _BOTOCORE_SERVICE_MAP's values are.-_GREEDY_URI_LABELS: dict[str, frozenset[str]] = {- "iot-data": frozenset({"topic"}),-}---def _compile_uri(uri_pattern: str,- greedy_labels: frozenset[str] = frozenset()) -> tuple[re.Pattern, int, dict[str, str]]:+def _compile_uri(uri_pattern: str) -> tuple[re.Pattern, int, dict[str, str]]:"""Compile a botocore URI pattern into a regex + specificity score +required query params.@@ -489,9 +474,7 @@ def _compile_uri(uri_pattern: str,(2 literal segments).Query params from the pattern (e.g., ``?mode=import``) are returned- separately for disambiguation. Labels named in ``greedy_labels`` match- across ``/`` as if the model had marked them ``{x+}``; see- ``_GREEDY_URI_LABELS``.+ separately for disambiguation."""required_query: dict[str, str] = {}if "?" in uri_pattern:@@ -518,7 +501,15 @@ def _compile_uri(uri_pattern: str,if seg.startswith("{") and seg.endswith("+}"):regex_parts.append(".+")elif seg.startswith("{") and seg.endswith("}"):- regex_parts.append(".+" if seg[1:-1] in greedy_labels else "[^/]+")+ # Lazy, not single-segment. A botocore label is non-greedy because+ # the SDK percent-encodes any "/" the value carries, so it stays one+ # segment on the wire; we match the decoded path, where those are+ # separators again. Every ARN-valued label is in this position, as+ # is an MQTT topic, so "[^/]+" resolves no action at all and the+ # request authorizes against "*". The pattern is anchored and the+ # literal segments around a label still bound it, and a route with+ # more literals outscores one with fewer.+ regex_parts.append(".+?")else:regex_parts.append(re.escape(seg))specificity += 1@@ -565,7 +556,6 @@ def _load_botocore_routes(botocore_service: str) -> list[tuple[str, re.Pattern,logger.debug("AUTH: failed to load botocore model for %s", botocore_service)return []- greedy_labels = _GREEDY_URI_LABELS.get(botocore_service, frozenset())routes = []for op_name, op_def in model.get("operations", {}).items():http = op_def.get("http", {})@@ -573,7 +563,7 @@ def _load_botocore_routes(botocore_service: str) -> list[tuple[str, re.Pattern,uri = http.get("requestUri", "")if not method or not uri:continue- compiled, specificity, required_query = _compile_uri(uri, greedy_labels)+ compiled, specificity, required_query = _compile_uri(uri)# Operations with required query params get a specificity boostif required_query:specificity += len(required_query)diff --git a/ministack/services/appsync_events.py b/ministack/services/appsync_events.pyindex be8b9fb3..7f35d824 100644--- a/ministack/services/appsync_events.py+++ b/ministack/services/appsync_events.py@@ -128,10 +128,6 @@ def restore_state(data):_restore_api_child_store(_api_keys, data.get("api_keys", {}))-# Same contract as apigateway.py (used by app.py persistence loader)-load_persisted_state = restore_state--try:_restored = load_state("appsync_events")if _restored:diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 73b9fe24..ee5b8439 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -2170,22 +2170,11 @@ def _iam_role_delete(physical_id, props):# --- IAM Policy ---#-# Two resource types share this section. AWS::IAM::ManagedPolicy creates a-# managed policy and attaches it; AWS::IAM::Policy embeds an *inline* policy on-# every Role, User and Group it names, exactly as PutRolePolicy,-# PutUserPolicy and PutGroupPolicy do. The two are easy to confuse, because-# both carry the same Roles / Users / Groups properties, but they differ in the-# way that matters here: an inline policy is scoped to its entity, so the same-# PolicyName can live on many entities at once, each with its own document,-# while a managed policy is one account-global record that entities point at.-#-# CDK depends on that difference. It derives PolicyName from the construct-# path, so every stack granting something to a role reached by the same path-# produces the same PolicyName. Provisioned as managed policies they collapse-# onto one record and the last stack deployed silently takes the grants away-# from every earlier one; provisioned inline they are independent, as on AWS.-#-# The four helpers below serve the managed policy; the inline handlers follow.+# AWS::IAM::ManagedPolicy creates a managed policy and attaches it;+# AWS::IAM::Policy embeds an inline policy on every Role, User and Group it+# names, as PutRolePolicy / PutUserPolicy / PutGroupPolicy do. Both carry the+# same Roles / Users / Groups properties, which is why they are easy to+# confuse. The helpers below serve the managed policy; the inline ones follow.def _attach_policy_to_entities(arn, props):"""Attach an AWS::IAM::ManagedPolicy to the Roles / Users / Groups it names.@@ -2258,16 +2247,12 @@ def _iam_policy_remove(arn, props):# The AWS::IAM::Policy (inline) handlers.def _iam_inline_policy_targets(props):- """The entities an AWS::IAM::Policy names, with the IAM handlers that write- and remove an inline policy on each kind.+ """The entities an AWS::IAM::Policy names, with the IAM handlers for each.- Going through the handlers rather than the stores directly matters because- the three kinds are stored differently: a role keeps its inline policies on- the role record, while users and groups keep theirs in the sidecar- _user_inline_policies / _group_inline_policies maps.-- An entity the template names but that does not exist is skipped, which is- what attaching did before this became an inline policy.+ Through the handlers, not the stores: a role keeps its inline policies on+ the role record, users and groups in the _user_inline_policies /+ _group_inline_policies sidecars. A named entity that does not exist is+ skipped, as attaching did before."""for prop, param, store, put, remove in (("Roles", "RoleName", _iam._roles,@@ -2314,17 +2299,12 @@ def _iam_policy_drop(props, name):def _iam_policy_create(logical_id, props, stack_name):- """AWS::IAM::Policy embeds an inline policy on every entity it names; it- does not create a managed policy and attach it.-- The physical id is generated rather than being the PolicyName. On AWS the- type's primary identifier is its read-only Id attribute (its resource- schema declares exactly Groups, Id, PolicyDocument, PolicyName, Roles and- Users), and a template that sets an explicit PolicyName still gets an- opaque generated id back from CloudFormation. _physical_name hashes the- stack and the logical id, so the value is stable across updates the way- that generated id is, and two stacks that happen to share a PolicyName- still get ids of their own.+ """Embed the inline policy on every entity the resource names.++ The physical id is generated, not the PolicyName: measured, a stack with an+ explicit PolicyName answers Ref with an opaque id. _physical_name hashes the+ stack and logical id, so it is stable across updates and two stacks sharing+ a PolicyName still get ids of their own."""physical_id = _physical_name(stack_name, logical_id, max_len=128)_iam_policy_put(props, props.get("PolicyName") or physical_id)@@ -2337,13 +2317,9 @@ def _iam_policy_update(physical_id, old_props, new_props, stack_name, logical_idincluded, updates with no interruption(https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-policy.html).- The physical id comes back unchanged, which is what "no interruption" means- here. The engine reads a changed physical id as a replacement and deletes- the predecessor once the update completes, and since an inline policy is- keyed by its entity and its name, that cleanup would delete the very policy- this update had just written. Returning it unchanged also leaves stacks- provisioned by an older MiniStack alone, where the physical id is the- policy name.+ The physical id comes back unchanged: the engine reads a changed one as a+ replacement and deletes the predecessor, which for an inline policy keyed by+ entity and name would delete what this update just wrote."""old_name = old_props.get("PolicyName") or physical_idnew_name = new_props.get("PolicyName") or physical_iddiff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex ce0a9c9a..ceb5ab4d 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -111,11 +111,11 @@ _ecs_reaper_started = False_ecs_reaper_lock = threading.Lock()-# A task that is registered but not stopped, in task-lifecycle order. A-# PENDING or ACTIVATING task already counts against a service's desired-# capacity, so reconciliation must not launch a second one while its images-# are still pulling.-_PRE_STOP_STATUSES = ("PENDING", "ACTIVATING", "RUNNING")+# A task that is registered but not stopped, in task-lifecycle order. A task in+# any starting state already counts against a service's desired capacity, so+# reconciliation must not launch a second one while its images are still+# pulling.+_PRE_STOP_STATUSES = ("PROVISIONING", "PENDING", "ACTIVATING", "RUNNING")def _live_container_ids():@@ -1286,11 +1286,10 @@ def _register_metadata(task_arn, cluster_arn, td, cdef, launch_type, env,env["AWS_CONTAINER_CREDENTIALS_FULL_URI"] = f"http://{host}:{port}/v2/credentials/{new_uuid()}"env["AWS_CONTAINER_AUTHORIZATION_TOKEN"] = secrets.token_urlsafe(32)env["AWS_ENDPOINT_URL"] = f"http://{host}:{port}"- # Seeded from the record, not from a literal: the endpoint overlays the- # live status on every read, so a literal here would only ever be read for- # a task that no longer has one, and it would be wrong then too.+ # Seeded from the record, not a literal: the task is not RUNNING yet here.+ # Later transitions are pushed by _mark_task_activating/_running/_stopped.desired, known, per_container = (- metadata_task_status(task_arn) or ("RUNNING", "PENDING", {})+ _task_status_snapshot(task_arn) or ("RUNNING", "PENDING", {}))container_known = per_container.get(cdef["name"]) or knownecs_metadata.register_container(@@ -1469,26 +1468,12 @@ def _resolve_container_secrets(cdef):return resolved-def metadata_task_status(task_arn):- """Status for the task metadata endpoint, or None when the task is gone.+def _task_status_snapshot(task_arn):+ """``(desiredStatus, lastStatus, {container name: lastStatus})``, or None.- Returns ``(desiredStatus, lastStatus, {container name: lastStatus})``. The- endpoint reports a task's status, and a task's status changes after the- metadata is registered: it is `PENDING` when `RunTask` answers, `ACTIVATING`- for the pull and `RUNNING` once the container is up. Serving the record- rather than a value captured at registration is what keeps- `${ECS_CONTAINER_METADATA_URI_V4}/task` agreeing with `DescribeTasks`.-- A container's own status is carried separately because the two really do- differ: a live Fargate task served `"KnownStatus": "NONE"` for the task and- `"KnownStatus": "RUNNING"` for the container in the same payload, read by- the container itself while it was starting. `DesiredStatus` is the task's- on both, which is what flips to STOPPED when the task is being shut down.-- The lookup is scoped by the account and the region in the task ARN, not by- the request's: a container reaches this endpoint with a path token and no- SigV4, so the request resolves under the default account and region- whatever the task was created under.+ Seeds the metadata payloads at registration. Scoped by the ARN's account and+ region, not the request's: the endpoint is reached with a path token and no+ SigV4, so the request resolves under the defaults."""try:spec = parse_arn(task_arn)@@ -1561,16 +1546,34 @@ def _cleanup_task_resources(task, docker_client, extra_container=None):_remove_docker_container(docker_client, docker_id)+# The downward half of the lifecycle, and whether each state raises an event.+# A Fargate task polled through DescribeTasks read 4 with lastStatus still+# RUNNING and desiredStatus STOPPED, 5 at DEPROVISIONING and 6 at STOPPED, so+# DEACTIVATING and STOPPING pass through without moving the counter.+_STOP_SEQUENCE = (("DEACTIVATING", False), ("STOPPING", False),+ ("DEPROVISIONING", True), ("STOPPED", True))++def _mark_task_stopped(task_arn, task, reason, stop_code, exit_code=None):with resource_lock("ecs-task", task_arn):if not _task_is_active(task_arn, task):return Falsenow = _iso()+ # desiredStatus flips first and counts, while lastStatus is still what+ # it was: that is the change a consumer polls for to learn the task is+ # being shut down._bump_task_version(task)- task["lastStatus"] = "STOPPED"task["desiredStatus"] = "STOPPED"task["stoppingAt"] = task.get("stoppingAt") or now+ for state, counts in _STOP_SEQUENCE:+ if counts:+ _bump_task_version(task)+ task["lastStatus"] = statetask["stoppedAt"] = now+ # "The Unix timestamp for the time when the task execution stopped" —+ # the containers stop before the task reaches STOPPED, so it is set here+ # and never later than stoppedAt.+ task["executionStoppedAt"] = task.get("executionStoppedAt") or nowtask["stoppedReason"] = reasontask["stopCode"] = stop_codefor container in task.get("containers", []):@@ -1578,6 +1581,34 @@ def _mark_task_stopped(task_arn, task, reason, stop_code, exit_code=None):if exit_code is not None:container["exitCode"] = exit_code+ ecs_metadata.set_task_status(+ task_arn, known_status="STOPPED", desired_status="STOPPED"+ )+ ecs_metadata.set_all_container_status(task_arn, "STOPPED")++ cluster_name = _cluster_name_from_arn(task.get("clusterArn", ""))+ if cluster_name:+ _recount_cluster(cluster_name)+ _refresh_service_state(cluster_name, task.get("group", ""))+ return True+++def _mark_task_pending(task_arn, task):+ """Move a registered task to PENDING, where it waits on the agent.++ "PENDING: This is a transition state where Amazon ECS is waiting on the+ container agent to take further action" (task-lifecycle): the state between+ PROVISIONING, where the task is placed, and ACTIVATING, where its images+ are pulled.+ """+ with resource_lock("ecs-task", task_arn):+ if not _task_is_active(task_arn, task):+ return False+ _bump_task_version(task)+ task["lastStatus"] = "PENDING"++ ecs_metadata.set_task_status(task_arn, known_status="PENDING")+cluster_name = _cluster_name_from_arn(task.get("clusterArn", ""))if cluster_name:_recount_cluster(cluster_name)@@ -1592,16 +1623,19 @@ def _mark_task_activating(task_arn, task):additional steps after the task is launched but before the task cantransition to the RUNNING state. This is the state where Amazon ECS pullsthe container images, creates the containers, configures the task- networking, registers load balancer target groups" (task-lifecycle). The- task sits PENDING only until its worker picks it up.+ networking, registers load balancer target groups" (task-lifecycle)."""with resource_lock("ecs-task", task_arn):if not _task_is_active(task_arn, task):return False- _bump_task_version(task)+ # No version bump: a real task polled through DescribeTasks reads 1 at+ # PROVISIONING, 2 at PENDING and 3 at RUNNING, so ACTIVATING raises no+ # state-change event of its own.task["lastStatus"] = "ACTIVATING"task["pullStartedAt"] = task.get("pullStartedAt") or _iso()+ ecs_metadata.set_task_status(task_arn, known_status="ACTIVATING")+cluster_name = _cluster_name_from_arn(task.get("clusterArn", ""))if cluster_name:# pendingTasksCount / pendingCount are "the number of tasks in the@@ -1622,6 +1656,8 @@ def _mark_task_running(task_arn, task):task["pullStoppedAt"] = task.get("pullStoppedAt") or nowtask["startedAt"] = task.get("startedAt") or now+ ecs_metadata.set_task_status(task_arn, known_status="RUNNING")+cluster_name = _cluster_name_from_arn(task.get("clusterArn", ""))if cluster_name:_recount_cluster(cluster_name)@@ -1641,6 +1677,8 @@ def _attach_started_container(task, container, index, metadata_token, ecs_networtask["containers"][index]["lastStatus"] = "RUNNING"ecs_metadata.set_docker_id(metadata_token, container_id)+ # The container's own KnownStatus, not the task's: AWS reports them apart.+ ecs_metadata.set_container_status(metadata_token, "RUNNING")_record_task_ip(task, container, ecs_network)logger.info("ECS: started container %s for task %s", container_id, task_arn[:8])return True@@ -1713,6 +1751,8 @@ def _start_task_worker(task, td, container_overrides, docker_client):cluster_arn = task["clusterArn"]launch_type = task.get("launchType", "EC2")+ if not _mark_task_pending(task_arn, task):+ returnif not _mark_task_activating(task_arn, task):return@@ -1843,12 +1883,12 @@ def _run_task(data):req_tags = data.get("tags", [])docker_client = _get_docker()docker_backed = bool(docker_client)- initial_status = "PENDING" if docker_backed else "RUNNING"- # The network mode decides whether a task reports an ENI attachment at all,- # and the subnet is one of the members that attachment carries. Both are read- # when the container comes up, so they ride on the record until then.+ # Read when the container comes up, so both ride on the record until then.network_mode = td.get("networkMode")subnet = _requested_subnet(data)+ # "PROVISIONING: Amazon ECS has to perform additional steps before the task+ # is launched" (task-lifecycle), for every task, whatever its network mode.+ initial_status = "PROVISIONING" if docker_backed else "RUNNING"tasks = []failures = []diff --git a/ministack/services/ecs_metadata.py b/ministack/services/ecs_metadata.pyindex 83fea2a0..e5abe05e 100644--- a/ministack/services/ecs_metadata.py+++ b/ministack/services/ecs_metadata.py@@ -73,49 +73,48 @@ def set_docker_id(token: str, docker_id: str) -> None:container["DockerId"] = docker_id-def reset() -> None:- with _LOCK:- _TASKS.clear()- _TOKEN_TO_TASK.clear()- _TOKEN_TO_CONTAINER.clear()---def _live_status(task_arn: str) -> tuple[str, str, dict] | None:- """``(DesiredStatus, KnownStatus, {container name: status})``, or None.+def set_task_status(task_arn: str, known_status=None, desired_status=None) -> None:+ """Task-level status for the V4 endpoint, pushed at each transition.- Imported lazily: services/ecs.py imports this module, so a module-level- import back would be circular.+ KnownStatus is task-level only; a container's own is pushed separately,+ because AWS reports the two independently (a Fargate task serves+ "KnownStatus": "NONE" for itself and "RUNNING" for the container in one+ payload). DesiredStatus is the task's on every payload."""- from ministack.services import ecs+ with _LOCK:+ task = _TASKS.get(task_arn)+ if task is None:+ return+ if known_status is not None:+ task["KnownStatus"] = known_status+ if desired_status is not None:+ task["DesiredStatus"] = desired_status+ for container in task.get("Containers", []):+ container["DesiredStatus"] = desired_status- return ecs.metadata_task_status(task_arn)+def set_container_status(token: str, known_status: str) -> None:+ """Push one container's own KnownStatus onto its payload."""+ with _LOCK:+ if container := _TOKEN_TO_CONTAINER.get(token):+ container["KnownStatus"] = known_status-def _with_status(payload: dict, status, container: bool = False) -> dict:- """A copy of ``payload`` carrying the current status.- `DesiredStatus` is the task's everywhere, which is how a container learns- it is being shut down. `KnownStatus` is the task's on the task payload and- the container's own on a container payload: on AWS the two differ while a- task starts, where the container is already RUNNING and the task is not.+def set_all_container_status(task_arn: str, known_status: str) -> None:+ """One KnownStatus onto every container. Only the stop path moves them together."""+ with _LOCK:+ task = _TASKS.get(task_arn)+ if task is None:+ return+ for container in task.get("Containers", []):+ container["KnownStatus"] = known_status- A copy because this writes the two members, and the dicts it is handed are- the live registry entries: the task payload every sibling container's- `/task` view is built from, and the container payloads inside it. Writing- the overlay into those would drift the registry away from what was- registered, and the fallback for a task whose record is gone would then- serve a value nobody registered.- """- out = dict(payload)- if status is None:- return out- desired, known, per_container = status- out["DesiredStatus"] = desired- if container:- out["KnownStatus"] = per_container.get(out.get("Name")) or out.get("KnownStatus") or known- else:- out["KnownStatus"] = known- return out++def reset() -> None:+ with _LOCK:+ _TASKS.clear()+ _TOKEN_TO_TASK.clear()+ _TOKEN_TO_CONTAINER.clear()async def handle_request(method, path, headers, body, query_params):@@ -129,20 +128,11 @@ async def handle_request(method, path, headers, body, query_params):return json_response({"message": "unknown token"}, status=404)container = _TOKEN_TO_CONTAINER[token]task = _TASKS[arn]- containers = list(task.get("Containers", []))-- # Resolved outside _LOCK: the ecs service takes its own per-task locks, and- # holding this one across that call would be a lock-order inversion.- status = _live_status(arn)rest = (m.group("rest") or "").rstrip("/")if rest == "":- return json_response(_with_status(container, status, container=True))+ return json_response(container)if rest == "/task":- task = _with_status(task, status)- task["Containers"] = [- _with_status(c, status, container=True) for c in containers- ]return json_response(task)if rest in ("/stats", "/task/stats"):return json_response({})diff --git a/ministack/services/eks.py b/ministack/services/eks.pyindex fa8d4646..50cba178 100644--- a/ministack/services/eks.py+++ b/ministack/services/eks.py@@ -29,6 +29,7 @@ import jsonimport loggingimport osimport re+import secretsimport threadingimport timeimport urllib.parse@@ -101,9 +102,9 @@ _oidc_keypair = None # (private_key, jwk_dict, kid)_rbac_reconcilers_lock = threading.Lock()_rbac_reconcilers = {} # (account, region, cluster) -> (stop, wake)_rbac_reconcile_locks = {} # (account, region, cluster) -> Lock-_EKS_RBAC_RECONCILE_INTERVAL = float(- os.environ.get("EKS_RBAC_RECONCILE_INTERVAL", "2")-)+# Paces only the discovery of a namespace created after a wildcard-scoped+# policy was associated; every other trigger wakes the loop directly.+_EKS_RBAC_RECONCILE_INTERVAL = 2.0def _cluster_endpoint(port):@@ -452,7 +453,6 @@ def _k3s_run_kwargs("--tls-san=0.0.0.0","--https-listen-port=6443","--kube-apiserver-arg=authentication-token-webhook-config-file=/etc/rancher/k3s/eks-auth-webhook.yaml",- "--kube-apiserver-arg=authentication-token-webhook-cache-ttl=5m",]if oidc_args:command.extend(oidc_args)@@ -505,7 +505,8 @@ def _k3s_gateway_host(client, ms_network):return "host.docker.internal"-def _k3s_auth_webhook_config(client, ms_network, cluster_name, account_id=None, region=None):+def _k3s_auth_webhook_config(client, ms_network, cluster_name, account_id=None,+ region=None, auth_token=""):"""Build the kubeconfig consumed by the k3s token webhook authenticator.The webhook endpoint is deliberately addressed through MiniStack's@@ -519,7 +520,10 @@ def _k3s_auth_webhook_config(client, ms_network, cluster_name, account_id=None,scheme = "https" if _tls.use_ssl_enabled() else "http"account_id = account_id or get_account_id()region = region or get_region()- server = f"{scheme}://{host}:{port}/eks-auth/{account_id}/{region}/{cluster_name}"+ server = (+ f"{scheme}://{host}:{port}/_ministack/eks-auth/"+ f"{account_id}/{region}/{cluster_name}/{auth_token}"+ )return ("apiVersion: v1\n""kind: Config\n"@@ -723,6 +727,12 @@ def _create_cluster(body, creator_arn=None):"encryptionConfig": body.get("encryptionConfig", []),"accessConfig": body.get("accessConfig", {}),"_creator_arn": creator_arn,+ # The webhook URL's shared secret. The route is unauthenticated by+ # necessity (the apiserver has no AWS credentials), so without this the+ # path is guessable and anyone who reaches the gateway can ask whether a+ # token is valid. Only k3s learns it, from the kubeconfig written into+ # the container before boot.+ "_auth_token": secrets.token_urlsafe(32),"_docker_id": None,"_port": port,}@@ -730,6 +740,7 @@ def _create_cluster(body, creator_arn=None):_clusters[name] = clusterif cluster["tags"]:_tags[arn] = dict(cluster["tags"])+ _bootstrap_creator_access_entry(name, cluster, creator_arn)account_id, region = get_account_id(), get_region()oidc_args, _idp_cfg_refs = _collect_oidc_state(name)@@ -755,7 +766,8 @@ def _create_cluster(body, creator_arn=None):registries_yaml = _k3s_registries_yaml(client, ms_network, _ecr_registry_hosts(cluster))auth_webhook_config = _k3s_auth_webhook_config(- client, ms_network, name, account_id, region+ client, ms_network, name, account_id, region,+ cluster.get("_auth_token", ""),)container = _start_k3s_container(client, run_kwargs, registries_yaml, auth_webhook_config@@ -790,6 +802,35 @@ def _list_clusters(query):return _json_resp(200, {"clusters": names})++def _bootstrap_creator_access_entry(cluster_name, cluster, creator_arn):+ """Give the cluster creator its access entry, as AWS does at creation.++ "Specifies whether or not the cluster creator IAM principal was set as a+ cluster admin access entry during cluster creation time"+ (CreateAccessConfigRequest.bootstrapClusterCreatorAdminPermissions). It is+ an ordinary STANDARD entry with AmazonEKSClusterAdminPolicy at cluster+ scope, which is why ListAccessEntries returns it and deleting it is the+ documented way to revoke the creator's admin access.+ """+ if not creator_arn:+ return+ if not cluster.get("accessConfig", {}).get(+ "bootstrapClusterCreatorAdminPermissions", True+ ):+ return+ entry = _build_access_entry(cluster_name, creator_arn, {"type": "STANDARD"})+ _access_entries[_ae_key(cluster_name, creator_arn)] = entry+ now = _now()+ policy_arn = f"arn:aws:eks::aws:{_ACCESS_POLICY_ARN_PREFIX}AmazonEKSClusterAdminPolicy"+ _access_policies[_ap_key(cluster_name, creator_arn, policy_arn)] = {+ "policyArn": policy_arn,+ "accessScope": {"type": "cluster", "namespaces": []},+ "associatedAt": now,+ "modifiedAt": now,+ }++def _delete_cluster(name):cluster = _clusters.get(name)if not cluster:@@ -817,10 +858,16 @@ def _delete_cluster(name):if ng:_tags.pop(ng.get("nodegroupArn", ""), None)- # Pod identity associations belong to the cluster, so they go with it.- # Left behind they outlive it, and a cluster recreated under the same name- # would inherit the previous one's associations and their role ARNs.+ # Access entries and their policy associations belong to the cluster, so+ # they go with it. Left behind they outlive it, and a cluster recreated+ # under the same name would inherit the previous one's grants.prefix = f"{name}\x00"+ for key in [k for k in _access_entries if str(k).startswith(prefix)]:+ entry = _access_entries.pop(key, None)+ if entry:+ _tags.pop(entry.get("accessEntryArn", ""), None)+ for key in [k for k in _access_policies if str(k).startswith(prefix)]:+ _access_policies.pop(key, None)for key in [k for k in _pod_identity_associations if str(k).startswith(prefix)]:assoc = _pod_identity_associations.pop(key, None)if assoc:@@ -1774,8 +1821,12 @@ def _restart_k3s(cluster_name, oidc_args=None, idp_cfg_refs=None):registries_yaml = _k3s_registries_yaml(client, ms_network, _ecr_registry_hosts(cluster))cluster_spec = parse_arn(cluster.get("arn", ""))+ # A restart reuses the cluster's token; one minted here would not+ # match the URL k3s was given, and the restored record carries it.+ cluster.setdefault("_auth_token", secrets.token_urlsafe(32))auth_webhook_config = _k3s_auth_webhook_config(- client, ms_network, cluster_name, cluster_spec.account_id, cluster_spec.region+ client, ms_network, cluster_name, cluster_spec.account_id,+ cluster_spec.region, cluster["_auth_token"],)container = _start_k3s_container(client, run_kwargs, registries_yaml, auth_webhook_config@@ -2288,7 +2339,7 @@ def _access_entry_for_principal(cluster_name, account_id, region, principal_arn)return None-def _authenticate_token_review(cluster_name, account_id, region, review):+def _authenticate_token_review(cluster_name, account_id, region, review, auth_token=""):from ministack.app import AUTHspec = review.get("spec")@@ -2300,6 +2351,13 @@ def _authenticate_token_review(cluster_name, account_id, region, review):return _token_review_response(review)account_id, region, cluster = cluster_info+ # The URL's shared secret. Only the kubeconfig written into this cluster's+ # container carries it, so a caller who merely reached the gateway cannot+ # use the endpoint to test whether a token is valid.+ expected_token = cluster.get("_auth_token") or ""+ if not expected_token or not secrets.compare_digest(auth_token, expected_token):+ return _token_review_response(review)+# Permissive mode accepts local bearer credentials without requiring an# IAM identity, a matching secret, or an access entry, just like the AWS# control plane skips IAM enforcement when AUTH=false.@@ -2334,15 +2392,11 @@ def _authenticate_token_review(cluster_name, account_id, region, review):)if principal_arn == entry["principalArn"])- elif (- credential.account_id == account_id- and cluster.get("accessConfig", {}).get("bootstrapClusterCreatorAdminPermissions", True)- and cluster.get("_creator_arn") == (- _role_arn_from_assumed_role(credential.principal_arn) or credential.principal_arn- )- ):- groups.append("system:masters")else:+ # No entry, no Kubernetes access. The creator has one, minted at+ # CreateCluster, so it authorizes through the same path as everyone+ # else rather than through system:masters, which bypasses RBAC and+ # could never be revoked.return _token_review_response(review)# Deduplicate while preserving the caller's configured order.@@ -2356,14 +2410,14 @@ def _authenticate_token_review(cluster_name, account_id, region, review):)-def _handle_auth_webhook(cluster_name, account_id, region, body_bytes):+def _handle_auth_webhook(cluster_name, account_id, region, body_bytes, auth_token=""):try:review = json.loads(body_bytes) if body_bytes else {}except (TypeError, json.JSONDecodeError):review = {}if not isinstance(review, dict):review = {}- return _authenticate_token_review(cluster_name, account_id, region, review)+ return _authenticate_token_review(cluster_name, account_id, region, review, auth_token)# ---------------------------------------------------------------------------@@ -2383,7 +2437,8 @@ def _handle_request_sync(method, path, headers, body_bytes, query_params):# webhook, not by an AWS EKS client. Keep it outside the EKS JSON API# namespace so the normal AWS action router never sees TokenReview data.auth_match = re.fullmatch(- r"/eks-auth/(\d{12})/([A-Za-z0-9-]+)/([A-Za-z0-9_.-]+)", path+ r"/_ministack/eks-auth/(\d{12})/([A-Za-z0-9-]+)/([A-Za-z0-9_.-]+)/([A-Za-z0-9_-]{16,})",+ path,)if auth_match and method == "POST":return _handle_auth_webhook(@@ -2391,6 +2446,7 @@ def _handle_request_sync(method, path, headers, body_bytes, query_params):auth_match.group(1),auth_match.group(2),body_bytes,+ auth_match.group(4),)try:diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 31c925bd..15655421 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -6986,7 +6986,16 @@ _esm_inflight_lock = threading.Lock()_esm_wake = threading.Event()-def _sqs_esm_concurrency(esm: dict, func_rec: dict, config: dict) -> int:+def _sqs_esm_concurrency(esm: dict, func_rec: dict, config: dict, queue: dict | None = None) -> int:+ """In-flight batches allowed for one SQS event source mapping.++ FIFO is 1: "Amazon SQS ensures that messages in the same group are+ delivered to Lambda in order", and a batch here spans groups, so two in+ flight reorder one. Serial until the poller splits batches by+ MessageGroupId.+ """+ if (queue or {}).get("is_fifo"):+ return 1limit = (esm.get("ScalingConfig") or {}).get("MaximumConcurrency") or _ESM_SQS_DEFAULT_CONCURRENCYreserved = _reserved_concurrency(func_rec, config)return min(limit, reserved) if reserved else limit@@ -7131,7 +7140,7 @@ def _poll_sqs():if _esm_backoff_until.get(esm_id, 0) > time.time():continue# Only this thread increments, so the count can't rise before dispatch.- if _esm_inflight.get(esm_id, 0) >= _sqs_esm_concurrency(esm, func_rec, _cfg):+ if _esm_inflight.get(esm_id, 0) >= _sqs_esm_concurrency(esm, func_rec, _cfg, queue):continuebatch_size = esm.get("BatchSize", 10)diff --git a/ministack/services/organizations.py b/ministack/services/organizations.pyindex aa4f24f0..efd68896 100644--- a/ministack/services/organizations.py+++ b/ministack/services/organizations.py@@ -19,6 +19,7 @@ import jsonimport loggingimport time+from ministack.core.persistence import load_statefrom ministack.core.responses import (AccountScopedDict,error_response_json,@@ -72,6 +73,16 @@ def restore_state(data):store[k] = v+try:+ _restored = load_state("organizations")+ if _restored:+ restore_state(_restored)+except Exception:+ logging.getLogger(__name__).exception(+ "Failed to restore persisted state; continuing with fresh store"+ )++def _json(status, body):return status, {"Content-Type": "application/x-amz-json-1.1"}, json.dumps(body).encode()diff --git a/ministack/services/ses_v2.py b/ministack/services/ses_v2.pyindex 50e392d1..cb22515d 100644--- a/ministack/services/ses_v2.py+++ b/ministack/services/ses_v2.py@@ -320,7 +320,7 @@ async def handle_request(method, path, headers, body, query_params):# POST /v2/email/outbound-emails (SendEmail)if sub == "/outbound-emails" and method == "POST":- msg_id = f"ministack-{new_uuid()}"+ msg_id = f"{new_uuid()}@email.amazonses.com"source = data.get("FromEmailAddress", "")dest = data.get("Destination", {})to_addrs = dest.get("ToAddresses", [])@@ -423,7 +423,7 @@ async def handle_request(method, path, headers, body, query_params):subj = rendered.get("Subject", "")body_text = rendered.get("Text", "")body_html = rendered.get("Html", "")- msg_id = f"ministack-{new_uuid()}"+ msg_id = f"{new_uuid()}@email.amazonses.com"all_addrs = to_addrs + cc_addrs + bcc_addrsif source and all_addrs:diff --git a/ministack/services/sqs.py b/ministack/services/sqs.pyindex abf2f2cc..9f34f9e1 100644--- a/ministack/services/sqs.py+++ b/ministack/services/sqs.py@@ -718,14 +718,55 @@ def _act_change_visibility(data: dict, qurl: str) -> dict:return {}+# ── Batch request validation ───────────────────────────────++_BATCH_MAX_ENTRIES = 10+_BATCH_ENTRY_ID_MAX_LENGTH = 80+_BATCH_ENTRY_ID_RE = re.compile(r"^[A-Za-z0-9_-]+$")+++def _validate_batch_entries(entries: list, entry_name: str) -> None:+ """Run the checks AWS applies to a batch request before it looks at any entry.++ Each of these fails the whole request rather than a single entry, which is what+ separates them from the per-entry results the batch actions return. The codes are+ the JSON protocol shape names; _QUERY_COMPAT_CODES already carries their legacy+ Query spellings, so callers see AWS.SimpleQueueService.EmptyBatchRequest and the+ rest. SendMessageBatch, DeleteMessageBatch and ChangeMessageVisibilityBatch each+ declare all four in the SQS model.+ See https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessageBatch.html+ """+ if not entries:+ raise _Err("EmptyBatchRequest",+ f"There should be at least one {entry_name} in the request.")++ if len(entries) > _BATCH_MAX_ENTRIES:+ raise _Err("TooManyEntriesInBatchRequest",+ "Too many messages in a batch request. A maximum of 10 messages are allowed.")++ seen: set = set()+ for entry in entries:+ entry_id = entry.get("Id") or ""+ if (len(entry_id) > _BATCH_ENTRY_ID_MAX_LENGTH+ or not _BATCH_ENTRY_ID_RE.match(entry_id)):+ raise _Err("InvalidBatchEntryId",+ "A batch entry id can only contain alphanumeric characters, "+ "hyphens and underscores. It can be at most 80 letters long.")+ if entry_id in seen:+ raise _Err("BatchEntryIdsNotDistinct", f"Id {entry_id} repeated.")+ seen.add(entry_id)++# ── ChangeMessageVisibilityBatch ───────────────────────────def _act_change_visibility_batch(data: dict, qurl: str) -> dict:url = data.get("QueueUrl", qurl)q = _get_q(url)+ entries = data.get("Entries", [])+ _validate_batch_entries(entries, "ChangeMessageVisibilityBatchRequestEntry")ok: list = []fail: list = []- for e in data.get("Entries", []):+ for e in entries:eid = e.get("Id", "")rh = e.get("ReceiptHandle", "")vt = int(e.get("VisibilityTimeout", 30))@@ -888,9 +929,7 @@ def _act_send_message_batch(data: dict, qurl: str) -> dict:url = data.get("QueueUrl", qurl)_get_q(url)entries = data.get("Entries", [])- if len(entries) > 10:- raise _Err("TooManyEntriesInBatchRequest",- "Too many messages in a batch request. A maximum of 10 messages are allowed.")+ _validate_batch_entries(entries, "SendMessageBatchRequestEntry")# AWS rule: "The maximum allowed individual message size and the maximum# total payload size (the sum of the individual lengths of all of the@@ -935,9 +974,11 @@ def _act_send_message_batch(data: dict, qurl: str) -> dict:def _act_delete_message_batch(data: dict, qurl: str) -> dict:url = data.get("QueueUrl", qurl)q = _get_q(url)+ entries = data.get("Entries", [])+ _validate_batch_entries(entries, "DeleteMessageBatchRequestEntry")ok: list = []fail: list = []- for e in data.get("Entries", []):+ for e in entries:eid = e.get("Id", "")rh = e.get("ReceiptHandle", "")before = len(q["messages"])diff --git a/tests/test_ecs.py b/tests/test_ecs.pyindex 0ad96d9b..f0395c03 100644--- a/tests/test_ecs.py+++ b/tests/test_ecs.py@@ -80,7 +80,7 @@ def test_ecs_run_task_stops_after_exit(ecs):)resp = ecs.run_task(cluster="task-lifecycle", taskDefinition="short-lived")task_arn = resp["tasks"][0]["taskArn"]- assert resp["tasks"][0]["lastStatus"] in ("PENDING", "RUNNING")+ assert resp["tasks"][0]["lastStatus"] in ("PROVISIONING", "PENDING", "RUNNING")# Poll until STOPPED (container exits almost immediately)stopped = False@@ -170,7 +170,7 @@ def test_ecs_run_task_network_connectivity(ecs):)resp = ecs.run_task(cluster="net-test", taskDefinition="net-probe")task_arn = resp["tasks"][0]["taskArn"]- assert resp["tasks"][0]["lastStatus"] in ("PENDING", "RUNNING")+ assert resp["tasks"][0]["lastStatus"] in ("PROVISIONING", "PENDING", "RUNNING")# Poll until STOPPED — wget should succeed (exit 0) if network is correctsuccess = False@@ -218,7 +218,7 @@ def test_ecs_run_task_metadata_v4(ecs):)resp = ecs.run_task(cluster="metadata-test", taskDefinition="metadata-probe")task_arn = resp["tasks"][0]["taskArn"]- assert resp["tasks"][0]["lastStatus"] in ("PENDING", "RUNNING")+ assert resp["tasks"][0]["lastStatus"] in ("PROVISIONING", "PENDING", "RUNNING")success = Falsefor _ in range(30):@@ -1584,7 +1584,7 @@ def test_ecs_run_task_returns_pending_before_docker_start(monkeypatch):"taskDefinition": "pending-test-td",})task = json.loads(response[2])["tasks"][0]- assert task["lastStatus"] == "PENDING"+ assert task["lastStatus"] == "PROVISIONING"assert task["containers"][0]["lastStatus"] == "PENDING"# AWS omits a timestamp it has no value for rather than sending a null:# the task has not started, pulled or stopped yet.@@ -1609,6 +1609,125 @@ def test_ecs_run_task_returns_pending_before_docker_start(monkeypatch):assert described["containers"][0]["exitCode"] == 0+def test_ecs_run_task_starts_provisioning_and_metadata_follows(monkeypatch):+ """A task starts PROVISIONING and the metadata endpoint follows it,+ reporting the container's own KnownStatus apart from the task's.+ Reported by @iot-rocket."""+ import threading++ from ministack.services import ecs as _ecs+ from ministack.services import ecs_metadata as _md++ started = threading.Event()+ release = threading.Event()+ containers = {}++ class FakeContainer:+ def __init__(self, cid):+ self.id = cid+ self.status = "running"+ self.attrs = {"NetworkSettings": {"Networks": {}}}++ def reload(self):+ pass++ def wait(self):+ return {"StatusCode": 0}++ def stop(self, timeout=5):+ self.status = "exited"++ def remove(self, **kwargs):+ pass++ class FakeContainers:+ def get(self, name):+ if name in containers:+ return containers[name]+ raise Exception("not found")++ def list(self, *args, **kwargs):+ return list(containers.values())++ def run(self, image, **kwargs):+ started.set()+ assert release.wait(timeout=5)+ container = FakeContainer("awsvpc-test-container")+ containers[container.id] = container+ return container++ monkeypatch.setattr(+ _ecs, "_get_docker", lambda: SimpleNamespace(containers=FakeContainers())+ )+ _ecs._register_task_definition({+ "family": "awsvpc-test-td",+ "networkMode": "awsvpc",+ "containerDefinitions": [{"name": "app", "image": "busybox"}],+ })++ response = _ecs._run_task({+ "cluster": "awsvpc-test-c",+ "taskDefinition": "awsvpc-test-td",+ })+ task = json.loads(response[2])["tasks"][0]+ arn = task["taskArn"]+ assert task["lastStatus"] == "PROVISIONING"++ assert started.wait(timeout=2)+ assert _ecs._tasks[arn]["lastStatus"] == "ACTIVATING"+ # Seeded from the container's own record entry, still PENDING while the+ # task pulls: AWS reports the two apart.+ assert _md._TASKS[arn]["KnownStatus"] == "ACTIVATING"+ assert _md._TASKS[arn]["DesiredStatus"] == "RUNNING"+ assert all(c["KnownStatus"] == "PENDING" for c in _md._TASKS[arn]["Containers"])++ release.set()+ _wait_until(lambda: _ecs._tasks[arn]["lastStatus"] == "RUNNING")+ _wait_until(lambda: _md._TASKS[arn]["KnownStatus"] == "RUNNING")+ assert all(c["KnownStatus"] == "RUNNING" for c in _md._TASKS[arn]["Containers"])++ # DesiredStatus reaches the container payloads; KnownStatus stays per-container.+ _ecs._stop_task({"cluster": "awsvpc-test-c", "task": arn})+ assert _ecs._tasks[arn]["lastStatus"] == "STOPPED"+++def test_ecs_run_task_bridge_mode_also_starts_provisioning(monkeypatch):+ """Every network mode starts PROVISIONING, not only awsvpc: the ENI is one+ example of the "additional steps before the task is launched", not the+ condition for the state (task-lifecycle)."""+ import threading++ from ministack.services import ecs as _ecs++ release = threading.Event()++ class FakeContainers:+ def get(self, _name):+ raise Exception("not found")++ def list(self, *args, **kwargs):+ return []++ def run(self, image, **kwargs):+ assert release.wait(timeout=5)+ raise RuntimeError("stopped by the test")++ monkeypatch.setattr(+ _ecs, "_get_docker", lambda: SimpleNamespace(containers=FakeContainers())+ )+ _ecs._register_task_definition({+ "family": "bridge-test-td",+ "networkMode": "bridge",+ "containerDefinitions": [{"name": "app", "image": "busybox"}],+ })+ response = _ecs._run_task({+ "cluster": "bridge-test-c",+ "taskDefinition": "bridge-test-td",+ })+ assert json.loads(response[2])["tasks"][0]["lastStatus"] == "PROVISIONING"+ release.set()++def test_ecs_run_task_startup_failure_is_a_stopped_task(monkeypatch):from ministack.services import ecs as _ecs@@ -1823,11 +1942,11 @@ def test_ecs_task_version_counts_state_changes(monkeypatch):})task = json.loads(response[2])["tasks"][0]task_arn = task["taskArn"]- assert task["lastStatus"] == "PENDING"+ assert task["lastStatus"] == "PROVISIONING"assert task["version"] == 1- # 3, not 2: the task passes through ACTIVATING on its way to RUNNING, and- # that is a state this record reports, so it counts like the others.+ # 3, not 4: ACTIVATING raises no state-change event, so the bumps to RUNNING+ # are PROVISIONING, PENDING and RUNNING, which is what a real task reads._wait_until(lambda: _ecs._tasks[task_arn]["lastStatus"] == "RUNNING")assert _ecs._tasks[task_arn]["version"] == 3@@ -1837,12 +1956,13 @@ def test_ecs_task_version_counts_state_changes(monkeypatch):"reason": "done here",})[2])["task"]assert stopped["lastStatus"] == "STOPPED"- assert stopped["version"] == 4+ assert stopped["version"] == 6def test_ecs_task_version_moves_once_for_a_natural_exit(monkeypatch):"""The exit is observed by whichever DescribeTasks notices it first; the- ones after it describe the same version."""+ ones after it describe the same version. 6, as on a real task: the+ desiredStatus flip, DEPROVISIONING and STOPPED each count."""from ministack.services import ecs as _ecscontainer = _version_probe_container("version-exit-container")@@ -1864,13 +1984,13 @@ def test_ecs_task_version_moves_once_for_a_natural_exit(monkeypatch):"tasks": [task_arn],})[2])["tasks"][0]assert described["lastStatus"] == "STOPPED"- assert described["version"] == 4+ assert described["version"] == 6again = json.loads(_ecs._describe_tasks({"cluster": "version-exit-c","tasks": [task_arn],})[2])["tasks"][0]- assert again["version"] == 4+ assert again["version"] == 6def test_ecs_secret_resolution_failure_stops_before_docker_run(monkeypatch):@@ -1921,7 +2041,7 @@ def test_ecs_run_task_count_and_multi_container_startup_are_independent(monkeypa"count": 2,})tasks = json.loads(response[2])["tasks"]- assert all(task["lastStatus"] == "PENDING" for task in tasks)+ assert all(task["lastStatus"] == "PROVISIONING" for task in tasks)_wait_until(lambda: len(fake_containers.calls) == 4)_wait_until(lambda: all(diff --git a/tests/test_ecs_metadata.py b/tests/test_ecs_metadata.pyindex 75fe6726..62384c21 100644--- a/tests/test_ecs_metadata.py+++ b/tests/test_ecs_metadata.py@@ -160,57 +160,55 @@ def test_trailing_slash_on_root_is_tolerated():assert body["Name"] == "web"-def test_status_follows_the_task_record():- """The endpoint follows the task record instead of always saying RUNNING.-- A container reads ${ECS_CONTAINER_METADATA_URI_V4}/task while it is- starting, which since the async start is the whole image pull. Reporting- RUNNING there contradicts DescribeTasks for the length of that pull.- """- from ministack.services import ecs-+def test_status_is_pushed_onto_the_payload_as_the_task_moves():+ """The endpoint reports the task's status instead of always saying RUNNING."""arn = "arn:aws:ecs:us-east-1:000000000000:task/c/statusprobe01"- task = {- "taskArn": arn,- "desiredStatus": "RUNNING",- "lastStatus": "PENDING",- "containers": [{"name": "probe", "lastStatus": "PENDING"}],- }- ecs._tasks[arn] = task_register("statusprobetoken01", arn, "probe", KnownStatus="PENDING")- try:- for status in ("PENDING", "ACTIVATING", "RUNNING"):- task["lastStatus"] = status- _, body = _call("GET", "/v4/statusprobetoken01/task")- assert body["KnownStatus"] == status-- # A container's KnownStatus is its own, not the task's: on AWS a- # starting task serves "NONE" for itself and "RUNNING" for the- # container that is reading the endpoint.- task["lastStatus"] = "ACTIVATING"- task["containers"][0]["lastStatus"] = "RUNNING"- _, body = _call("GET", "/v4/statusprobetoken01/task")- assert body["KnownStatus"] == "ACTIVATING"- assert body["Containers"][0]["KnownStatus"] == "RUNNING"- assert _call("GET", "/v4/statusprobetoken01")[1]["KnownStatus"] == "RUNNING"- # desiredStatus is the task's on both, which is what a container polls- # to find out it is being shut down.- task["desiredStatus"] = "STOPPED"+ for status in ("PENDING", "ACTIVATING", "RUNNING"):+ ecs_metadata.set_task_status(arn, known_status=status)_, body = _call("GET", "/v4/statusprobetoken01/task")- assert body["DesiredStatus"] == "STOPPED"- assert body["Containers"][0]["DesiredStatus"] == "STOPPED"- assert _call("GET", "/v4/statusprobetoken01")[1]["DesiredStatus"] == "STOPPED"-- # The overlay is applied to a copy. The registry dicts are shared by- # every sibling container of a task, so writing the live status into- # them would make one read change what the next one serves. Reading the- # response back cannot show this, since json.loads already copies:- # assert on the registry itself.- assert ecs_metadata._TASKS[arn]["KnownStatus"] == "RUNNING"- assert ecs_metadata._TOKEN_TO_CONTAINER["statusprobetoken01"]["KnownStatus"] == "PENDING"- finally:- ecs._tasks.pop(arn, None)+ assert body["KnownStatus"] == status++ # On AWS a starting task serves "NONE" for itself and "RUNNING" for the+ # container reading the endpoint, in one payload.+ ecs_metadata.set_task_status(arn, known_status="ACTIVATING")+ ecs_metadata.set_container_status("statusprobetoken01", "RUNNING")+ _, body = _call("GET", "/v4/statusprobetoken01/task")+ assert body["KnownStatus"] == "ACTIVATING"+ assert body["Containers"][0]["KnownStatus"] == "RUNNING"+ assert _call("GET", "/v4/statusprobetoken01")[1]["KnownStatus"] == "RUNNING"++ # DesiredStatus is the task's on both.+ ecs_metadata.set_task_status(arn, desired_status="STOPPED")+ _, body = _call("GET", "/v4/statusprobetoken01/task")+ assert body["DesiredStatus"] == "STOPPED"+ assert body["Containers"][0]["DesiredStatus"] == "STOPPED"+ assert _call("GET", "/v4/statusprobetoken01")[1]["DesiredStatus"] == "STOPPED"+ # ... and it did not drag the container's KnownStatus with it.+ assert body["Containers"][0]["KnownStatus"] == "RUNNING"+++def test_stop_pushes_every_container_to_stopped():+ """The stop path moves every container of the task at once."""+ arn = "arn:aws:ecs:us-east-1:000000000000:task/c/stopprobe01"+ _register("stopprobetoken01", arn, "web")+ _register("stopprobetoken02", arn, "sidecar")++ ecs_metadata.set_task_status(arn, known_status="STOPPED", desired_status="STOPPED")+ ecs_metadata.set_all_container_status(arn, "STOPPED")++ _, body = _call("GET", "/v4/stopprobetoken01/task")+ assert body["KnownStatus"] == "STOPPED"+ assert [c["KnownStatus"] for c in body["Containers"]] == ["STOPPED", "STOPPED"]+++def test_a_push_for_an_unregistered_task_is_a_no_op():+ """A task whose tokens are already unregistered must not resurrect an entry."""+ ecs_metadata.set_task_status("arn:aws:ecs:us-east-1:000000000000:task/c/none", known_status="STOPPED")+ ecs_metadata.set_all_container_status("arn:aws:ecs:us-east-1:000000000000:task/c/none", "STOPPED")+ ecs_metadata.set_container_status("no-such-token", "STOPPED")+ assert ecs_metadata._TASKS == {}def test_status_falls_back_to_what_was_registered_when_the_task_is_gone():@@ -221,14 +219,8 @@ def test_status_falls_back_to_what_was_registered_when_the_task_is_gone():assert body["Containers"][0]["KnownStatus"] == "ACTIVATING"-def test_status_finds_a_task_outside_the_default_account_and_region():- """The lookup is keyed off the task ARN, not off the request.-- A container reaches this endpoint with a path token and no SigV4, so the- request resolves under the default account and region. Keying the task- store on those would miss every task created anywhere else, and the- endpoint would silently fall back to what it registered.- """+def test_seeding_finds_a_task_outside_the_default_account_and_region():+ """The seed is keyed off the task ARN, not the request, which carries no SigV4."""from ministack.services import ecsaccount, region = "111122223333", "eu-central-1"@@ -239,10 +231,18 @@ def test_status_finds_a_task_outside_the_default_account_and_region():"lastStatus": "ACTIVATING","containers": [{"name": "probe", "lastStatus": "PENDING"}],})- _register("otherprobetoken01", arn, "probe")try:- _, body = _call("GET", "/v4/otherprobetoken01/task")- assert body["KnownStatus"] == "ACTIVATING"- assert body["Containers"][0]["KnownStatus"] == "PENDING"+ assert ecs._task_status_snapshot(arn) == (+ "RUNNING", "ACTIVATING", {"probe": "PENDING"},+ )finally:ecs._tasks.pop_scoped(account, region, arn, None)+++def test_seeding_returns_none_for_an_unparseable_or_missing_task():+ from ministack.services import ecs++ assert ecs._task_status_snapshot("not-an-arn") is None+ assert ecs._task_status_snapshot(+ "arn:aws:ecs:us-east-1:000000000000:task/c/absent01"+ ) is Nonediff --git a/tests/test_eks.py b/tests/test_eks.pyindex 5d5a5454..b87cd048 100644--- a/tests/test_eks.py+++ b/tests/test_eks.py@@ -1174,7 +1174,11 @@ def test_eks_access_entry_list_returns_principal_arns(eks):eks.create_access_entry(clusterName=cn, principalArn=p1)eks.create_access_entry(clusterName=cn, principalArn=p2)listed = eks.list_access_entries(clusterName=cn)["accessEntries"]- assert set(listed) == {p1, p2}+ # The creator's entry is there too: AWS sets the cluster creator as a+ # cluster admin access entry at creation time, which is what makes it+ # listable and revocable.+ assert {p1, p2} <= set(listed)+ assert "arn:aws:iam::000000000000:root" in listedfinally:try:eks.delete_cluster(name=cn)@@ -1598,21 +1602,42 @@ def _auth_token(key="test", secret="test", session=None, name=_AUTH_CLUSTER, sigreturn "k8s-aws-v1." + base64.urlsafe_b64encode(request.url.encode()).decode().rstrip("=")+# The webhook URL's shared secret; only the kubeconfig written into the k3s+# container carries it, so a caller who merely reaches the gateway cannot use+# the endpoint to probe whether a token is valid.+_AUTH_WEBHOOK_SECRET = "test-webhook-secret-000000000000"++def _auth_cluster(account=_AUTH_ACCOUNT, creator=None, bootstrap=True):- eks_service._clusters.set_scoped(account, _AUTH_REGION, _AUTH_CLUSTER, {+ cluster = {"arn": f"arn:aws:eks:{_AUTH_REGION}:{account}:cluster/{_AUTH_CLUSTER}","roleArn": f"arn:aws:iam::{account}:role/control-plane","_creator_arn": creator,"accessConfig": {"bootstrapClusterCreatorAdminPermissions": bootstrap},- })+ "_auth_token": _AUTH_WEBHOOK_SECRET,+ }+ eks_service._clusters.set_scoped(account, _AUTH_REGION, _AUTH_CLUSTER, cluster)+ # CreateCluster mints the creator's access entry; these records are built+ # straight into the store, so do what that path does.+ with request_scope(account, _AUTH_REGION):+ eks_service._bootstrap_creator_access_entry(_AUTH_CLUSTER, cluster, creator)+++def _auth_token_for(account, region, name):+ """The cluster's webhook secret, the way k3s reads it from its kubeconfig."""+ cluster = eks_service._clusters.get_scoped(account, region, name) or {}+ # A cluster that does not exist has no secret; keep the URL well formed so+ # the request still reaches the handler and is refused on the lookup.+ return cluster.get("_auth_token") or _AUTH_WEBHOOK_SECRETdef _auth_review(bearer, account=_AUTH_ACCOUNT, name=_AUTH_CLUSTER):# Real k3s requests carry no AWS credentials; deliberately use the default# request account even when authenticating to a different tenant's cluster.+ secret = _auth_token_for(account, _AUTH_REGION, name)with request_scope(_AUTH_ACCOUNT, "us-east-1"):status, _, body = asyncio.run(app._dispatch_service_request(- "POST", f"/eks-auth/{account}/{_AUTH_REGION}/{name}", {},+ "POST", f"/_ministack/eks-auth/{account}/{_AUTH_REGION}/{name}/{secret}", {},json.dumps({"apiVersion": "authentication.k8s.io/v1", "spec": {"token": bearer}}).encode(),{}, "review-test",))@@ -1643,16 +1668,21 @@ def test_eks_token_review_authenticates_root_exec_token(eks_mod, monkeypatch):import ministack.app as appmonkeypatch.setattr(app, "AUTH", True)name = f"auth-{_uid()}"- eks_mod._clusters[name] = {+ creator = "arn:aws:iam::000000000000:root"+ cluster = {"arn": f"arn:aws:eks:{REGION}:000000000000:cluster/{name}","roleArn": "arn:aws:iam::000000000000:role/eks-role",- "_creator_arn": "arn:aws:iam::000000000000:root",+ "_creator_arn": creator,+ "_auth_token": _AUTH_WEBHOOK_SECRET,}+ eks_mod._clusters[name] = cluster+ eks_mod._bootstrap_creator_access_entry(name, cluster, creator)token = _eks_exec_token(name)status, _headers, response = _eks_direct(eks_mod,"POST",- f"/eks-auth/000000000000/{REGION}/{name}",+ f"/_ministack/eks-auth/000000000000/{REGION}/{name}/"+ f"{_auth_token_for('000000000000', REGION, name)}",{"apiVersion": "authentication.k8s.io/v1","kind": "TokenReview",@@ -1662,7 +1692,9 @@ def test_eks_token_review_authenticates_root_exec_token(eks_mod, monkeypatch):assert status == 200assert response["status"]["authenticated"] is Trueassert response["status"]["user"]["username"] == "arn:aws:iam::000000000000:root"- assert "system:masters" in response["status"]["user"]["groups"]+ groups = response["status"]["user"]["groups"]+ assert "system:masters" not in groups+ assert any(g.startswith("ministack:eks:access:") for g in groups)def test_eks_token_review_rejects_wrong_cluster_and_tampering(eks_mod, monkeypatch):@@ -1679,7 +1711,8 @@ def test_eks_token_review_rejects_wrong_cluster_and_tampering(eks_mod, monkeypatstatus, _headers, response = _eks_direct(eks_mod,"POST",- f"/eks-auth/000000000000/{REGION}/{name}",+ f"/_ministack/eks-auth/000000000000/{REGION}/{name}/"+ f"{_auth_token_for('000000000000', REGION, name)}",{"spec": {"token": candidate}},)assert status == 200@@ -1755,9 +1788,24 @@ def test_eks_auth_create_records_actual_caller_and_honors_bootstrap(eks_auth_envdef test_eks_auth_root_does_not_get_other_accounts_bootstrap_access(eks_auth_env):_auth_cluster(_AUTH_OTHER_ACCOUNT, creator=f"arn:aws:iam::{_AUTH_OTHER_ACCOUNT}:root")assert _auth_review(_auth_token(), _AUTH_OTHER_ACCOUNT)["authenticated"] is False- assert _auth_review(_auth_token(_AUTH_OTHER_ACCOUNT), _AUTH_OTHER_ACCOUNT)["user"]["groups"] == [- "system:authenticated", "system:masters",- ]+ # The creator authorizes through its own access entry and the materialized+ # AmazonEKSClusterAdminPolicy group, not through system:masters.+ groups = _auth_review(_auth_token(_AUTH_OTHER_ACCOUNT), _AUTH_OTHER_ACCOUNT)["user"]["groups"]+ assert groups[0] == "system:authenticated"+ assert "system:masters" not in groups+ assert any(g.startswith("ministack:eks:access:") for g in groups)+++def test_eks_delete_cluster_takes_its_access_entries_with_it(eks_auth_env):+ """A recreated cluster must not inherit the previous one's grants."""+ _auth_cluster(creator=f"arn:aws:iam::{_AUTH_ACCOUNT}:root")+ with request_scope(_AUTH_ACCOUNT, _AUTH_REGION):+ prefix = f"{_AUTH_CLUSTER}\x00"+ assert [k for k in eks_service._access_entries if str(k).startswith(prefix)]+ assert [k for k in eks_service._access_policies if str(k).startswith(prefix)]+ eks_service._delete_cluster(_AUTH_CLUSTER)+ assert not [k for k in eks_service._access_entries if str(k).startswith(prefix)]+ assert not [k for k in eks_service._access_policies if str(k).startswith(prefix)]def test_eks_auth_nondefault_sts_session_and_role_path_access_entry(eks_auth_env):@@ -1930,4 +1978,7 @@ def test_eks_auth_background_webhook_preserves_account_and_region(eks_auth_env,status, _, _ = eks_service._create_cluster({"name": _AUTH_CLUSTER, "roleArn": iam._roles["control-plane"]["Arn"]})assert status == 200assert finished.wait(3)- assert f"/eks-auth/{_AUTH_OTHER_ACCOUNT}/{_AUTH_REGION}/{_AUTH_CLUSTER}" in captured["webhook"]+ assert f"/_ministack/eks-auth/{_AUTH_OTHER_ACCOUNT}/{_AUTH_REGION}/{_AUTH_CLUSTER}/" in captured["webhook"]+ # The secret is in the URL only k3s receives, and it is not guessable.+ secret = captured["webhook"].split(f"/{_AUTH_CLUSTER}/", 1)[1].split("\n", 1)[0].strip()+ assert len(secret) >= 16diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex a28fafa6..83e34608 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -5753,7 +5753,7 @@ def test_esm_batch_completion_wakes_poll_loop(esm_poll_state):def _sqs_esm_fixture(_lsvc, _sqs, name, *, messages=1, esm_extra=None, func_extra=None):- queue_url = f"http://localhost:4566/000000000000/{name}"+ queue_url = _sqs._queue_url(name)_sqs._queues[queue_url] = {"name": name,"messages": [{@@ -5839,6 +5839,29 @@ def test_poll_sqs_caps_in_flight_batches_per_esm(esm_threaded_dispatch, monkeypaassert _lsvc._esm_inflight["esm-capped"] == expected+def test_poll_sqs_keeps_a_fifo_queue_serial(esm_threaded_dispatch, monkeypatch):+ """A FIFO queue gets one batch in flight whatever MaximumConcurrency says.++ "Amazon SQS ensures that messages in the same group are delivered to Lambda+ in order", and a batch here spans groups, so two in flight at once reorder+ a group. The cap is not MaximumConcurrency for FIFO: on AWS concurrency is+ bounded by the number of message group IDs, and the poller does not+ partition batches by MessageGroupId, so serial is the only safe setting.+ """+ (_lsvc, _sqs, _kin, _ddb), release = esm_threaded_dispatch+ _sqs_esm_fixture(+ _lsvc, _sqs, "esm-fifo", messages=20,+ esm_extra={"ScalingConfig": {"MaximumConcurrency": 8}},+ )+ _sqs._queues[_sqs._queue_url("esm-fifo")]["is_fifo"] = True+ monkeypatch.setattr(_lsvc, "_execute_function", lambda _func, _event: (release.wait(10), {"body": {}})[1])++ for _ in range(20):+ _lsvc._poll_sqs()++ assert _lsvc._esm_inflight["esm-fifo"] == 1++def test_lambda_create_esm_rejects_unresolved_function_arn():original_account = get_account_id()original_region = get_region()diff --git a/tests/test_persistence.py b/tests/test_persistence.pyindex 92e637a7..f120b2bf 100644--- a/tests/test_persistence.py+++ b/tests/test_persistence.py@@ -59,6 +59,34 @@ def test_registered_service_defines_state_contract(mod_name):)[email protected]("svc_key,mod_name", sorted(_state_map.items()))+def test_service_has_restore_path(svc_key, mod_name):+ """Every service in `_state_map` must expose a way to restore its own state.++ Either the module calls `load_state()` itself at import time, or it exposes+ `load_persisted_state(data)` and is wired into `_load_persisted_state()`.+ Without one of the two its state is written on shutdown and dropped on the+ next boot, silently.+ """+ mod = _module(mod_name)+ if not mod.get_state():+ pytest.skip(f"{mod_name} holds no state to restore")+ src = Path(mod.__file__).read_text()++ self_restoring = (+ "from ministack.core.persistence import" in src+ and "load_state(" in src+ )+ centrally_restored = hasattr(mod, "load_persisted_state") and svc_key in {+ "apigateway", "apigateway_v1", "servicediscovery",+ }++ assert self_restoring or centrally_restored, (+ f"Service `{svc_key}` (module `{mod_name}`) is in `_state_map` and will "+ f"be saved on shutdown, but has no restore path on startup."+ )++def test_account_region_scoped_dict_isolates_account_and_region():"""Account+region scoped stores keep same-name resources independent."""from ministack.core.responses import (diff --git a/tests/test_ses.py b/tests/test_ses.pyindex de352024..8218d52d 100644--- a/tests/test_ses.py+++ b/tests/test_ses.py@@ -210,7 +210,9 @@ def test_ses_v2_send_email(sesv2):}},)- assert resp["MessageId"].startswith("ministack-")+ # Same shape the six v1 send paths return; nothing an AWS client sees+ # should be prefixed with the emulator's name.+ assert resp["MessageId"].endswith("@email.amazonses.com")def test_ses_v2_email_identity_crud(sesv2):sesv2.create_email_identity(EmailIdentity="test-domain.com")diff --git a/tests/test_sqs.py b/tests/test_sqs.pyindex a506e704..7e5b2eb7 100644--- a/tests/test_sqs.py+++ b/tests/test_sqs.py@@ -837,6 +837,102 @@ def test_sqs_send_message_batch_limit(sqs):assert exc_info.value.response["Error"]["Code"] == "AWS.SimpleQueueService.TooManyEntriesInBatchRequest"sqs.delete_queue(QueueUrl=q)+_BATCH_ACTIONS = ("SendMessageBatch", "DeleteMessageBatch", "ChangeMessageVisibilityBatch")+++def _batch_call(sqs, action, url, entries):+ if action == "SendMessageBatch":+ return sqs.send_message_batch(QueueUrl=url, Entries=entries)+ if action == "DeleteMessageBatch":+ return sqs.delete_message_batch(QueueUrl=url, Entries=entries)+ return sqs.change_message_visibility_batch(QueueUrl=url, Entries=entries)+++def _batch_entry(action, entry_id):+ """An entry valid enough to reach the request-level checks.++ The receipt handle is deliberately bogus: every assertion below is about a+ check AWS runs on the request before it looks at an entry, so a batch that+ passes them lands in the per-entry results instead of raising.+ """+ if action == "SendMessageBatch":+ return {"Id": entry_id, "MessageBody": "m"}+ entry = {"Id": entry_id, "ReceiptHandle": "not-a-real-receipt-handle"}+ if action == "ChangeMessageVisibilityBatch":+ entry["VisibilityTimeout"] = 30+ return entry++[email protected]("action", _BATCH_ACTIONS)+def test_sqs_batch_rejects_empty_request(sqs, action):+ """AWS answers a batch with no entries with EmptyBatchRequest."""+ url = sqs.create_queue(QueueName=f"batch-empty-{action.lower()}")["QueueUrl"]+ with pytest.raises(ClientError) as exc:+ _batch_call(sqs, action, url, [])+ assert exc.value.response["Error"]["Code"] == "AWS.SimpleQueueService.EmptyBatchRequest"+ sqs.delete_queue(QueueUrl=url)++[email protected]("action", _BATCH_ACTIONS)+def test_sqs_batch_rejects_repeated_entry_ids(sqs, action):+ """Entry ids have to be distinct within one batch, or AWS fails the whole request."""+ url = sqs.create_queue(QueueName=f"batch-dup-{action.lower()}")["QueueUrl"]+ entries = [_batch_entry(action, "same"), _batch_entry(action, "same")]+ with pytest.raises(ClientError) as exc:+ _batch_call(sqs, action, url, entries)+ assert exc.value.response["Error"]["Code"] == "AWS.SimpleQueueService.BatchEntryIdsNotDistinct"+ sqs.delete_queue(QueueUrl=url)++[email protected]("action", _BATCH_ACTIONS)[email protected]("entry_id", ["bad!id", "a" * 81])+def test_sqs_batch_rejects_malformed_entry_id(sqs, action, entry_id):+ """An entry id is at most 80 alphanumerics, hyphens and underscores."""+ url = sqs.create_queue(QueueName=f"batch-badid-{action.lower()}-{len(entry_id)}")["QueueUrl"]+ with pytest.raises(ClientError) as exc:+ _batch_call(sqs, action, url, [_batch_entry(action, entry_id)])+ assert exc.value.response["Error"]["Code"] == "AWS.SimpleQueueService.InvalidBatchEntryId"+ sqs.delete_queue(QueueUrl=url)++[email protected]("action", ["DeleteMessageBatch", "ChangeMessageVisibilityBatch"])+def test_sqs_batch_rejects_more_than_ten_entries(sqs, action):+ """The ten-entry limit is the whole request's, not just SendMessageBatch's."""+ url = sqs.create_queue(QueueName=f"batch-limit-{action.lower()}")["QueueUrl"]+ entries = [_batch_entry(action, str(i)) for i in range(11)]+ with pytest.raises(ClientError) as exc:+ _batch_call(sqs, action, url, entries)+ assert exc.value.response["Error"]["Code"] == "AWS.SimpleQueueService.TooManyEntriesInBatchRequest"+ sqs.delete_queue(QueueUrl=url)+++def test_sqs_batch_of_ten_distinct_entries_still_succeeds(sqs):+ """A full, well-formed batch is not caught by any of the checks above."""+ url = sqs.create_queue(QueueName="batch-ten-valid")["QueueUrl"]+ sent = sqs.send_message_batch(+ QueueUrl=url,+ Entries=[{"Id": f"id_{i}", "MessageBody": f"m{i}"} for i in range(10)],+ )+ assert len(sent["Successful"]) == 10+ assert not sent.get("Failed")++ handles = []+ while len(handles) < 10:+ received = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10, WaitTimeSeconds=1)+ messages = received.get("Messages", [])+ if not messages:+ break+ handles.extend(m["ReceiptHandle"] for m in messages)++ deleted = sqs.delete_message_batch(+ QueueUrl=url,+ Entries=[{"Id": f"id_{i}", "ReceiptHandle": h} for i, h in enumerate(handles[:10])],+ )+ assert len(deleted["Successful"]) == 10+ assert not deleted.get("Failed")+ sqs.delete_queue(QueueUrl=url)++def test_sqs_typed_exception_queue_not_found(sqs):"""client.exceptions.QueueDoesNotExist must be raised (not generic ClientError)when accessing a non-existent queue — requires <Type> in the XML error response."""diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.pyindex 8d11bd79..143eaf66 100644--- a/tests/test_stepfunctions.py+++ b/tests/test_stepfunctions.py@@ -3849,7 +3849,7 @@ def test_sfn_integration_ecs_run_task_output_contains_status(sfn, ecs):assert "taskArn" in task_outassert "containers" in task_outassert task_out["containers"][0]["name"] == "app"- assert task_out["lastStatus"] in ("PENDING", "RUNNING")+ assert task_out["lastStatus"] in ("PROVISIONING", "PENDING", "RUNNING")assert "failures" in outputdef test_sfn_integration_ecs_run_task_container_overrides_reach_the_task(sfn, ecs):