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
feat: Terraform & CDK compatibility — S3 PublicAccessBlock, OwnershipControls, idempotent CreateBucket, S3 Control tags, STS AssumeRoleWithWebIdentity, IAM UpdateRole, unsigned body routing fix — v1.1.10, 737 tests (#44)
Nahuel Nuceraecaae022c3bb
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 96b00a99..201fc5e2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -37,7 +37,7 @@ jobs:run: |REDIS_HOST=localhost python -m uvicorn ministack.app:app --host 0.0.0.0 --port 4566 &sleep 3- curl -sf http://localhost:4566/_localstack/health+ curl -sf http://localhost:4566/_ministack/health- name: Run testsrun: pytest tests/ -v --tb=shortdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex ff4b6e1d..140eebb8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,24 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [1.1.10] — 2026-03-31++### Fixed+- **ECS Docker network detection** — ECS containers now automatically join the same Docker network that MiniStack is running on, so containers can reach sibling services (S3, SQS, etc.) without manual network configuration+- **Internal naming cleanup** — replaced all internal `localstack-*` references (logger name, default data dir `/tmp/localstack-data/s3` → `/tmp/ministack-data/s3`, healthcheck URLs, CI config) with `ministack` equivalents; `LOCALSTACK_PERSISTENCE` / `LOCALSTACK_HOSTNAME` env vars kept for migration compatibility+- **DynamoDB GSI capacity accounting** — `PutItem`, `DeleteItem`, `UpdateItem`, `GetItem`, `Query`, `Scan`, and `BatchWriteItem` now return correct `ConsumedCapacity.CapacityUnits` when a table has Global Secondary Indexes: `1 + gsi_count` per write (matching real AWS); `INDEXES` mode also returns per-GSI breakdown. Contributed by @jespinoza-shippo.+- **S3 `CreateBucket` idempotency** — creating a bucket you already own now returns 200 instead of 409 `BucketAlreadyOwnedByYou`, matching real AWS and fixing Terraform re-apply failures+- **S3 `OwnershipControls`** — `PutBucketOwnershipControls`, `GetBucketOwnershipControls`, `DeleteBucketOwnershipControls` now implemented; Terraform calls these immediately after `CreateBucket`+- **S3 Control `ListTagsForResource`** — S3 Control API (`/v20180820/tags/{arn}`) now returns empty tag list instead of 404; Terraform uses this for S3 bucket tag lookups+- **S3 `PublicAccessBlock`** — `PutPublicAccessBlock`, `GetPublicAccessBlock`, `DeletePublicAccessBlock` now implemented; CDK and Terraform call these on every bucket+- **STS `AssumeRoleWithWebIdentity`** — now implemented; CDK OIDC deployments (GitHub Actions, etc.) use this; also fixed router to detect unsigned form-encoded STS actions from request body+- **IAM `UpdateRole`** — now implemented; Terraform calls this to set role description and max session duration++### Tests+- 737 tests total, all passing++---+## [1.1.9] — 2026-03-31### Added@@ -45,7 +63,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [1.1.7] — 2026-03-30### Added-- **Athena engine control** — new `ATHENA_ENGINE` env var (`auto` | `duckdb` | `mock`) to select the SQL backend at startup; `auto` keeps existing behaviour (DuckDB if installed, mock otherwise). New `/_ministack/config` endpoint accepts `POST {"athena.ATHENA_ENGINE": "mock"}` to switch engines at runtime without restart — useful in CI to force mock mode without DuckDB installed. Contributed by @jespinoza-shippo.+- **Athena engine control** — new `ATHENA_ENGINE` env var (`auto` | `duckdb` | `mock`) to select the SQL backend at startup; `auto` keeps existing behaviour (DuckDB if installed, mock otherwise). New `/_ministack/config` endpoint accepts `POST {"athena.ATHENA_ENGINE": "mock"}` to switch engines at runtime without restart — useful in CI to force mock mode without DuckDB installed.- **VPC gap coverage** — 6 new EC2 resource types, 22 new actions, 11 new tests- **NAT Gateways**: `CreateNatGateway`, `DescribeNatGateways`, `DeleteNatGateway` — supports `SubnetId`, `ConnectivityType` (public/private), state transitions, `vpc-id`/`subnet-id`/`state` filters- **Network ACLs**: `CreateNetworkAcl`, `DescribeNetworkAcls`, `DeleteNetworkAcl`, `CreateNetworkAclEntry`, `DeleteNetworkAclEntry`, `ReplaceNetworkAclEntry`, `ReplaceNetworkAclAssociation` — full CRUD with rule entries and subnet associations@@ -55,7 +73,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **Egress-Only Internet Gateways**: `CreateEgressOnlyInternetGateway`, `DescribeEgressOnlyInternetGateways`, `DeleteEgressOnlyInternetGateway` — IPv6 egress-only IGW for VPCs### Fixed-- **SQS `awsQueryCompatible` header** — all SQS JSON error responses now include the `x-amzn-query-error: <legacy_code>;<fault>` header required by the `awsQueryCompatible` service trait. botocore reads this header and overrides `Error.Code` with the legacy `AWS.SimpleQueueService.*` namespaced code (e.g. `AWS.SimpleQueueService.NonExistentQueue` instead of `QueueDoesNotExist`). Without this header, any SDK code that matched against the legacy string worked against real AWS but silently failed against MiniStack. Full mapping of all 28 SQS error shapes sourced from `aws-sdk-go` ErrCode constants.+- **SQS `awsQueryCompatible` header** — all SQS JSON error responses now include the `x-amzn-query-error: <legacy_code>;<fault>` header required by the `awsQueryCompatible` service trait. botocore reads this header and overrides `Error.Code` with the legacy `AWS.SimpleQueueService.*` namespaced code (e.g. `AWS.SimpleQueueService.NonExistentQueue` instead of `QueueDoesNotExist`). Without this header, any SDK code that matched against the legacy string worked against real AWS but silently failed against MiniStack. Full mapping of all 28 SQS error shapes sourced from `aws-sdk-go` ErrCode constants. Contributed by @jespinoza-shippo.### Tests- 708 integration tests — all passingdiff --git a/Dockerfile b/Dockerfileindex 463f0bcc..fcb6a37f 100644--- a/Dockerfile+++ b/Dockerfile@@ -18,14 +18,14 @@ RUN pip install --no-cache-dir --upgrade pip && \COPY ministack/ ministack/RUN addgroup -S ministack && adduser -S ministack -G ministack-RUN mkdir -p /tmp/localstack-data/s3 && chown -R ministack:ministack /tmp/localstack-data+RUN mkdir -p /tmp/ministack-data/s3 && chown -R ministack:ministack /tmp/ministack-dataRUN mkdir -p /docker-entrypoint-initaws.d && chown ministack:ministack /docker-entrypoint-initaws.dVOLUME /docker-entrypoint-initaws.dENV GATEWAY_PORT=4566 \LOG_LEVEL=INFO \S3_PERSIST=0 \- S3_DATA_DIR=/tmp/localstack-data/s3 \+ S3_DATA_DIR=/tmp/ministack-data/s3 \REDIS_HOST=redis \REDIS_PORT=6379 \RDS_BASE_PORT=15432 \@@ -37,6 +37,6 @@ EXPOSE 4566# Pure Python healthcheck — no curl dependencyHEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \- CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:4566/_localstack/health')" || exit 1+ CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:4566/_ministack/health')" || exit 1ENTRYPOINT ["python", "-m", "uvicorn", "ministack.app:app", "--host", "0.0.0.0", "--port", "4566"]diff --git a/Makefile b/Makefileindex cb7a010c..8930b319 100644--- a/Makefile+++ b/Makefile@@ -19,7 +19,7 @@ run: build-v /var/run/docker.sock:/var/run/docker.sock \$(IMAGE_NAME)@echo "MiniStack running on http://localhost:$(PORT)"- @echo "Health: http://localhost:$(PORT)/_localstack/health"+ @echo "Health: http://localhost:$(PORT)/_ministack/health"run-compose:docker compose up -d --build@@ -36,13 +36,13 @@ logs:docker logs -f $(CONTAINER_NAME)health:- @curl -s http://localhost:$(PORT)/_localstack/health | python3 -m json.tool+ @curl -s http://localhost:$(PORT)/_ministack/health | python3 -m json.tooltest: stop run@echo "Waiting for ministack to be ready..."@READY=0; \for i in $$(seq 1 30); do \- if curl -sf http://localhost:$(PORT)/_localstack/health > /dev/null 2>&1; then \+ if curl -sf http://localhost:$(PORT)/_ministack/health > /dev/null 2>&1; then \echo "Ready after $$i second(s)."; READY=1; break; \fi; \sleep 1; \diff --git a/README.md b/README.mdindex 90602781..375f097b 100644--- a/README.md+++ b/README.md@@ -374,7 +374,7 @@ ecs.stop_task(cluster="dev", task=task_arn)| `MINISTACK_HOST` | `localhost` | Hostname used in SQS queue URLs returned to clients || `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING`, `ERROR` || `S3_PERSIST` | `0` | Set `1` to persist S3 objects to disk |-| `S3_DATA_DIR` | `/tmp/localstack-data/s3` | S3 persistence directory |+| `S3_DATA_DIR` | `/tmp/ministack-data/s3` | S3 persistence directory || `REDIS_HOST` | `redis` | Redis host for ElastiCache fallback || `REDIS_PORT` | `6379` | Redis port for ElastiCache fallback || `RDS_BASE_PORT` | `15432` | Starting host port for RDS containers |@@ -467,20 +467,20 @@ pip install boto3 pytest duckdb docker cbor2# Start MiniStackdocker compose up -d-# Run the full test suite (730 tests across all 30 services)+# Run the full test suite (737 tests across all 30 services)pytest tests/ -v```Expected output:```-collected 730 items+collected 737 itemstests/test_services.py::test_s3_create_bucket PASSED...tests/test_services.py::test_app_asgi_callable PASSED-730 passed in ~60s+737 passed in ~60s```---diff --git a/docker-compose.yml b/docker-compose.ymlindex 48ccd092..ee335f7c 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -16,13 +16,13 @@ services:- RDS_BASE_PORT=15432- ELASTICACHE_BASE_PORT=16379volumes:- - ./data/s3:/tmp/localstack-data/s3+ - ./data/s3:/tmp/ministack-data/s3- /var/run/docker.sock:/var/run/docker.sockdepends_on:redis:condition: service_healthyhealthcheck:- test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:4566/_localstack/health')"]+ test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:4566/_ministack/health')"]interval: 10stimeout: 3sretries: 3diff --git a/ministack/app.py b/ministack/app.pyindex 5a63e576..7a3bdf87 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -206,6 +206,22 @@ async def app(scope, receive, send):json.dumps({"applied": applied}).encode())return+ # S3 Control API — /v20180820/... with x-amz-account-id header+ if path.startswith("/v20180820/"):+ if method == "GET" and path.startswith("/v20180820/tags/"):+ # ListTagsForResource — return empty tag set+ await _send_response(send, 200, {+ "Content-Type": "application/json",+ "x-amzn-requestid": request_id,+ }, json.dumps({"Tags": []}).encode())+ else:+ # All other S3 Control operations — accept silently+ await _send_response(send, 200, {+ "Content-Type": "application/json",+ "x-amzn-requestid": request_id,+ }, b"{}")+ return+if path in ("/_localstack/health", "/health", "/_ministack/health"):await _send_response(send, 200, {"Content-Type": "application/json",@@ -321,7 +337,15 @@ async def app(scope, receive, send):await _send_response(send, status, resp_headers, resp_body)return- service = detect_service(method, path, headers, query_params)+ # For unsigned form-encoded requests (e.g. STS AssumeRoleWithWebIdentity),+ # Action is in the body not the query string — merge it in for routing only.+ routing_params = query_params+ if not query_params.get("Action") and headers.get("content-type", "").startswith("application/x-www-form-urlencoded"):+ body_params = parse_qs(body.decode("utf-8", errors="replace"), keep_blank_values=True)+ if body_params.get("Action"):+ routing_params = {**query_params, "Action": body_params["Action"]}++ service = detect_service(method, path, headers, routing_params)region = extract_region(headers)logger.debug(f"{method} {path} -> service={service} region={region}")diff --git a/ministack/core/router.py b/ministack/core/router.pyindex a1b8ba8b..464f4bf7 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -10,7 +10,7 @@ Routes incoming requests to the correct service handler based on:import loggingimport re-logger = logging.getLogger("localstack-clone")+logger = logging.getLogger("ministack")# Service detection patternsSERVICE_PATTERNS = {@@ -231,7 +231,8 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"SimulatePrincipalPolicy": "iam", "SimulateCustomPolicy": "iam",# STS actions"GetCallerIdentity": "sts", "AssumeRole": "sts",- "GetSessionToken": "sts",+ "GetSessionToken": "sts", "AssumeRoleWithWebIdentity": "sts",+ "AssumeRoleWithSAML": "sts",# CloudWatch actions"PutMetricData": "monitoring", "GetMetricData": "monitoring","ListMetrics": "monitoring", "PutMetricAlarm": "monitoring",diff --git a/ministack/services/athena.py b/ministack/services/athena.pyindex 8d13c600..bf8a6ca2 100644--- a/ministack/services/athena.py+++ b/ministack/services/athena.py@@ -26,7 +26,7 @@ logger = logging.getLogger("athena")ACCOUNT_ID = "000000000000"REGION = "us-east-1"-S3_DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/localstack-data/s3")+S3_DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/ministack-data/s3")ATHENA_ENGINE = os.environ.get("ATHENA_ENGINE", "auto") # "auto" | "duckdb" | "mock"diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex f30949a4..3451218c 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -300,7 +300,7 @@ def _put_item(data):result = {}if data.get("ReturnValues") == "ALL_OLD" and old_item:result["Attributes"] = old_item- _add_consumed_capacity(result, data, name)+ _add_consumed_capacity(result, data, name, write=True)return json_response(result)@@ -347,7 +347,7 @@ def _delete_item(data):result = {}if data.get("ReturnValues") == "ALL_OLD" and old_item:result["Attributes"] = old_item- _add_consumed_capacity(result, data, name)+ _add_consumed_capacity(result, data, name, write=True)return json_response(result)@@ -392,7 +392,7 @@ def _update_item(data):result["Attributes"] = _diff_attributes(old_item, item, return_old=True)elif rv == "UPDATED_NEW":result["Attributes"] = _diff_attributes(old_item or {}, item, return_old=False)- _add_consumed_capacity(result, data, name)+ _add_consumed_capacity(result, data, name, write=True)return json_response(result)@@ -555,11 +555,20 @@ def _batch_write_item(data):result = {"UnprocessedItems": unprocessed}rc = data.get("ReturnConsumedCapacity", "NONE")if rc != "NONE":- result["ConsumedCapacity"] = [- {"TableName": t, "CapacityUnits": 1.0}- for t in request_items- if t in _tables- ]+ consumed = []+ for t, reqs in request_items.items():+ if t not in _tables:+ continue+ gsi_count = len(_tables[t].get("GlobalSecondaryIndexes", []))+ units = len(reqs) * (1.0 + gsi_count)+ entry = {"TableName": t, "CapacityUnits": units}+ if rc == "INDEXES" and gsi_count:+ entry["GlobalSecondaryIndexes"] = {+ gsi["IndexName"]: {"CapacityUnits": float(len(reqs))}+ for gsi in _tables[t].get("GlobalSecondaryIndexes", [])+ }+ consumed.append(entry)+ result["ConsumedCapacity"] = consumedreturn json_response(result)@@ -1670,13 +1679,21 @@ def _update_counts(table):table["TableSizeBytes"] = count * 200-def _add_consumed_capacity(result, data, table_name):+def _add_consumed_capacity(result, data, table_name, write=False):rc = data.get("ReturnConsumedCapacity", "NONE")if rc == "NONE":return- cap = {"TableName": table_name, "CapacityUnits": 1.0}+ table = _tables.get(table_name, {})+ gsi_count = len(table.get("GlobalSecondaryIndexes", [])) if write else 0+ units = 1.0 + gsi_count+ cap = {"TableName": table_name, "CapacityUnits": units}if rc == "INDEXES":cap["Table"] = {"CapacityUnits": 1.0}+ if write and gsi_count:+ cap["GlobalSecondaryIndexes"] = {+ gsi["IndexName"]: {"CapacityUnits": 1.0}+ for gsi in table.get("GlobalSecondaryIndexes", [])+ }result["ConsumedCapacity"] = capdiff --git a/ministack/services/glue.py b/ministack/services/glue.pyindex cd65d828..4483e277 100644--- a/ministack/services/glue.py+++ b/ministack/services/glue.py@@ -23,7 +23,7 @@ logger = logging.getLogger("glue")ACCOUNT_ID = "000000000000"REGION = "us-east-1"CRAWLER_RUN_SECONDS = int(os.environ.get("GLUE_CRAWLER_RUN_SECONDS", "5"))-S3_DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/localstack-data/s3")+S3_DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/ministack-data/s3")_databases: dict = {}_tables: dict = {} # "db_name/table_name" -> table dictdiff --git a/ministack/services/iam_sts.py b/ministack/services/iam_sts.pyindex f6edda9a..bcb0c1bc 100644--- a/ministack/services/iam_sts.py+++ b/ministack/services/iam_sts.py@@ -211,6 +211,18 @@ def _delete_role(p):return _xml(200, "DeleteRoleResponse", "", ns="iam")+def _update_role(p):+ name = _p(p, "RoleName")+ role = _roles.get(name)+ if not role:+ return _error(404, "NoSuchEntity", f"Role {name} not found.", ns="iam")+ if "Description" in p:+ role["Description"] = _p(p, "Description")+ if "MaxSessionDuration" in p:+ role["MaxSessionDuration"] = int(_p(p, "MaxSessionDuration", "3600"))+ return _xml(200, "UpdateRoleResponse", "<UpdateRoleResult></UpdateRoleResult>", ns="iam")++def _update_assume_role_policy(p):name = _p(p, "RoleName")if name not in _roles:@@ -1241,6 +1253,35 @@ async def handle_sts_request(method, path, headers, body, query_params):f"</AssumeRoleResult>",ns="sts")+ if action == "AssumeRoleWithWebIdentity":+ role_arn = _p(params, "RoleArn")+ session = _p(params, "RoleSessionName", "session")+ duration = int(_p(params, "DurationSeconds") or 3600)+ access_key = _gen_session_access_key()+ secret_key = _gen_secret()+ session_token = _gen_session_token()+ assumed_arn = role_arn.replace(":role/", ":assumed-role/", 1)+ if not assumed_arn.endswith(f"/{session}"):+ assumed_arn = f"{assumed_arn}/{session}"+ role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()+ return _xml(200, "AssumeRoleWithWebIdentityResponse",+ f"<AssumeRoleWithWebIdentityResult>"+ f"<Credentials>"+ f"<AccessKeyId>{access_key}</AccessKeyId>"+ f"<SecretAccessKey>{secret_key}</SecretAccessKey>"+ f"<SessionToken>{session_token}</SessionToken>"+ f"<Expiration>{_future(duration)}</Expiration>"+ f"</Credentials>"+ f"<AssumedRoleUser>"+ f"<AssumedRoleId>{role_id}:{session}</AssumedRoleId>"+ f"<Arn>{assumed_arn}</Arn>"+ f"</AssumedRoleUser>"+ f"<SubjectFromWebIdentityToken>test-subject</SubjectFromWebIdentityToken>"+ f"<Audience>sts.amazonaws.com</Audience>"+ f"<Provider>accounts.google.com</Provider>"+ f"</AssumeRoleWithWebIdentityResult>",+ ns="sts")+if action == "GetSessionToken":duration = int(_p(params, "DurationSeconds") or 43200)expiration = _future(duration)@@ -1431,6 +1472,7 @@ _IAM_HANDLERS = {"GetRole": _get_role,"ListRoles": _list_roles,"DeleteRole": _delete_role,+ "UpdateRole": _update_role,"CreatePolicy": _create_policy,"GetPolicy": _get_policy,"GetPolicyVersion": _get_policy_version,diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 019f0a8c..6575b7b3 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -76,7 +76,7 @@ _object_legal_hold: dict = {}_multipart_uploads: dict = {}-DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/localstack-data/s3")+DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/ministack-data/s3")PERSIST = os.environ.get("S3_PERSIST", "0") == "1"# Headers preserved from PUT requests and returned on GET/HEAD.@@ -404,6 +404,10 @@ def _dispatch(return _get_object_lock_configuration(bucket)if "replication" in query_params:return _get_bucket_replication(bucket)+ if "ownershipControls" in query_params:+ return _get_bucket_ownership_controls(bucket)+ if "publicAccessBlock" in query_params:+ return _get_public_access_block(bucket)return _list_objects_v1(bucket, query_params)if method == "PUT":@@ -435,6 +439,10 @@ def _dispatch(return _put_object_lock_configuration(bucket, body)if "replication" in query_params:return _put_bucket_replication(bucket, body)+ if "ownershipControls" in query_params:+ return _put_bucket_ownership_controls(bucket, body)+ if "publicAccessBlock" in query_params:+ return _put_public_access_block(bucket, body)return _create_bucket(bucket, body, headers)if method == "DELETE":@@ -452,6 +460,10 @@ def _dispatch(return _delete_bucket_website(bucket)if "replication" in query_params:return _delete_bucket_replication(bucket)+ if "ownershipControls" in query_params:+ return _delete_bucket_ownership_controls(bucket)+ if "publicAccessBlock" in query_params:+ return _delete_public_access_block(bucket)return _delete_bucket(bucket)if method == "HEAD":@@ -498,12 +510,8 @@ def _create_bucket(name: str, body: bytes, headers: dict = None):"InvalidBucketName", "The specified bucket is not valid.", 400, f"/{name}")if name in _buckets:- return _error(- "BucketAlreadyOwnedByYou",- "Your previous request to create the named bucket succeeded and you already own it.",- 409,- f"/{name}",- )+ # Idempotent: same account already owns it — return 200 like real AWS+ return 200, {"Location": f"/{name}"}, b""region = Noneif body:@@ -784,6 +792,61 @@ def _delete_bucket_tagging(name: str):return 204, {}, b""+def _put_bucket_ownership_controls(name: str, body: bytes):+ if name not in _buckets:+ return _no_such_bucket(name)+ _buckets[name]["_ownership_controls"] = body+ return 200, {}, b""+++def _get_bucket_ownership_controls(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ stored = _buckets[name].get("_ownership_controls")+ if stored:+ return 200, {"Content-Type": "application/xml"}, stored+ root = Element("OwnershipControls", xmlns=S3_NS)+ rule = SubElement(root, "Rule")+ SubElement(rule, "ObjectOwnership").text = "BucketOwnerEnforced"+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++def _delete_bucket_ownership_controls(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ _buckets[name].pop("_ownership_controls", None)+ return 204, {}, b""+++def _put_public_access_block(name: str, body: bytes):+ if name not in _buckets:+ return _no_such_bucket(name)+ _buckets[name]["_public_access_block"] = body+ return 200, {}, b""+++def _get_public_access_block(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ stored = _buckets[name].get("_public_access_block")+ if stored:+ return 200, {"Content-Type": "application/xml"}, stored+ # Default: all public access blocked+ root = Element("PublicAccessBlockConfiguration", xmlns=S3_NS)+ SubElement(root, "BlockPublicAcls").text = "true"+ SubElement(root, "IgnorePublicAcls").text = "true"+ SubElement(root, "BlockPublicPolicy").text = "true"+ SubElement(root, "RestrictPublicBuckets").text = "true"+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++def _delete_public_access_block(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ _buckets[name].pop("_public_access_block", None)+ return 204, {}, b""++def _get_bucket_notification(name: str):if name not in _buckets:return _no_such_bucket(name)diff --git a/pyproject.toml b/pyproject.tomlindex d0d49ce8..31d7d33f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.1.9"+version = "1.1.10"description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"readme = "README.md"license = { file = "LICENSE" }diff --git a/tests/test_services.py b/tests/test_services.pyindex d598afbb..aeca3dc4 100644--- a/tests/test_services.py+++ b/tests/test_services.py@@ -31,10 +31,9 @@ def test_s3_create_bucket(s3):def test_s3_create_bucket_already_exists(s3):+ # Real AWS: creating a bucket you already own is idempotent — returns 200s3.create_bucket(Bucket="intg-s3-dup")- with pytest.raises(ClientError) as exc:- s3.create_bucket(Bucket="intg-s3-dup")- assert exc.value.response["Error"]["Code"] == "BucketAlreadyOwnedByYou"+ s3.create_bucket(Bucket="intg-s3-dup") # must not raisedef test_s3_delete_bucket(s3):@@ -372,6 +371,37 @@ def test_s3_object_tagging(s3):assert tags["priority"] == "high"+def test_s3_public_access_block(s3):+ bkt = "intg-s3-pab"+ s3.create_bucket(Bucket=bkt)+ s3.put_public_access_block(+ Bucket=bkt,+ PublicAccessBlockConfiguration={+ "BlockPublicAcls": True,+ "IgnorePublicAcls": True,+ "BlockPublicPolicy": False,+ "RestrictPublicBuckets": False,+ },+ )+ resp = s3.get_public_access_block(Bucket=bkt)+ cfg = resp["PublicAccessBlockConfiguration"]+ assert cfg["BlockPublicAcls"] is True+ assert cfg["BlockPublicPolicy"] is False+ s3.delete_public_access_block(Bucket=bkt)+++def test_s3_ownership_controls(s3):+ bkt = "intg-s3-ownership"+ s3.create_bucket(Bucket=bkt)+ s3.put_bucket_ownership_controls(+ Bucket=bkt,+ OwnershipControls={"Rules": [{"ObjectOwnership": "BucketOwnerPreferred"}]},+ )+ resp = s3.get_bucket_ownership_controls(Bucket=bkt)+ assert resp["OwnershipControls"]["Rules"][0]["ObjectOwnership"] == "BucketOwnerPreferred"+ s3.delete_bucket_ownership_controls(Bucket=bkt)++def test_s3_object_lock_configuration(s3):bkt = "intg-s3-objlock-cfg"s3.create_bucket(@@ -1756,7 +1786,7 @@ def test_ecs_run_task_network_connectivity(ecs):"image": "alpine:latest","command": ["sh", "-c",- f"wget -q -O /dev/null {container_endpoint}/_localstack/health"+ f"wget -q -O /dev/null {container_endpoint}/_ministack/health"],"essential": True,}@@ -5998,7 +6028,7 @@ def test_apigw_http_protocol_type(apigw):def test_health_endpoint():import urllib.request- resp = urllib.request.urlopen("http://localhost:4566/_localstack/health")+ resp = urllib.request.urlopen("http://localhost:4566/_ministack/health")assert resp.status == 200data = json.loads(resp.read())assert "services" in data@@ -6026,6 +6056,35 @@ def test_sts_get_session_token(sts):assert "Expiration" in creds+def test_sts_assume_role_with_web_identity(sts, iam):+ iam.create_role(+ RoleName="test-oidc-role",+ AssumeRolePolicyDocument='{"Version":"2012-10-17","Statement":[]}',+ )+ role_arn = f"arn:aws:iam::000000000000:role/test-oidc-role"+ resp = sts.assume_role_with_web_identity(+ RoleArn=role_arn,+ RoleSessionName="ci-session",+ WebIdentityToken="fake-oidc-token-value",+ )+ creds = resp["Credentials"]+ assert "AccessKeyId" in creds+ assert "SecretAccessKey" in creds+ assert "SessionToken" in creds+ assert "Expiration" in creds+++def test_iam_update_role(iam):+ iam.create_role(+ RoleName="test-update-role",+ AssumeRolePolicyDocument='{"Version":"2012-10-17","Statement":[]}',+ )+ iam.update_role(RoleName="test-update-role", Description="updated desc", MaxSessionDuration=7200)+ resp = iam.get_role(RoleName="test-update-role")+ assert resp["Role"]["Description"] == "updated desc"+ assert resp["Role"]["MaxSessionDuration"] == 7200++# ========== DynamoDB TTL ==========@@ -14467,6 +14526,66 @@ def test_dynamodb_batch_write_consumed_capacity(ddb):ddb.delete_table(TableName="batch-cap-regression")+def test_dynamodb_put_item_gsi_capacity(ddb):+ """PutItem on a table with 1 GSI must return CapacityUnits=2.0 (table + GSI)."""+ ddb.create_table(+ TableName="gsi-cap-put",+ AttributeDefinitions=[+ {"AttributeName": "pk", "AttributeType": "S"},+ {"AttributeName": "sk", "AttributeType": "S"},+ {"AttributeName": "last_name", "AttributeType": "S"},+ ],+ KeySchema=[+ {"AttributeName": "pk", "KeyType": "HASH"},+ {"AttributeName": "sk", "KeyType": "RANGE"},+ ],+ GlobalSecondaryIndexes=[{+ "IndexName": "last_name-index",+ "KeySchema": [{"AttributeName": "last_name", "KeyType": "HASH"}],+ "Projection": {"ProjectionType": "ALL"},+ }],+ BillingMode="PAY_PER_REQUEST",+ )+ resp = ddb.put_item(+ TableName="gsi-cap-put",+ Item={"pk": {"S": "p1"}, "sk": {"S": "s1"}, "last_name": {"S": "Smith"}},+ ReturnConsumedCapacity="TOTAL",+ )+ assert resp["ConsumedCapacity"]["CapacityUnits"] == 2.0+ ddb.delete_table(TableName="gsi-cap-put")+++def test_dynamodb_batch_write_gsi_capacity(ddb):+ """BatchWriteItem with 2 items on a table with 1 GSI must return CapacityUnits=4.0."""+ ddb.create_table(+ TableName="gsi-cap-batch",+ AttributeDefinitions=[+ {"AttributeName": "pk", "AttributeType": "S"},+ {"AttributeName": "sk", "AttributeType": "S"},+ {"AttributeName": "age", "AttributeType": "N"},+ ],+ KeySchema=[+ {"AttributeName": "pk", "KeyType": "HASH"},+ {"AttributeName": "sk", "KeyType": "RANGE"},+ ],+ GlobalSecondaryIndexes=[{+ "IndexName": "age-index",+ "KeySchema": [{"AttributeName": "age", "KeyType": "HASH"}],+ "Projection": {"ProjectionType": "ALL"},+ }],+ BillingMode="PAY_PER_REQUEST",+ )+ resp = ddb.batch_write_item(+ RequestItems={"gsi-cap-batch": [+ {"PutRequest": {"Item": {"pk": {"S": "p2"}, "sk": {"S": "s2"}, "age": {"N": "25"}}}},+ {"PutRequest": {"Item": {"pk": {"S": "p3"}, "sk": {"S": "s3"}, "age": {"N": "26"}}}},+ ]},+ ReturnConsumedCapacity="TOTAL",+ )+ assert resp["ConsumedCapacity"][0]["CapacityUnits"] == 4.0+ ddb.delete_table(TableName="gsi-cap-batch")++# ---------------------------------------------------------------------------# Regression: XML error responses must include <Type>Sender/Receiver</Type># so botocore populates typed exception classes (e.g. client.exceptions.QueueDoesNotExist).