Skip to content

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

add /v2/credentials endpoint and inject container env for ECS tasks (#634)

Yakir Orenec5a4e65627c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aaa4b405..94b4e0a5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,16 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [Unreleased]
+
+### Added
+- **ECS task IAM role credentials endpoint (`GET /v2/credentials/<uuid>`)** — real ECS injects `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/v2/credentials/<uuid>` per task and SDKs fetch credentials by GETting that path against `169.254.170.2`. MiniStack now serves the same path on the gateway and returns the IMDS-shape credentials document (`Code`, `LastUpdated`, `Type`, `AccessKeyId`, `SecretAccessKey`, `Token`, `Expiration`); the path-`<uuid>` segment is opaque and treated as the auth token, mirroring real ECS.
+- **ECS task env injection for SDK-driven workloads** — tasks launched by MiniStack's ECS emulator now also get `AWS_CONTAINER_CREDENTIALS_FULL_URI` (so SDKs in task containers fetch emulated credentials automatically from the new `/v2/credentials/<uuid>` endpoint), `AWS_CONTAINER_AUTHORIZATION_TOKEN` (satisfies botocore's allow-list when the gateway host is not loopback, e.g. `host.docker.internal` or a Docker bridge IP), and `AWS_ENDPOINT_URL` (so SDK service calls auto-route to the gateway). Together with the existing `ECS_CONTAINER_METADATA_URI_V4`, unmodified AWS SDKs running inside an emulated ECS task now use MiniStack end-to-end with no client config.
+
+### Fixed
+- **ECS `connectivityAt` and `stoppingAt` timestamps wire-formatted as numbers** — both fields are set on tasks but were missing from the `_ECS_TIMESTAMP_FIELDS` normalization set, so they shipped as ISO strings in `DescribeTasks` / `ListTasks` responses. The Go AWS SDK v2 (which strictly requires `Timestamp` to be a JSON number under the JSON 1.1 protocol) rejected the response with `deserialization failed, expected Timestamp to be a JSON Number, got string instead`. boto3 is lenient and accepted the strings, hiding the issue. Both fields are now epoch-normalized alongside the other task timestamps.
+- **CloudFormation `AWS::ECS::TaskDefinition` populates `registeredAt`, `registeredBy`, and `compatibilities`** — the CFN provisioner constructed the task-definition record without these three fields, so `DescribeTaskDefinition` returned them as missing for CFN-created TDs even though the equivalent CLI/SDK path (`RegisterTaskDefinition`) always set them. Workloads that read `registeredAt` (e.g. the ARMO ECS operator and other reconcilers) had to fall back to "now". The CFN path now mirrors the CLI path and emits the same three fields with the same values.
+
## [1.3.37] — 2026-05-12
### Added
diff --git a/README.md b/README.md
index a13c1c8a..6657f11c 100644
--- a/README.md
+++ b/README.md
@@ -354,6 +354,7 @@ subnet = ec2.create_subnet(
| **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`) |
+| **ECS Container Credentials** | `GET /v2/credentials/<uuid>` | The path real ECS exposes via `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/v2/credentials/<uuid>` (resolved by SDKs against `169.254.170.2`). MiniStack serves the same path on the gateway and returns the IMDS-shape credentials document (`Code`, `LastUpdated`, `Type`, `AccessKeyId`, `SecretAccessKey`, `Token`, `Expiration`). `RunTask` injects `AWS_CONTAINER_CREDENTIALS_FULL_URI`, `AWS_CONTAINER_AUTHORIZATION_TOKEN` (satisfies botocore's allow-list for non-loopback gateway hosts), and `AWS_ENDPOINT_URL` so unmodified SDKs inside the task fetch credentials and route service calls through MiniStack with no client config |
| **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 |
@@ -643,7 +644,12 @@ 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.
+`GET $ECS_CONTAINER_METADATA_URI_V4/task`) works without changes. Alongside it,
+`RunTask` injects `AWS_CONTAINER_CREDENTIALS_FULL_URI`,
+`AWS_CONTAINER_AUTHORIZATION_TOKEN`, and `AWS_ENDPOINT_URL` so unmodified AWS
+SDKs running inside the task fetch emulated credentials from the new
+`/v2/credentials/<uuid>` endpoint and route service calls through MiniStack
+end-to-end without any client config.
---
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 42a4ebc9..34ee99ab 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -771,6 +771,8 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
path_lower = path.lower()
if path_lower.startswith("/latest/"):
return "imds"
+ if path_lower.startswith("/v2/credentials"):
+ return "imds"
if path_lower.startswith("/v1/apis") or path_lower.startswith("/v1/tags/arn:aws:appsync"):
return "appsync"
if path_lower.startswith("/key-value-stores/"):
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index a8d14e8e..65711b8a 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -2107,13 +2107,15 @@ def _ecs_task_def_create(logical_id, props, stack_name):
revision = 1
td_key = f"{family}:{revision}"
arn = f"arn:aws:ecs:{get_region()}:{get_account_id()}:task-definition/{td_key}"
+ compat = props.get("RequiresCompatibilities", ["EC2"])
td = {
"taskDefinitionArn": arn,
"family": family,
"revision": revision,
"status": "ACTIVE",
"containerDefinitions": _normalize_container_defs(props.get("ContainerDefinitions", [])),
- "requiresCompatibilities": props.get("RequiresCompatibilities", ["EC2"]),
+ "requiresCompatibilities": compat,
+ "compatibilities": compat + (["EC2"] if "FARGATE" in compat and "EC2" not in compat else []),
"networkMode": props.get("NetworkMode", "bridge"),
"cpu": props.get("Cpu", "256"),
"memory": props.get("Memory", "512"),
@@ -2123,6 +2125,8 @@ def _ecs_task_def_create(logical_id, props, stack_name):
"pidMode": props.get("PidMode", ""),
"ipcMode": props.get("IpcMode", ""),
"placementConstraints": props.get("PlacementConstraints", []),
+ "registeredAt": now_iso(),
+ "registeredBy": f"arn:aws:iam::{get_account_id()}:root",
}
_ecs._task_defs[td_key] = td
_ecs._task_def_latest[family] = revision
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.py
index c144b67b..2b9d72c3 100644
--- a/ministack/services/ecs.py
+++ b/ministack/services/ecs.py
@@ -191,9 +191,9 @@ def _iso():
# ---------------------------------------------------------------------------
_ECS_TIMESTAMP_FIELDS = {
- "createdAt", "startedAt", "stoppedAt", "registeredAt",
+ "createdAt", "startedAt", "stoppedAt", "stoppingAt", "registeredAt",
"deregisteredAt", "updatedAt", "lastModified", "runningAt",
- "pullStartedAt", "pullStoppedAt", "executionStoppedAt",
+ "connectivityAt", "pullStartedAt", "pullStoppedAt", "executionStoppedAt",
}
@@ -879,6 +879,9 @@ def _register_metadata(task_arn, cluster_arn, td, cdef, launch_type, env,
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}"
+ 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}"
ecs_metadata.register_container(
token,
task_arn,
diff --git a/ministack/services/imds.py b/ministack/services/imds.py
index acec1859..10e4feb1 100644
--- a/ministack/services/imds.py
+++ b/ministack/services/imds.py
@@ -136,6 +136,11 @@ async def handle_request(method, path, headers, body, query_params):
method = method.upper()
path = path.rstrip("/") or path
+ if path.startswith("/v2/credentials/"):
+ if method != "GET":
+ return _text("Method Not Allowed", 405)
+ return _json_resp(_credentials_doc())
+
if path.startswith("/latest/api/token"):
if method != "PUT":
return _text("Method Not Allowed", 405)
diff --git a/tests/test_ecs.py b/tests/test_ecs.py
index b9c86bed..1fc77245 100644
--- a/tests/test_ecs.py
+++ b/tests/test_ecs.py
@@ -610,3 +610,36 @@ def test_ecs_cfn_service_visible(ecs, cfn):
# Cleanup
cfn.delete_stack(StackName=stack_name)
+
+
+def test_ecs_cfn_taskdef_populates_registered_fields(ecs, cfn):
+ """CFN-created TaskDefinitions must surface registeredAt/registeredBy/compatibilities,
+ matching what RegisterTaskDefinition emits. Workloads like Go-SDK reconcilers fall
+ back to time.Now() and emit warnings when registeredAt is missing."""
+ from datetime import datetime
+ stack_name = "ecs-cfn-td-fields"
+ template = json.dumps({
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "TaskDef": {
+ "Type": "AWS::ECS::TaskDefinition",
+ "Properties": {
+ "Family": "cfn-td-fields",
+ "ContainerDefinitions": [
+ {"Name": "app", "Image": "nginx", "Memory": 128},
+ ],
+ },
+ },
+ },
+ })
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ try:
+ td = ecs.describe_task_definition(taskDefinition="cfn-td-fields")["taskDefinition"]
+ assert isinstance(td.get("registeredAt"), datetime), \
+ f"registeredAt missing or wrong type: {td.get('registeredAt')!r}"
+ assert td.get("registeredBy", "").startswith("arn:aws:iam::"), \
+ f"registeredBy missing: {td.get('registeredBy')!r}"
+ assert "EC2" in td.get("compatibilities", []), \
+ f"compatibilities missing/empty: {td.get('compatibilities')!r}"
+ finally:
+ cfn.delete_stack(StackName=stack_name)
diff --git a/tests/test_imds.py b/tests/test_imds.py
index 6b1de5c5..fc9229f8 100644
--- a/tests/test_imds.py
+++ b/tests/test_imds.py
@@ -68,3 +68,26 @@ def test_imds_placement_region():
r = requests.get(f"{ENDPOINT}/latest/meta-data/placement/region")
assert r.status_code == 200
assert r.text.strip()
+
+
+def test_container_credentials_returns_imds_shape():
+ """ECS task role endpoint: AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/v2/credentials/<uuid>."""
+ r = requests.get(f"{ENDPOINT}/v2/credentials/68e5868d-1bde-4f9e-9921-6e0442cb567b")
+ assert r.status_code == 200
+ doc = r.json()
+ assert doc["Code"] == "Success"
+ assert doc["Type"] == "AWS-HMAC"
+ for k in ("AccessKeyId", "SecretAccessKey", "Token", "Expiration", "LastUpdated"):
+ assert k in doc and doc[k]
+
+
+def test_container_credentials_requires_id_segment():
+ r = requests.get(f"{ENDPOINT}/v2/credentials/")
+ assert r.status_code == 404
+ r = requests.get(f"{ENDPOINT}/v2/credentials")
+ assert r.status_code == 404
+
+
+def test_container_credentials_rejects_non_get():
+ r = requests.post(f"{ENDPOINT}/v2/credentials/abc")
+ assert r.status_code == 405