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
Ecs container metadata (#553)
Yakir Oren4faf0d8ac586
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8adc3a01..38b68c21 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,14 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [Unreleased]++### Added++- **ECS Task Metadata V4 emulator** — every container started by `RunTask` now receives `ECS_CONTAINER_METADATA_URI_V4=http://<ministack>:<gateway>/v4/<token>`, and the gateway responds on `/v4/<token>` (current container), `/v4/<token>/task` (task with sibling `Containers` array), and `/v4/<token>/stats` / `/task/stats` (empty stub). Tokens are per-container `secrets.token_urlsafe(32)` values; the registry is volatile by design (stripped on persistence, cleared by `/_ministack/reset`). The metadata host is Ministack's own IP on the shared user-defined Docker network (the only address that's reliably reachable on Linux Docker — `host-gateway` resolves to `docker0` which sibling bridges typically can't route to); when Ministack runs outside Docker the URI falls back to `host.docker.internal` mapped through `extra_hosts: host-gateway` for Docker-Desktop compatibility, and `networkMode: host` containers use loopback. Container labels follow the standard `com.amazonaws.ecs.*` keys (`task-arn`, `container-name`, `task-definition-family`, `task-definition-version`, `cluster`). `RunTask` also now translates more of the task-def: `privileged`, `linuxParameters.capabilities.add`, `pidMode: host`, and `volumes` + `mountPoints` (list-of-binds so two ECS volumes sharing a host path don't collide).++---+## [1.3.27] — 2026-05-04### Addeddiff --git a/README.md b/README.mdindex 13ec6b4d..27126a6a 100644--- a/README.md+++ b/README.md@@ -353,6 +353,7 @@ subnet = ec2.create_subnet(| **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, CreatePolicy, GetPolicy, DeletePolicy, AttachRolePolicy, DetachRolePolicy, PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies, ListAttachedRolePolicies, CreateAccessKey, ListAccessKeys, DeleteAccessKey, CreateInstanceProfile, GetInstanceProfile, DeleteInstanceProfile, AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile, ListInstanceProfiles, CreateGroup, GetGroup, AddUserToGroup, RemoveUserFromGroup, CreateServiceLinkedRole, DeleteServiceLinkedRole, GetServiceLinkedRoleDeletionStatus, CreateOpenIDConnectProvider, TagRole, UntagRole, TagUser, UntagUser, TagPolicy, UntagPolicy | || **STS** | GetCallerIdentity, AssumeRole, GetSessionToken, AssumeRoleWithWebIdentity | || **IMDS** (EC2 Instance Metadata) | `PUT /latest/api/token`, `GET /latest/meta-data/instance-id`, `GET /latest/meta-data/iam/security-credentials/`, `GET /latest/meta-data/iam/security-credentials/<role>`, `GET /latest/meta-data/iam/info`, `GET /latest/meta-data/placement/{region,availability-zone,...}`, `GET /latest/dynamic/instance-identity/document` | IMDSv1 + IMDSv2; default credential chain falls through to a `ministack-instance-role` document with `ASIA*` session creds. Point SDKs at ministack via `AWS_EC2_METADATA_SERVICE_ENDPOINT=http://localhost:4566` (or `ec2_metadata_service_endpoint` in `~/.aws/config`); set `MINISTACK_IMDS_V2_REQUIRED=1` to require the token PUT |+| **ECS Task Metadata V4** | `GET /v4/<token>`, `GET /v4/<token>/task`, `GET /v4/<token>/stats`, `GET /v4/<token>/task/stats` | Per-container token injected as `ECS_CONTAINER_METADATA_URI_V4` on every container started by `RunTask`. `/task` returns sibling containers in the same task. Containers reach the gateway via `host.docker.internal` (mapped through `extra_hosts: host-gateway`, so it works on user-defined Docker networks); `networkMode: host` containers use loopback. Volatile by design (stripped on persistence, cleared by `/_ministack/reset`) || **SecretsManager** | CreateSecret, GetSecretValue, ListSecrets, DeleteSecret, UpdateSecret, DescribeSecret, PutSecretValue, UpdateSecretVersionStage, RestoreSecret, RotateSecret, GetRandomPassword, ListSecretVersionIds, ReplicateSecretToRegions, TagResource, UntagResource, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy, ValidateResourcePolicy | || **CloudWatch Logs** | CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents, PutRetentionPolicy, DeleteRetentionPolicy, PutSubscriptionFilter, DeleteSubscriptionFilter, DescribeSubscriptionFilters, PutMetricFilter, DeleteMetricFilter, DescribeMetricFilters, TagLogGroup, UntagLogGroup, ListTagsLogGroup, TagResource, UntagResource, ListTagsForResource, StartQuery, GetQueryResults, StopQuery, PutDestination, DeleteDestination, DescribeDestinations, PutDestinationPolicy | `FilterLogEvents` supports `*`/`?` globs, multi-term AND, `-term` exclusion |@@ -637,6 +638,11 @@ task_arn = resp["tasks"][0]["taskArn"]ecs.stop_task(cluster="dev", task=task_arn)```+Each container also gets the standard ECS Task Metadata V4 endpoint injected as+`ECS_CONTAINER_METADATA_URI_V4`, so anything inside the container that uses the+AWS SDK for ECS metadata (X-Ray, OpenTelemetry, application code calling+`GET $ECS_CONTAINER_METADATA_URI_V4/task`) works without changes.+---## Configurationdiff --git a/ministack/app.py b/ministack/app.pyindex 3da2efed..ec340bce 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -213,6 +213,7 @@ SERVICE_REGISTRY = {"ec2": {"module": "ec2"},"ecr": {"module": "ecr"},"ecs": {"module": "ecs"},+ "ecs-metadata": {"module": "ecs_metadata"},"eks": {"module": "eks"},"elasticache": {"module": "elasticache"},"elasticfilesystem": {"module": "efs"},diff --git a/ministack/core/router.py b/ministack/core/router.pyindex 2c2e6c0f..26413e46 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -23,6 +23,10 @@ _LAMBDA_PATH_RE = re.compile(r"account-settings|runtime|tags|code-signing-configs)(?:/|$)")+# ECS Task Metadata V4 paths: /v4/<token>[/task|/stats|...]. Token is+# url-safe base64, generated per-container in services/ecs.py.+_ECS_METADATA_PATH_RE = re.compile(r"^/v4/[A-Za-z0-9_-]{8,}(?:/.*)?$")+# Service detection patternsSERVICE_PATTERNS = {"s3": {@@ -790,6 +794,8 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->return "cognito-idp"if path_lower.startswith("/saml2/idpresponse"):return "cognito-idp"+ if _ECS_METADATA_PATH_RE.match(path_lower):+ return "ecs-metadata"if path_lower.startswith(("/clusters", "/taskdefinitions", "/tasks", "/services", "/stoptask")):return "ecs"# smithy-rpc-v2-cbor path: /service/ServiceName/operation/ActionNamediff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 46424bf3..19833f27 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -1971,6 +1971,8 @@ def _ecs_task_def_create(logical_id, props, stack_name):"executionRoleArn": props.get("ExecutionRoleArn", ""),"taskRoleArn": props.get("TaskRoleArn", ""),"volumes": props.get("Volumes", []),+ "pidMode": props.get("PidMode", ""),+ "ipcMode": props.get("IpcMode", ""),"placementConstraints": props.get("PlacementConstraints", []),}_ecs._task_defs[td_key] = tddiff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex cf2f3dd7..c144b67b 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -27,6 +27,7 @@ import copyimport jsonimport loggingimport os+import secretsimport threadingimport time@@ -40,6 +41,7 @@ from ministack.core.responses import (new_uuid,now_iso,)+from ministack.services import ecs_metadatalogger = logging.getLogger("ecs")@@ -123,6 +125,7 @@ def get_state():for scoped_key, task in _tasks._data.items():t = copy.deepcopy(task)t.pop("_docker_ids", None)+ t.pop("_metadata_tokens", None)tasks._data[scoped_key] = tstate["tasks"] = tasksreturn state@@ -857,6 +860,116 @@ def _build_task_containers(td, container_overrides):return containers+def _register_metadata(task_arn, cluster_arn, td, cdef, launch_type, env,+ host_mode, ministack_net_ip):+ """Inject ECS_CONTAINER_METADATA_URI_V4 into env and register the+ container with the metadata server. Returns the token so the caller can+ record it on the task and update DockerId once the container starts.++ `ministack_net_ip` is Ministack's IP on the shared user-defined network+ (when discoverable). Using it directly is the only reliable address on+ Linux Docker; `host.docker.internal` is a Docker-Desktop-only fallback.+ """+ token = secrets.token_urlsafe(32)+ if host_mode:+ host = "127.0.0.1"+ elif ministack_net_ip:+ host = ministack_net_ip+ else:+ host = "host.docker.internal"+ port = os.environ.get("GATEWAY_PORT") or os.environ.get("EDGE_PORT") or "4566"+ env["ECS_CONTAINER_METADATA_URI_V4"] = f"http://{host}:{port}/v4/{token}"+ ecs_metadata.register_container(+ token,+ task_arn,+ task_payload={+ "Cluster": cluster_arn,+ "TaskARN": task_arn,+ "Family": td.get("family", ""),+ "Revision": str(td.get("revision", 1)),+ "DesiredStatus": "RUNNING",+ "KnownStatus": "RUNNING",+ "AvailabilityZone": f"{get_region()}a",+ "LaunchType": launch_type,+ },+ container_payload={+ "DockerId": "",+ "Name": cdef["name"],+ "Image": cdef["image"],+ "Labels": {+ "com.amazonaws.ecs.task-arn": task_arn,+ "com.amazonaws.ecs.container-name": cdef["name"],+ "com.amazonaws.ecs.task-definition-family": td.get("family", ""),+ "com.amazonaws.ecs.task-definition-version": str(td.get("revision", 1)),+ "com.amazonaws.ecs.cluster": cluster_arn,+ },+ "DesiredStatus": "RUNNING",+ "KnownStatus": "RUNNING",+ "Type": "NORMAL",+ },+ )+ return token+++def _docker_binds_from_taskdef(td, cdef):+ """Translate task-def `volumes` + container `mountPoints` into Docker+ bind strings. Returns a list (not a dict) so two ECS volume entries+ sharing the same host SourcePath don't collide on dict-key dedup.+ """+ vol_src = {}+ for v in td.get("volumes", []):+ name = v.get("Name") or v.get("name")+ if not name:+ continue+ host = v.get("Host") or v.get("host") or {}+ vol_src[name] = host.get("SourcePath") or host.get("sourcePath")+ binds = []+ for mp in cdef.get("mountPoints", []):+ src = vol_src.get(mp.get("sourceVolume"))+ cp = mp.get("containerPath")+ if src and cp:+ mode = "ro" if mp.get("readOnly", False) else "rw"+ binds.append(f"{src}:{cp}:{mode}")+ return binds+++def _build_run_kwargs(cdef, td, env, port_bindings, ecs_network,+ host_mode, task_id, task_arn, ministack_net_ip):+ """Build kwargs for docker_client.containers.run from a container+ definition + task definition (privileged, cap_add, pid_mode, networking,+ bind mounts).+ """+ lp = cdef.get("linuxParameters") or cdef.get("LinuxParameters") or {}+ caps = lp.get("Capabilities") or lp.get("capabilities") or {}+ cap_add = caps.get("Add") or caps.get("add") or []+ binds = _docker_binds_from_taskdef(td, cdef)++ kwargs = dict(+ detach=True,+ environment=env,+ ports=port_bindings or None,+ name=f"ministack-ecs-{task_id[:8]}-{cdef['name']}",+ labels={"ministack": "ecs", "task_arn": task_arn},+ command=cdef.get("command"),+ privileged=bool(cdef.get("privileged") or cdef.get("Privileged")),+ )+ if binds:+ kwargs["volumes"] = binds+ if cap_add:+ kwargs["cap_add"] = cap_add+ if td.get("pidMode") == "host":+ kwargs["pid_mode"] = "host"+ if host_mode:+ kwargs["network_mode"] = "host"+ else:+ kwargs["network"] = ecs_network+ if not ministack_net_ip:+ # Docker-Desktop fallback: when we couldn't discover Ministack's+ # IP on the shared network, route via host.docker.internal.+ kwargs["extra_hosts"] = {"host.docker.internal": "host-gateway"}+ return kwargs++def _run_task(data):cluster_name = _resolve_cluster_name(data.get("cluster", "default"))if cluster_name not in _clusters:@@ -932,12 +1045,22 @@ def _run_task(data):# Detect the Docker network Ministack is running on,# so ECS containers can reach sibling services (S3, etc.)ecs_network = None+ ministack_net_ip = Nonetry:self_container = docker_client.containers.get(os.environ.get("HOSTNAME", ""))- nets = list(self_container.attrs["NetworkSettings"]["Networks"].keys())+ nets = self_container.attrs["NetworkSettings"]["Networks"]if nets:- ecs_network = nets[0]- logger.debug("ECS: detected Ministack network: %s", ecs_network)+ ecs_network = next(iter(nets))+ # IP that ECS containers should use to reach Ministack.+ # Using ministack's own address on the shared network is+ # the only thing that works reliably on Linux Docker —+ # `host-gateway` magic resolves to 172.17.0.1 (docker0),+ # which iptables typically blocks from a sibling bridge.+ ministack_net_ip = nets[ecs_network].get("IPAddress") or None+ logger.debug(+ "ECS: detected Ministack network=%s ip=%s",+ ecs_network, ministack_net_ip,+ )except Exception:logger.debug("ECS: could not detect Ministack network, using default")@@ -956,21 +1079,26 @@ def _run_task(data):host_port = pm.get("hostPort", pm.get("containerPort"))port_bindings[f"{pm['containerPort']}/tcp"] = host_port+ host_mode = td.get("networkMode") == "host"+ metadata_token = _register_metadata(+ task_arn, _clusters[cluster_name]["clusterArn"],+ td, cdef, launch_type, env, host_mode, ministack_net_ip,+ )+ run_kwargs = _build_run_kwargs(+ cdef, td, env, port_bindings, ecs_network,+ host_mode, task_id, task_arn, ministack_net_ip,+ )+try:- container = docker_client.containers.run(- cdef["image"], detach=True,- environment=env,- ports=port_bindings or None,- name=f"ministack-ecs-{task_id[:8]}-{cdef['name']}",- labels={"ministack": "ecs", "task_arn": task_arn},- network=ecs_network,- command=cdef["command"]- )+ container = docker_client.containers.run(cdef["image"], **run_kwargs)task["_docker_ids"].append(container.id)+ ecs_metadata.set_docker_id(metadata_token, container.id)+ task.setdefault("_metadata_tokens", []).append(metadata_token)if i < len(task["containers"]):task["containers"][i]["runtimeId"] = container.id[:12]logger.info("ECS: started container %s for task %s", cdef['image'], task_id[:8])except Exception as e:+ ecs_metadata.unregister_token(metadata_token)logger.warning("ECS: Docker run failed for %s: %s", cdef.get('image'), e)_tasks[task_arn] = task@@ -1005,6 +1133,9 @@ def _stop_task(data):except Exception as e:logger.warning("ECS: failed to stop container %s: %s", docker_id, e)+ for tok in task.get("_metadata_tokens", []):+ ecs_metadata.unregister_token(tok)+now = _iso()task["lastStatus"] = "STOPPED"task["desiredStatus"] = "STOPPED"diff --git a/ministack/services/ecs_metadata.py b/ministack/services/ecs_metadata.pynew file mode 100644index 00000000..1867a6bb--- /dev/null+++ b/ministack/services/ecs_metadata.py@@ -0,0 +1,100 @@+"""ECS Task Metadata V4 emulator.++Real ECS injects ECS_CONTAINER_METADATA_URI_V4=http://169.254.170.2/v4/<token>+per container; ministack instead serves the same routes off the gateway port,+keyed by tokens registered from services/ecs.py. State is volatile by design+(stripped on persistence; reset() called by /_ministack/reset).+"""++import logging+import re+import threading++from ministack.core.responses import json_response++logger = logging.getLogger("ecs_metadata")++# task_arn -> task_payload (Containers list shared by all sibling tokens)+_TASKS: dict[str, dict] = {}+# token -> task_arn+_TOKEN_TO_TASK: dict[str, str] = {}+# token -> container_payload (an entry inside _TASKS[arn]["Containers"])+_TOKEN_TO_CONTAINER: dict[str, dict] = {}+_LOCK = threading.Lock()++_PATH_RE = re.compile(r"^/v4/(?P<token>[A-Za-z0-9_-]{8,})(?P<rest>/.*)?$")+++def register_container(+ token: str, task_arn: str, task_payload: dict, container_payload: dict+) -> None:+ """Register a container under a task. The first call for a task_arn seeds+ the task payload; subsequent calls just append to its Containers list, so+ /task returns every sibling container regardless of which token was used.+ """+ with _LOCK:+ task = _TASKS.get(task_arn)+ if task is None:+ task = dict(task_payload)+ task.setdefault("Containers", [])+ _TASKS[task_arn] = task+ task["Containers"].append(container_payload)+ _TOKEN_TO_TASK[token] = task_arn+ _TOKEN_TO_CONTAINER[token] = container_payload+ logger.debug(+ "registered metadata token for task=%s container=%s",+ task_arn,+ container_payload.get("Name"),+ )+++def unregister_token(token: str) -> None:+ with _LOCK:+ arn = _TOKEN_TO_TASK.pop(token, None)+ container = _TOKEN_TO_CONTAINER.pop(token, None)+ if not arn:+ return+ task = _TASKS.get(arn)+ if task and container is not None:+ try:+ task["Containers"].remove(container)+ except ValueError:+ pass+ if task is not None and not task.get("Containers"):+ _TASKS.pop(arn, None)+ logger.debug("unregistered metadata token for task=%s", arn)+++def set_docker_id(token: str, docker_id: str) -> None:+ with _LOCK:+ if container := _TOKEN_TO_CONTAINER.get(token):+ container["DockerId"] = docker_id+++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):+ m = _PATH_RE.match(path)+ if not m:+ return json_response({"message": "not found"}, status=404)+ token = m.group("token")+ with _LOCK:+ arn = _TOKEN_TO_TASK.get(token)+ if not arn:+ return json_response({"message": "unknown token"}, status=404)+ container = _TOKEN_TO_CONTAINER[token]+ task = _TASKS[arn]++ rest = (m.group("rest") or "").rstrip("/")+ if rest == "":+ return json_response(container)+ if rest == "/task":+ return json_response(task)+ if rest in ("/stats", "/task/stats"):+ return json_response({})+ return json_response({"message": "not found"}, status=404)diff --git a/tests/test_ecs.py b/tests/test_ecs.pyindex 9d29a600..b9c86bed 100644--- a/tests/test_ecs.py+++ b/tests/test_ecs.py@@ -120,6 +120,54 @@ def test_ecs_run_task_network_connectivity(ecs):breakassert success, "Task should transition to STOPPED"+def test_ecs_run_task_metadata_v4(ecs):+ """Container can resolve and read its V4 task-metadata URI end-to-end.++ Proves the full wiring: env-var injection in _run_task, the+ host.docker.internal/host-gateway extra_hosts mapping, the gateway+ routing /v4/<token>/task to ecs_metadata.handle_request, and the task+ payload containing the Containers array.+ """+ ecs.create_cluster(clusterName="metadata-test")+ ecs.register_task_definition(+ family="metadata-probe",+ containerDefinitions=[+ {+ "name": "probe",+ "image": "alpine:latest",+ # wget -O /tmp/r exits 0 only if the URI is reachable and+ # returns 200; grep then proves the body is the V4 task+ # shape (with a Containers array) rather than something+ # else returning 200.+ "command": [+ "sh", "-c",+ 'wget -q -O /tmp/r "$ECS_CONTAINER_METADATA_URI_V4/task" '+ '&& grep -q \'"Containers"\' /tmp/r',+ ],+ "essential": True,+ }+ ],+ )+ resp = ecs.run_task(cluster="metadata-test", taskDefinition="metadata-probe")+ task_arn = resp["tasks"][0]["taskArn"]+ assert resp["tasks"][0]["lastStatus"] == "RUNNING"++ success = False+ for _ in range(30):+ time.sleep(2)+ desc = ecs.describe_tasks(cluster="metadata-test", tasks=[task_arn])+ task = desc["tasks"][0]+ if task["lastStatus"] == "STOPPED":+ exit_code = task["containers"][0].get("exitCode")+ assert exit_code == 0, (+ f"Container could not read ECS_CONTAINER_METADATA_URI_V4/task "+ f"(exit code {exit_code}) — env-var injection, host-gateway "+ "mapping, or the /v4/<token> route may be broken"+ )+ success = True+ break+ assert success, "Task should transition to STOPPED"+def test_ecs_service(ecs):ecs.create_service(cluster="test-cluster",diff --git a/tests/test_ecs_metadata.py b/tests/test_ecs_metadata.pynew file mode 100644index 00000000..51d7c9c9--- /dev/null+++ b/tests/test_ecs_metadata.py@@ -0,0 +1,160 @@+"""Unit tests for the ECS Task Metadata V4 emulator (services/ecs_metadata.py).++These exercise the registry + handler directly, without a running Docker+container or boto client, since the module is reachable only from inside an+ECS task in production.+"""++import asyncio+import json++import pytest++from ministack.services import ecs_metadata+++def _call(method, path):+ status, _headers, body = asyncio.run(+ ecs_metadata.handle_request(method, path, {}, b"", {})+ )+ payload = json.loads(body) if body else None+ return status, payload++[email protected](autouse=True)+def _reset_registry():+ ecs_metadata.reset()+ yield+ ecs_metadata.reset()+++def _register(token, task_arn, container_name, **container_overrides):+ container = {+ "DockerId": "",+ "Name": container_name,+ "Image": "alpine:latest",+ "Labels": {"com.amazonaws.ecs.task-arn": task_arn},+ "DesiredStatus": "RUNNING",+ "KnownStatus": "RUNNING",+ "Type": "NORMAL",+ }+ container.update(container_overrides)+ ecs_metadata.register_container(+ token,+ task_arn,+ task_payload={+ "Cluster": "arn:aws:ecs:us-east-1:000000000000:cluster/c",+ "TaskARN": task_arn,+ "Family": "fam",+ "Revision": "1",+ "DesiredStatus": "RUNNING",+ "KnownStatus": "RUNNING",+ "AvailabilityZone": "us-east-1a",+ "LaunchType": "FARGATE",+ },+ container_payload=container,+ )+++def test_unknown_path_returns_404():+ status, body = _call("GET", "/v4/")+ assert status == 404+ assert body["message"] == "not found"+++def test_unknown_token_returns_404():+ status, body = _call("GET", "/v4/abcdefgh/task")+ assert status == 404+ assert body["message"] == "unknown token"+++def test_root_returns_container_payload():+ _register("tok-aaaaaaaa", "arn:task/1", "web", DockerId="d1")+ status, body = _call("GET", "/v4/tok-aaaaaaaa")+ assert status == 200+ assert body["Name"] == "web"+ assert body["DockerId"] == "d1"+++def test_task_endpoint_lists_all_sibling_containers():+ _register("tok-aaaaaaaa", "arn:task/1", "web")+ _register("tok-bbbbbbbb", "arn:task/1", "sidecar")+ _register("tok-cccccccc", "arn:task/2", "other")++ status, body = _call("GET", "/v4/tok-aaaaaaaa/task")+ assert status == 200+ names = {c["Name"] for c in body["Containers"]}+ assert names == {"web", "sidecar"}++ # Task 2 sees only its own container.+ status, body = _call("GET", "/v4/tok-cccccccc/task")+ assert status == 200+ assert [c["Name"] for c in body["Containers"]] == ["other"]+++def test_set_docker_id_mutates_container_payload():+ _register("tok-aaaaaaaa", "arn:task/1", "web")+ ecs_metadata.set_docker_id("tok-aaaaaaaa", "deadbeef")+ _, body = _call("GET", "/v4/tok-aaaaaaaa")+ assert body["DockerId"] == "deadbeef"+++def test_set_docker_id_unknown_token_is_noop():+ # Should not raise; just does nothing.+ ecs_metadata.set_docker_id("tok-zzzzzzzz", "x")+++def test_stats_endpoints_return_empty_object():+ _register("tok-aaaaaaaa", "arn:task/1", "web")+ for path in ("/v4/tok-aaaaaaaa/stats", "/v4/tok-aaaaaaaa/task/stats"):+ status, body = _call("GET", path)+ assert status == 200+ assert body == {}+++def test_unregister_removes_only_that_container():+ _register("tok-aaaaaaaa", "arn:task/1", "web")+ _register("tok-bbbbbbbb", "arn:task/1", "sidecar")++ ecs_metadata.unregister_token("tok-aaaaaaaa")++ status, _ = _call("GET", "/v4/tok-aaaaaaaa")+ assert status == 404++ status, body = _call("GET", "/v4/tok-bbbbbbbb/task")+ assert status == 200+ assert [c["Name"] for c in body["Containers"]] == ["sidecar"]+++def test_unregister_last_token_drops_task_entry():+ _register("tok-aaaaaaaa", "arn:task/1", "web")+ ecs_metadata.unregister_token("tok-aaaaaaaa")+ # Internal: the task arn entry should be cleaned up so the registry+ # doesn't grow unbounded across run/stop cycles.+ assert "arn:task/1" not in ecs_metadata._TASKS+++def test_unregister_unknown_token_is_noop():+ ecs_metadata.unregister_token("tok-zzzzzzzz") # must not raise+++def test_reset_clears_all_state():+ _register("tok-aaaaaaaa", "arn:task/1", "web")+ _register("tok-bbbbbbbb", "arn:task/2", "other")+ ecs_metadata.reset()+ assert ecs_metadata._TASKS == {}+ assert ecs_metadata._TOKEN_TO_TASK == {}+ assert ecs_metadata._TOKEN_TO_CONTAINER == {}+++def test_path_regex_rejects_short_token():+ # Token must be at least 8 chars per the regex.+ status, _ = _call("GET", "/v4/short/task")+ assert status == 404+++def test_trailing_slash_on_root_is_tolerated():+ _register("tok-aaaaaaaa", "arn:task/1", "web")+ status, body = _call("GET", "/v4/tok-aaaaaaaa/")+ assert status == 200+ assert body["Name"] == "web"