Skip to content

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

prerelease v1.5.28 (#2222)

Nahuel Nucera696bf7fe4d5b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c51f0f5a..c10c1ab4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,30 +8,27 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
-- **RDS — reboot event history** — `DescribeEvents` returns account/region-scoped reboot completion events with source, category and time filtering, markers, 14-day retention, persistence and reset support. Reboot events are recorded after readiness succeeds; other RDS lifecycle event producers are not yet implemented.
+- **RDS — `DescribeEvents` with reboot events** — `DescribeEvents` returns the `availability` event `DB instance restarted.` once a `RebootDBInstance` has finished, filtered by source, source type, category and time, paged with `Marker` and kept for 14 days; other RDS lifecycle events are not recorded yet. Contributed by @jayjanssen.
### Changed
-- **RDS — real instance reboot** — `RebootDBInstance` now returns `rebooting`, stops and starts its backing database container, and waits for SQL readiness before reporting `available`. Data and endpoint bindings are preserved. Optional `RDS_REBOOT_DOWNTIME_SECONDS` (0–3600, default 0) holds the engine stopped for local outage testing. Docker failures no longer report a successful reboot.
-
-### Changed
-- **RDS — real instance reboot** — `RebootDBInstance` now returns `rebooting`, stops and starts its backing database container, and waits for SQL readiness before reporting `available`. Data and endpoint bindings are preserved. Optional `RDS_REBOOT_DOWNTIME_SECONDS` (0–3600, default 0) holds the engine stopped for local outage testing. Docker failures no longer report a successful reboot.
+- **RDS — real instance reboot** — `RebootDBInstance` now returns `rebooting`, stops and starts its backing database container, and waits for SQL readiness before reporting `available`. Data and endpoint bindings are preserved. An instance that is not `available` answers `InvalidDBInstanceState`, and a Docker failure reports `failed` rather than a successful reboot. Contributed by @jayjanssen.
### Added
-- **S3 Control — Multi-Region Access Points** — `CreateMultiRegionAccessPoint`, `DeleteMultiRegionAccessPoint`, `PutMultiRegionAccessPointPolicy`, `DescribeMultiRegionAccessPointOperation`, `GetMultiRegionAccessPoint`, `GetMultiRegionAccessPointPolicy`, `ListMultiRegionAccessPoints`, `GetMultiRegionAccessPointRoutes` and `SubmitMultiRegionAccessPointRoutes`. The async operations apply at once and `Describe` reports `SUCCEEDED`, or `FAILED` with AWS's `ErrorDetails` for a missing bucket, two buckets in one region or a name already in use. Management is served from `us-west-2` and route operations from `us-east-1`, `us-west-2`, `eu-west-1`, `ap-northeast-1` and `ap-southeast-2`, as on AWS; other regions get `301 PermanentRedirect`. `DeleteBucket` on a member returns `BucketHasAccessPointsAttached`. Under `AUTH=true` each operation needs its `s3:` IAM action. Access points from `AWS::S3::MultiRegionAccessPoint` appear in the API.
-- **S3 — Multi-Region Access Point failover** — a request through the MRAP host goes to the member with a traffic dial of 100 that is homed in `MINISTACK_REGION`, else the first active member. Setting a dial to 0 moves traffic to the other member, and an update that leaves every dial at 0 is refused.
-- **CloudFormation — `DescribeEvents`** — returns the validation errors of a create that fails pre-deployment validation, which the stack's `CREATE_FAILED` event tells the caller to look up.
-- **CloudFormation — `CFN_S3_ADOPT_EXISTING_BUCKET`** — `AWS::S3::Bucket` adopts an own bucket that already exists by default, so S3 data that outlives the stack store stays usable. `CFN_S3_ADOPT_EXISTING_BUCKET=0` fails the create the way AWS does, and auto-named buckets get a new name for each stack instance.
+- **S3 Control — Multi-Region Access Points** — `CreateMultiRegionAccessPoint`, `DeleteMultiRegionAccessPoint`, `PutMultiRegionAccessPointPolicy`, `DescribeMultiRegionAccessPointOperation`, `GetMultiRegionAccessPoint`, `GetMultiRegionAccessPointPolicy`, `ListMultiRegionAccessPoints`, `GetMultiRegionAccessPointRoutes` and `SubmitMultiRegionAccessPointRoutes`. The async operations apply at once and `Describe` reports `SUCCEEDED`, or `FAILED` with AWS's `ErrorDetails` for a missing bucket, two buckets in one region or a name already in use. Management is served from `us-west-2` and route operations from `us-east-1`, `us-west-2`, `eu-west-1`, `ap-northeast-1` and `ap-southeast-2`, as on AWS; other regions get `301 PermanentRedirect`. `DeleteBucket` on a member returns `BucketHasAccessPointsAttached`. Under `AUTH=true` each operation needs its `s3:` IAM action and `x-amz-account-id` must name the caller's account. Access points from `AWS::S3::MultiRegionAccessPoint` appear in the API. Contributed by @fabio-andre-rodrigues.
+- **S3 — Multi-Region Access Point failover** — a request through the MRAP host goes to the member with a traffic dial of 100 that is homed in `MINISTACK_REGION`, else the first active member. Setting a dial to 0 moves traffic to the other member, and an update that leaves every dial at 0 is refused. Contributed by @fabio-andre-rodrigues.
+- **CloudFormation — `DescribeEvents`** — returns the validation errors of a create that fails pre-deployment validation, which the stack's `CREATE_FAILED` event tells the caller to look up; every request member is optional. Contributed by @fabio-andre-rodrigues.
### Fixed
-- **S3 — bucket home region is enforced** — a request signed for a region other than the bucket's now returns `301 PermanentRedirect` with `x-amz-bucket-region`, which SDKs follow; at the bucket's own regional endpoint it returns `400 AuthorizationHeaderMalformed` or, presigned, `AuthorizationQueryParametersError`, with `<Region>`. HEAD gets the bodiless forms. `GetBucketLocation`, `ListBuckets`, `CreateBucket`, unsigned, SigV2 and SigV4a requests, MRAP requests and internal callers are exempt, and `CopyObject` from a source in another region still works.
-- **S3 — `CreateBucket` location constraint (breaking)** — a request signed for a region other than `us-east-1` must name that region as `LocationConstraint`, or gets `IllegalLocationConstraintException`; `LocationConstraint=us-east-1` returns `InvalidLocationConstraint`. Clients that created buckets in another region without a constraint now need one. `BucketAlreadyOwnedByYou` and `BucketAlreadyExists` carry AWS's message and `<BucketName>`.
-- **S3 — `ListBuckets` `bucket-region` filter** — `BucketRegion` lists only that region's buckets, with pagination inside the filter; a filter for another region than the endpoint's returns `InvalidArgument`.
-- **S3 — replication** — delete markers replicate for V2 rules with `DeleteMarkerReplication` enabled and no tag filter, from `DeleteObject` and `DeleteObjects`; version-id deletes don't. Rules with `Filter.Tag` or `Filter.And.Tags` replicate only objects carrying those tags.
-- **SigV4a requests no longer land in region `s3`** — the region was read from a credential scope that SigV4a doesn't have; a single-region `X-Amz-Region-Set` is used, else the default region.
-- **Lambda — S3 code from another region** — `CreateFunction`, `UpdateFunctionCode`, `PublishLayerVersion` and CloudFormation return AWS's `InvalidParameterValueException` when the code bucket is homed elsewhere.
-- **Resource Groups Tagging — S3 buckets by region** — `GetResources`, `GetTagKeys` and `GetTagValues` list only buckets homed in the region they are called in.
-- **CloudFormation — `AWS::S3::Bucket` and existing names** — a `BucketName` another account owns used to become a second bucket of that name; it now fails pre-deployment validation with `NAME_CONFLICT_VALIDATION`, as on AWS. With rollback disabled, a failed validation emits AWS's second `CREATE_FAILED` event.
-- **CloudFront — function status follows publish and association** — `DescribeFunction` and `ListFunctions` reported the `DEVELOPMENT` stage as `UNPUBLISHED` even after `PublishFunction`, so Terraform's `aws_cloudfront_function.status`, which reads that stage, never left `UNPUBLISHED`; once the current development version is published it now reports `UNASSOCIATED`, or `ASSOCIATED` while a distribution's cache behavior references the function, and an `UpdateFunction` makes it `UNPUBLISHED` again until the next publish. Contributed by @fabio-andre-rodrigues.
+- **CloudFront — function status follows publish and association** — `DescribeFunction` and `ListFunctions` reported the `DEVELOPMENT` stage as `UNPUBLISHED` even after `PublishFunction`, so Terraform's `aws_cloudfront_function.status`, which reads that stage, never left `UNPUBLISHED`; once the current development version is published it now reports `UNASSOCIATED`, or `DEPLOYED` while a distribution's cache behavior references the function, and an `UpdateFunction` makes it `UNPUBLISHED` again until the next publish. Contributed by @fabio-andre-rodrigues.
+- **S3 — bucket home region is enforced** — a request signed for a region other than the bucket's now returns `301 PermanentRedirect` with `x-amz-bucket-region`, which SDKs follow; at the bucket's own regional endpoint it returns `400 AuthorizationHeaderMalformed` or, presigned, `AuthorizationQueryParametersError`, with `<Region>`. HEAD gets the bodiless forms. `GetBucketLocation`, `ListBuckets`, `CreateBucket`, unsigned, SigV2 and SigV4a requests, MRAP requests and internal callers are exempt, and `CopyObject` from a source in another region still works. Contributed by @fabio-andre-rodrigues.
+- **S3 — `CreateBucket` location constraint (breaking)** — a request signed for a region other than `us-east-1` must name that region as `LocationConstraint`, or gets `IllegalLocationConstraintException`; `LocationConstraint=us-east-1` returns `InvalidLocationConstraint`. Clients that created buckets in another region without a constraint now need one. `BucketAlreadyOwnedByYou` and `BucketAlreadyExists` carry AWS's message and `<BucketName>`. Contributed by @fabio-andre-rodrigues.
+- **S3 — `ListBuckets` `bucket-region` filter** — `BucketRegion` lists only that region's buckets, with pagination inside the filter; a filter for another region than the endpoint's returns `InvalidArgument`. Contributed by @fabio-andre-rodrigues.
+- **S3 — replication** — delete markers replicate for V1 rules (no `Filter`) and for V2 rules with `DeleteMarkerReplication` enabled and no tag filter, from `DeleteObject` and `DeleteObjects`; version-id deletes don't. Rules with `Filter.Tag` or `Filter.And.Tags` replicate only objects carrying those tags. Contributed by @fabio-andre-rodrigues.
+- **SigV4a requests no longer land in region `s3`** — the region was read from a credential scope that SigV4a doesn't have; a single-region `X-Amz-Region-Set` is used, else the default region. Contributed by @fabio-andre-rodrigues.
+- **Lambda — S3 code from another region** — `CreateFunction`, `UpdateFunctionCode`, `PublishLayerVersion` and CloudFormation return AWS's `InvalidParameterValueException` when the code bucket is homed elsewhere. Contributed by @fabio-andre-rodrigues.
+- **Resource Groups Tagging — S3 buckets by region** — `GetResources`, `GetTagKeys` and `GetTagValues` list only buckets homed in the region they are called in. Contributed by @fabio-andre-rodrigues.
+- **CloudFormation — `User Initiated` on stack events** — the stack's `CREATE_IN_PROGRESS` and `UPDATE_IN_PROGRESS` events of `CreateStack` and `UpdateStack` carried no reason; they now carry `User Initiated`, as AWS does.
+- **CloudFormation — `AWS::S3::Bucket` and existing names** — an `AWS::S3::Bucket` whose `BucketName` already exists, in this account or another, was adopted (another account's became a second bucket of that name); it now fails pre-deployment validation with `NAME_CONFLICT_VALIDATION`, or with `DisableValidation` the resource's create with `<name> already exists`, as on AWS, and auto-named buckets get a new name for each stack instance. `CreateStack`, `UpdateStack` and `CreateChangeSet` take `DisableValidation`, and an update now runs the same pre-deployment validation, ending in `UPDATE_ROLLBACK_COMPLETE` without touching a resource (a bucket the stack already owns is not a conflict). With rollback disabled, a failed validation emits AWS's second `CREATE_FAILED` event (breaking: a stack no longer adopts a bucket left over from an earlier stack or an S3-only restore). Contributed by @fabio-andre-rodrigues.
- **Step Functions — JSONata Fail and Wait fields are evaluated** — a JSONata Fail state raised its `Error` and `Cause` expressions as literal text, a JSONata Wait failed on a `Seconds` expression, ignored a `Timestamp` expression and dropped its `Output` and `Assign`, and JSONPath `ErrorPath`/`CausePath` were ignored; they are now evaluated, with AWS's `States.QueryEvaluationError` or `States.Runtime` for a result of the wrong type, a `Seconds` that is not a non-negative integer and an unparsable `Timestamp`.
- **S3 — presigned URLs keep AWS's time limits under `AUTH=true`** — an `X-Amz-Expires` over 604800 seconds or not a number, or a malformed `X-Amz-Date`, answers 400 `AuthorizationQueryParametersError`, and a URL dated more than 15 minutes ahead answers 403 `AccessDenied` `Request is not yet valid`, where they were served. Contributed by @iot-rocket.
- **Auth — credential failures in the service's protocol** — under `AUTH=true` an unknown, inactive or expired access key answered `UnrecognizedClientException` 403 from every service; it now gets the code, status and `Content-Type` AWS sends for the service's protocol, for example `InvalidClientTokenId` 403 from IAM and SQS, `UnrecognizedClientException` 400 from DynamoDB, `InvalidAccessKeyId` 403 from S3 and `AuthFailure` 401 from EC2. Contributed by @iot-rocket.
@@ -80,8 +77,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **IoT — job rollout rates** — `jobExecutionsRolloutConfig` was stored but every execution was created at once; a job now creates `maximumPerMinute` executions a minute, or a rate that starts at `baseRatePerMinute` and grows by `incrementFactor` for every `rateIncreaseCriteria` step of notified or succeeded things, notifies each thing when its execution is created, reports `isConcurrent` until the last batch and stops when the job is canceled or deleted. Contributed by @iot-rocket.
- **IoT — MQTT publish, subscribe and receive evaluate IoT policies under `AUTH=true`** — after the CONNECT a certificate session could publish, subscribe and receive on any topic; it now needs `iot:Publish` on the topic (and `iot:RetainPublish` for a retained message or will), `iot:Subscribe` per topic filter and `iot:Receive` per delivered message. A refused PUBLISH or SUBSCRIBE closes an MQTT 3.1.1 connection (disconnect reason `CLIENT_ERROR`), MQTT 5 answers PUBACK 0x87, DISCONNECT 0x87 at QoS 0 (`AUTH_ERROR`) or 0x87 for the refused filter, which the `subscribed` event leaves out (no event when none is granted), a refused will refuses the CONNECT, and a message the subscriber may not receive is dropped. Contributed by @iot-rocket.
- **IoT — MQTT connections evaluate `iot:Connect` under `AUTH=true`** — a device certificate on the mTLS listener connected under any client id, with or without a policy; with `AUTH=true` the CONNECT now needs an attached policy that allows `iot:Connect` on `client/<client id>` and none that denies it, with `${iot:ClientId}`, `${iot:Connection.Thing.ThingName}`, `iot:Connection.Thing.IsAttached` and `${iot:Certificate.Subject.CommonName}` resolved. A refusal closes an MQTT 3.1.1 connection without a CONNACK, answers MQTT 5 with CONNACK 0x87 and publishes `$aws/events/presence/connect_failed/{clientId}`. Contributed by @iot-rocket.
-
-- **Authorization CI contracts** — marked SDK/HTTP tests run against both `AUTH=false` and `AUTH=true`, covering IAM allow/deny behavior and S3 copy source permissions. Shared IAM user fixtures create and clean up resources through MiniStack's IAM API, and health responses expose the effective `auth` state (`enabled`/`disabled`) so tests fail on mode mismatches.
+- **Health — `auth` field** — `/_ministack/health` reports `"auth": "enabled"` or `"disabled"`, the effective `AUTH` mode. Contributed by @jgrumboe.
### Fixed
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ff874997..cd159f96 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -200,24 +200,14 @@ pytest tests/ -v -k "cognito"
## Testing Permission Behavior
-When testing whether an AWS operation is allowed or denied, write an SDK/HTTP
-integration test in `tests/test_<service>.py` and mark it `auth_contract`.
-CI runs the same marked tests against fresh servers with `AUTH=false` and
-`AUTH=true`; the existing control-plane and data-plane jobs exclude them.
-The initial authorization matrix runs without Docker.
-
-Use the shared `iam_user` factory to create users through IAM APIs. It grants
-no permissions by default. Pass `policy={...}` to attach an explicit inline
-policy, then use `user.client("service")` for the request under test. Existing
-service fixtures such as `s3` use admin credentials for resource setup and
-cleanup. The user factory removes its users, keys, policies, and clients after
-each test, including after failures. Service resources need their own cleanup.
+Test whether an operation is allowed or denied with an SDK/HTTP test in
+`tests/test_<service>.py` marked `auth_contract`. CI runs these against servers
+with `AUTH=false` and `AUTH=true`; the other jobs exclude them. `iam_user`
+creates a user with no permissions (pass `policy={...}` for an inline policy)
+and cleans up after the test; `auth_enabled` is the server's mode, checked
+against the `AUTH` the tests run with.
```python
-import pytest
-from botocore.exceptions import ClientError
-
-
@pytest.mark.auth_contract
def test_list_buckets_without_permission(auth_enabled, iam_user):
client = iam_user().client("s3")
@@ -225,50 +215,18 @@ def test_list_buckets_without_permission(auth_enabled, iam_user):
with pytest.raises(ClientError) as exc:
client.list_buckets()
assert exc.value.response["Error"]["Code"] == "AccessDenied"
- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
else:
assert "Buckets" in client.list_buckets()
```
-Every marked test verifies that the server's health response reports the expected
-mode, even if it doesn't request `auth_enabled` explicitly. The fixture observes
-configuration; it never changes the server's mode. A mismatch fails the test.
-Health reports `auth` as `enabled` or `disabled`; `auth_enabled` exposes that
-state as a boolean to tests.
-
-For local runs, start the server in one terminal:
-
-```bash
-AUTH=false DOCKER_HOST=unix:///no-existent/docker.sock IOT_MTLS_ENABLED=0 \
-python -m hypercorn ministack.app:app --bind 127.0.0.1:4566 --keep-alive 75
-```
-
-Run the contracts in another terminal with the same mode:
+Run them locally with the server and pytest in the same mode, then repeat with
+`AUTH=true`:
```bash
+AUTH=false IOT_MTLS_ENABLED=0 python -m hypercorn ministack.app:app --bind 127.0.0.1:4566
AUTH=false pytest tests/ -m auth_contract -v
-# Or focus on one service:
-AUTH=false pytest tests/test_s3.py -m auth_contract -v
```
-Stop the server, restart it with `AUTH=true`, and rerun with `AUTH=true` in the
-test command. Set `MINISTACK_ENDPOINT` for pytest if using another address.
-CI also checks a separate server started with `AUTH` unset to protect the
-permissive default.
-
-Permission changes should assert both enforcement and permissive compatibility:
-a valid request lacking permission succeeds with `AUTH=false` and is denied
-with `AUTH=true`. Include a permitted case as a control, and verify error codes,
-HTTP status, and relevant resource state. Input validation and service-specific
-authentication requirements may still apply in permissive mode.
-
-Keep focused evaluator unit tests for policy logic. Existing tests that patch
-`app.AUTH` should migrate when they test externally observable behavior; remove
-redundant patched tests once the replacement covers their behavior. The legacy
-`inprocess_iam_user` helper supports remaining internal tests, not new permission
-contracts. More involved scenarios, such as role sessions and Docker-backed
-execution roles, can add shared fixtures and CI support when exercised.
-
---
## Code Conventions
diff --git a/ministack/app.py b/ministack/app.py
index c765c8b8..eff78cda 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -1590,7 +1590,7 @@ async def _handle_s3_control_request(path: str, method: str, body: bytes, query_
if denied:
return denied
status, resp_headers, resp_body = (
- s3.s3control_account_error(headers)
+ (AUTH and s3.s3control_account_error(headers))
or s3.handle_mrap_control(method, path, headers, body, query_params)
)
return status, {**resp_headers, "x-amzn-requestid": request_id}, resp_body
@@ -2597,8 +2597,7 @@ def _unknown_query_error(body: bytes, request_id: str):
else "The requested action is not valid for this web service."
)
msg = msg.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
- # Query-protocol error envelopes carry no <?xml?> declaration on the
- # real AWS wire (17-region capture sweep, 0/85 declarations).
+ # Query error envelopes carry no <?xml?> declaration (AWS captures).
xml = (
'<ErrorResponse xmlns="http://webservices.amazon.com/doc/2010-05-08/">'
f"<Error><Type>Sender</Type><Code>InvalidAction</Code><Message>{msg}</Message></Error>"
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index d7b63598..c153246c 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -2115,8 +2115,7 @@ def access_denied_response(service: str, action: str, principal_arn: str,
return status, {"Content-Type": "application/xml"}, body.encode()
if protocol == "query-xml":
- # Query-protocol error envelopes carry no <?xml?> declaration on
- # the real AWS wire (17-region capture sweep, 0/85 declarations).
+ # Query error envelopes carry no <?xml?> declaration (AWS captures).
ns = _QUERY_XML_NS.get(service, "https://iam.amazonaws.com/doc/2010-05-08/")
body = (
f'<ErrorResponse xmlns="{ns}">'
@@ -2126,6 +2125,15 @@ def access_denied_response(service: str, action: str, principal_arn: str,
)
return status, {"Content-Type": "text/xml"}, body.encode()
+ if service == "sqs" and headers is not None and not headers.get("x-amz-target"):
+ # A query-mode SQS request is answered in SQS's query XML (live AWS capture).
+ body = (
+ '<?xml version="1.0"?><ErrorResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/">'
+ f"<Error><Type>Sender</Type><Code>{_esc_code}</Code><Message>{_esc_msg}</Message><Detail/></Error>"
+ f"<RequestId>{_esc_rid}</RequestId></ErrorResponse>"
+ )
+ return status, {"Content-Type": "text/xml"}, body.encode()
+
# JSON protocol (DynamoDB, Lambda, KMS, Logs, Glue, etc.)
json_type = code if code != "AccessDenied" else "AccessDeniedException"
body = json.dumps({
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index 25458c44..3d57c649 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -1239,7 +1239,7 @@ def resolve_principal(access_key_id: str,
@dataclass(frozen=True)
class SignedRequest:
- """A header-signed request as it arrived."""
+ """A header- or query-signed request as it arrived."""
access_key_id: str
method: str
@@ -1247,6 +1247,7 @@ class SignedRequest:
query_params: dict
headers: dict
body: bytes = b""
+ presigned: bool = False
_signed_request: contextvars.ContextVar[SignedRequest | None] = contextvars.ContextVar(
@@ -1254,13 +1255,14 @@ _signed_request: contextvars.ContextVar[SignedRequest | None] = contextvars.Cont
def pin_signed_request(method: str, raw_path: str, query_params: dict, raw_headers: list) -> None:
- """Keep a request header-signed with an IAM user or STS session key as sent, for its signature check."""
+ """Keep a request signed with an IAM user or STS session key as sent, for its signature check."""
from ministack.core.router import extract_access_key_id
from ministack.core.sigv4 import decode_header_value
authorization = decode_header_value(next((v for n, v in raw_headers if n.lower() == b"authorization"), b""))
- access_key_id = extract_access_key_id({"authorization": authorization})
- if not authorization.startswith("AWS4-HMAC-SHA256") or _is_root_key(access_key_id):
+ presigned = not authorization.startswith("AWS4-HMAC-SHA256") and _query_signed(query_params)
+ access_key_id = extract_access_key_id({"authorization": authorization}, query_params if presigned else None)
+ if not (authorization.startswith("AWS4-HMAC-SHA256") or presigned) or _is_root_key(access_key_id):
_signed_request.set(None)
return
headers: dict[str, str] = {}
@@ -1268,7 +1270,18 @@ def pin_signed_request(method: str, raw_path: str, query_params: dict, raw_heade
key, text = name.decode("latin-1").lower(), decode_header_value(value)
# SigV4 signs a header sent on several lines as its values joined by a bare comma.
headers[key] = f"{headers[key]},{text}" if key in headers else text
- _signed_request.set(SignedRequest(access_key_id, method, raw_path, query_params, headers))
+ _signed_request.set(SignedRequest(access_key_id, method, raw_path, query_params, headers, presigned=presigned))
+
+
+def _query_signed(query_params: dict) -> bool:
+ """A SigV4 query-string signature; S3 checks its own presigned URLs."""
+ def value(name):
+ found = query_params.get(name) or query_params.get(name.lower()) or [""]
+ return found[0] if isinstance(found, list) else found
+
+ scope = value("X-Amz-Credential").split("/")
+ return value("X-Amz-Algorithm") == "AWS4-HMAC-SHA256" and bool(scope[0]) and (
+ len(scope) < 4 or scope[3] != "s3")
def pin_signed_body(body: bytes) -> None:
@@ -1281,19 +1294,30 @@ def pin_signed_body(body: bytes) -> None:
def authenticate(access_key_id: str, account_id: str) -> AuthError | ResolvedCredential | None:
"""Check the pinned request's time, session token and signature: its credential, a failure, or None."""
from ministack.core.responses import _account_from_sts_session
- from ministack.core.sigv4 import header_signature_failure, parse_header_signature, request_time_failure
+ from ministack.core.sigv4 import (
+ header_signature_failure,
+ parse_header_signature,
+ parse_query_signature,
+ request_time_failure,
+ )
request = _signed_request.get()
if request is None or request.access_key_id != access_key_id:
return None
_signed_request.set(None) # checked once; the request's later checks skip it
- signature = parse_header_signature(request.headers)
+ if request.presigned:
+ signature = parse_query_signature(request.query_params)
+ else:
+ signature = parse_header_signature(request.headers)
if isinstance(signature, tuple):
return AuthError(*signature)
skewed = request_time_failure(signature)
if skewed:
return AuthError(*skewed)
- token = request.headers.get("x-amz-security-token", "")
+ if request.presigned:
+ token = (request.query_params.get("X-Amz-Security-Token") or [""])[0]
+ else:
+ token = request.headers.get("x-amz-security-token", "")
credential = resolve_credential(access_key_id, _account_from_sts_session(access_key_id) or account_id, token)
if isinstance(credential, CredentialResolutionError):
if credential.code == "InvalidToken":
@@ -1304,7 +1328,7 @@ def authenticate(access_key_id: str, account_id: str) -> AuthError | ResolvedCre
return AuthError(credential.code, credential.message)
failure = header_signature_failure(
signature, credential.secret_access_key, request.method, request.raw_path,
- request.query_params, request.headers, request.body,
+ request.query_params, request.headers, request.body, presigned=request.presigned,
)
return AuthError(*failure) if failure else credential
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 162de2fb..5a57563c 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -1042,7 +1042,6 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"StartDBInstance": "rds",
"StopDBInstance": "rds",
"RebootDBInstance": "rds",
- "DescribeEvents": "rds",
"ModifyDBInstance": "rds",
"CreateDBCluster": "rds",
"DeleteDBCluster": "rds",
diff --git a/ministack/core/sigv4.py b/ministack/core/sigv4.py
index 5baab66b..f05c5599 100644
--- a/ministack/core/sigv4.py
+++ b/ministack/core/sigv4.py
@@ -198,6 +198,28 @@ def parse_header_signature(headers: Mapping[str, Any]) -> HeaderSignature | tupl
return HeaderSignature(*scope[:4], fields["SignedHeaders"], fields["Signature"], amz_date)
+def _query_value(query_params: Mapping[str, Any], name: str) -> str:
+ value = query_params.get(name, query_params.get(name.lower(), ""))
+ return (value[0] if value else "") if isinstance(value, list) else value
+
+
+def parse_query_signature(query_params: Mapping[str, Any]) -> HeaderSignature | tuple[str, str]:
+ """Split a query-string (presigned) signature into its parts, or name the part that is missing."""
+ credential = _query_value(query_params, "X-Amz-Credential")
+ for name in ("X-Amz-Signature", "X-Amz-SignedHeaders", "X-Amz-Date"):
+ if not _query_value(query_params, name):
+ return "IncompleteSignature", (
+ f"AWS query-string parameters must include '{name}'. Re-examine the query-string parameters.")
+ scope = credential.split("/")
+ if len(scope) != 5:
+ return "IncompleteSignature", (
+ "Credential must have exactly 5 slash-delimited elements, e.g. keyid/date/region/service/term, "
+ f"got '{credential}'"
+ )
+ return HeaderSignature(*scope[:4], _query_value(query_params, "X-Amz-SignedHeaders"),
+ _query_value(query_params, "X-Amz-Signature"), _query_value(query_params, "X-Amz-Date"))
+
+
# Services that accept a request signed up to 15 minutes from their clock; the others allow 5.
_FIFTEEN_MINUTE_SERVICES = frozenset({"dynamodb", "ecr", "elasticache", "iam", "rds", "s3", "sns", "sqs", "sts"})
@@ -261,15 +283,19 @@ def header_signature_failure(
query_params: Mapping[str, Any],
headers: Mapping[str, Any],
body: bytes,
+ *,
+ presigned: bool = False,
) -> tuple[str, str] | None:
- """Recompute a header signature; S3 signs its path as sent, other services the normalized path encoded again."""
+ """Recompute a header (or, ``presigned``, query-string) signature; S3 signs its path as sent, other services
+ the normalized path encoded again."""
if signature.date_stamp != signature.amz_date[:8]:
return "CredentialDateMismatch", (
"Date in Credential scope does not match YYYYMMDD from ISO-8601 version of date from HTTP. ")
path = raw_path if signature.service == "s3" else uri_encode(_remove_dot_segments(raw_path), encode_slash=False)
payload_hash = headers.get("x-amz-content-sha256") or hashlib.sha256(body).hexdigest()
+ excluded = ("x-amz-signature",) if presigned else ()
canonical_request = "\n".join([
- method, path, build_canonical_query_string(query_params, exclude=()),
+ method, path, build_canonical_query_string(query_params, exclude=excluded),
build_canonical_headers(headers, signature.signed_headers), signature.signed_headers, payload_hash,
])
string_to_sign = build_string_to_sign(
diff --git a/ministack/services/alb.py b/ministack/services/alb.py
index 584d11f8..6d57236a 100644
--- a/ministack/services/alb.py
+++ b/ministack/services/alb.py
@@ -408,9 +408,7 @@ def _empty(action):
def _error(code, message, status=400):
- # Query-protocol error envelope per real-AWS captures (17-region
- # sweep): <Type> inside <Error> (Sender for 4xx, Receiver for 5xx)
- # and no <?xml?> declaration.
+ # Query error envelope: <Type> in <Error>, no <?xml?> (AWS captures).
body = (
f'<ErrorResponse xmlns="{NS}">'
f'<Error><Type>{"Sender" if status < 500 else "Receiver"}</Type>'
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index ca6968cf..a94c8b5f 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -3963,11 +3963,9 @@ def _export_integration(integration):
def _export_security_scheme(authorizer, include_authorizers):
- """Security scheme for a TOKEN or REQUEST authorizer.
-
- More than one identity source, or one that is not a header or query
- string, gives the name ``Unused``, as the AWS docs show."""
- source = authorizer["identitySource"]
+ """Security scheme for a TOKEN or REQUEST authorizer."""
+ source = authorizer.get("identitySource") or ""
+ authorizer_type = authorizer.get("type") or "TOKEN"
name = "Unused"
location = "header"
if "," not in source:
@@ -3987,13 +3985,15 @@ def _export_security_scheme(authorizer, include_authorizers):
return scheme
extension = {
- "type": authorizer["type"].lower(),
- "authorizerUri": authorizer["authorizerUri"],
- "authorizerResultTtlInSeconds": authorizer["authorizerResultTtlInSeconds"],
+ "type": authorizer_type.lower(),
+ "authorizerUri": authorizer.get("authorizerUri", ""),
+ "authorizerResultTtlInSeconds": authorizer.get(
+ "authorizerResultTtlInSeconds", _DEFAULT_AUTHORIZER_TTL
+ ),
}
- if authorizer["type"] == "REQUEST":
+ if authorizer_type == "REQUEST":
extension["identitySource"] = source
- if authorizer["type"] == "TOKEN" and authorizer.get("identityValidationExpression"):
+ if authorizer_type == "TOKEN" and authorizer.get("identityValidationExpression"):
extension["identityValidationExpression"] = authorizer["identityValidationExpression"]
if authorizer.get("authorizerCredentials"):
extension["authorizerCredentials"] = authorizer["authorizerCredentials"]
diff --git a/ministack/services/autoscaling.py b/ministack/services/autoscaling.py
index 25170e5e..afbab4b8 100644
--- a/ministack/services/autoscaling.py
+++ b/ministack/services/autoscaling.py
@@ -145,9 +145,7 @@ def _xml(status, root_tag, inner):
def _error(code, message, status=400):
- # Query-protocol error envelope per real-AWS captures (17-region
- # sweep): <Type> inside <Error> (Sender for 4xx, Receiver for 5xx),
- # <RequestId> as a direct child, and no <?xml?> declaration.
+ # Query error envelope: <Type> in <Error>, no <?xml?> (AWS captures).
fault_type = "Sender" if status < 500 else "Receiver"
body = (f'<ErrorResponse xmlns="http://autoscaling.amazonaws.com/doc/2011-01-01/">'
f'<Error><Type>{fault_type}</Type><Code>{code}</Code><Message>{message}</Message></Error>'
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
index b223d3cf..d87cfa89 100644
--- a/ministack/services/cloudformation/changesets.py
+++ b/ministack/services/cloudformation/changesets.py
@@ -808,6 +808,7 @@ def _create_change_set(params):
"_resources_to_import": resources_to_import,
"_import_existing": {e["LogicalResourceId"]: e["ResourceIdentifier"] for e in existing},
"ImportExistingResources": import_existing,
+ "_disable_validation": _p(params, "DisableValidation", "false").lower() == "true",
}
_change_sets[cs_id] = change_set
@@ -1022,6 +1023,7 @@ def _execute_change_set(params):
status_prefix = "UPDATE" if is_update else "CREATE"
if not is_update:
stack["DisableRollback"] = disable_rollback
+ stack["_disable_validation"] = cs.get("_disable_validation", False)
stack["StackStatus"] = f"{status_prefix}_IN_PROGRESS"
stack["LastUpdatedTime"] = now_iso()
stack["_template_body"] = template_body
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index 1e413106..a3869fe9 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -358,6 +358,7 @@ def _create_stack(params):
"Outputs": [],
"DisableRollback": disable_rollback,
"EnableTerminationProtection": termination_protection,
+ "_disable_validation": _p(params, "DisableValidation", "false").lower() == "true",
"_stack_policy": stack_policy or "",
"_region": get_region(),
"_resources": {},
@@ -370,7 +371,7 @@ def _create_stack(params):
_stack_events[stack_id] = []
_add_event(stack_id, stack_name, stack_name,
- "AWS::CloudFormation::Stack", "CREATE_IN_PROGRESS",
+ "AWS::CloudFormation::Stack", "CREATE_IN_PROGRESS", "User Initiated",
physical_id=stack_id)
deploy = _deploy_stack_async(stack_name, stack_id, template,
@@ -615,12 +616,17 @@ def _describe_events(params):
that fails pre-deployment validation, the case the stack event tells the
caller to call DescribeEvents for; change-set events are not recorded."""
stack_name = _p(params, "StackName")
- if not stack_name:
- return _error("ValidationError", "StackName is required")
- stack = _resolve_stack(stack_name)
- if not stack:
- return _error("ValidationError", f"Stack [{stack_name}] does not exist")
- events = list(stack.get("_operation_events") or [])
+ if stack_name:
+ stack = _resolve_stack(stack_name)
+ if not stack:
+ return _error("ValidationError", f"Stack [{stack_name}] does not exist")
+ events = list(stack.get("_operation_events") or [])
+ elif _p(params, "ChangeSetName"):
+ events = []
+ else:
+ # Every member is optional; an OperationId alone names its stack's events.
+ from ministack.services.cloudformation import _stacks
+ events = [e for s in _stacks.values() for e in s.get("_operation_events") or []]
operation_id = _p(params, "OperationId")
if operation_id:
events = [e for e in events if e.get("OperationId") == operation_id]
@@ -1114,6 +1120,7 @@ def _update_stack(params):
stack["StackStatus"] = "UPDATE_IN_PROGRESS"
stack["LastUpdatedTime"] = now_iso()
+ stack["_disable_validation"] = _p(params, "DisableValidation", "false").lower() == "true"
stack["_template_body"] = template_body
# The capabilities a stack reports are the ones its last operation
# acknowledged, so an update replaces them rather than adding to them.
@@ -1128,7 +1135,7 @@ def _update_stack(params):
stack["_conditions"] = _evaluate_conditions(template, param_values)
_add_event(stack_id, stack_name, stack_name,
- "AWS::CloudFormation::Stack", "UPDATE_IN_PROGRESS",
+ "AWS::CloudFormation::Stack", "UPDATE_IN_PROGRESS", "User Initiated",
physical_id=stack_id)
_create_stack_task_in_region(
diff --git a/ministack/services/cloudformation/helpers.py b/ministack/services/cloudformation/helpers.py
index d1aa7eaf..2bcb5597 100644
--- a/ministack/services/cloudformation/helpers.py
+++ b/ministack/services/cloudformation/helpers.py
@@ -46,8 +46,7 @@ def _xml(status, root_tag, inner):
def _error(code, message, status=400):
- # Query-protocol error envelope per real-AWS captures (17-region
- # sweep): <Type> inside <Error> and no <?xml?> declaration.
+ # Query error envelope: <Type> in <Error>, no <?xml?> (AWS captures).
t = "Sender" if status < 500 else "Receiver"
body = (
f'<ErrorResponse xmlns="{CFN_NS}">'
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 215ebade..19a0b85a 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -1443,32 +1443,22 @@ def _s3_attrs(name):
}
-# AWS fails CreateStack when an AWS::S3::Bucket names a bucket that already
-# exists. MiniStack adopts an own existing bucket by default, which keeps S3
-# data usable when it outlives the CloudFormation state (S3 persistence with a
-# fresh stack store); 0 gives AWS's behaviour.
-CFN_S3_ADOPT_EXISTING_BUCKET = os.environ.get("CFN_S3_ADOPT_EXISTING_BUCKET", "1") == "1"
-
-
def s3_bucket_name_conflict(name: str) -> str | None:
- """The NAME_CONFLICT_VALIDATION message for a bucket name the stack can't
- take, or None. Another account's bucket is never taken; an own bucket only
- when CFN_S3_ADOPT_EXISTING_BUCKET is off."""
- owner = _s3._bucket_owner_account(name)
- if owner is None or (owner == get_account_id() and CFN_S3_ADOPT_EXISTING_BUCKET):
+ """The NAME_CONFLICT_VALIDATION message for a bucket name that already exists, or None."""
+ if _s3._bucket_owner_account(name) is None:
return None
return f"Resource of type 'AWS::S3::Bucket' with identifier '{name}' already exists."
def _s3_create(logical_id, props, stack_name):
- if not props.get("BucketName") and not CFN_S3_ADOPT_EXISTING_BUCKET and not _NAME_SEED.get():
+ if not props.get("BucketName") and not _NAME_SEED.get():
# AWS draws a new auto-name for each stack instance; the seed travels
# on the resource record, so updates keep the name.
_NAME_SEED.set(new_uuid()[:8])
name = props.get("BucketName") or _physical_name(stack_name, logical_id, lowercase=True, max_len=63)
- conflict = s3_bucket_name_conflict(name)
- if conflict:
- raise ValueError(conflict)
+ if _s3._bucket_owner_account(name) is not None:
+ # Reached with DisableValidation: the resource handler refuses the existing name.
+ raise ValueError(f"{name} already exists")
_s3._buckets.setdefault(name, {
"created": now_iso(),
"objects": {},
@@ -14381,7 +14371,8 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
"AWS::StepFunctions::StateMachine": ("StateMachineName", "StateMachineType"),
"AWS::AppSync::DataSource": ("ApiId", "Name"),
"AWS::AppSync::Resolver": ("ApiId", "TypeName", "FieldName"),
- "AWS::AppSync::GraphQLSchema": ("ApiId",),
+ # Every GraphQLSchema property is "Update requires: No interruption".
+ "AWS::AppSync::GraphQLSchema": (),
"AWS::Cognito::UserPoolGroup": ("GroupName", "UserPoolId"),
"AWS::Cognito::UserPoolResourceServer": ("Identifier", "UserPoolId"),
"AWS::Cognito::UserPoolDomain": ("Domain", "UserPoolId"),
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index 6550a68f..c87a5a56 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -606,6 +606,8 @@ _VALIDATION_FAILED = (
"full list of issues with resource and property details, resolve each error, "
"then retry the operation.")
_VALIDATION_ROLLBACK = "Validation failure detected. See the operation's FAILED event for details."
+# The update wording, observed on AWS 2026-10-16.
+_UPDATE_VALIDATION_ROLLBACK = "Validation failure detected. See operation's FAILED event for details."
def _static_property(raw, resources_defs, param_values, conditions, mappings, stack_name, stack_id):
@@ -616,10 +618,12 @@ def _static_property(raw, resources_defs, param_values, conditions, mappings, st
return _resolve_refs(copy.deepcopy(raw), {}, param_values, conditions, mappings, stack_name, stack_id)
-def _validation_errors(resources_defs, ordered, param_values, conditions, mappings, stack_name, stack_id):
+def _validation_errors(resources_defs, ordered, param_values, conditions, mappings, stack_name, stack_id,
+ owned_buckets=frozenset()):
"""Pre-deployment validation errors as ``(logical_id, type, validation name,
path, reason)``: properties outside their schema enum, and AWS::S3::Bucket
- names the stack can't take (NAME_CONFLICT_VALIDATION, observed on AWS)."""
+ names the stack can't take (NAME_CONFLICT_VALIDATION, observed on AWS); a
+ bucket the stack already owns is not a conflict for its update."""
from ministack.services.cloudformation.provisioners import s3_bucket_name_conflict
errors = []
@@ -642,33 +646,41 @@ def _validation_errors(resources_defs, ordered, param_values, conditions, mappin
if rtype == "AWS::S3::Bucket" and raw_props.get("BucketName"):
name = _static_property(raw_props["BucketName"], resources_defs, param_values, conditions,
mappings, stack_name, stack_id)
- conflict = s3_bucket_name_conflict(name) if isinstance(name, str) else None
+ conflict = (s3_bucket_name_conflict(name)
+ if isinstance(name, str) and name not in owned_buckets else None)
if conflict:
errors.append((logical_id, rtype, "NAME_CONFLICT_VALIDATION", f"/Resources/{logical_id}", conflict))
return errors
-def _operation_event(stack_id, operation_id, event_type, **fields):
+def _operation_event(stack_id, operation_id, event_type, operation_type="CREATE_STACK", **fields):
return {"EventId": new_uuid(), "StackId": stack_id, "OperationId": operation_id,
- "OperationType": "CREATE_STACK", "OperationStatus": "FAILED", "EventType": event_type,
+ "OperationType": operation_type, "OperationStatus": "FAILED", "EventType": event_type,
"Timestamp": now_iso(), **fields}
def _fail_property_validation(stack, stack_id, stack_name, resources_defs, ordered,
- param_values, conditions, mappings, disable_rollback):
- """Fail a create that doesn't pass pre-deployment validation before
- provisioning anything. The errors themselves are kept on the stack for
- DescribeEvents, which the stack event points the caller to."""
+ param_values, conditions, mappings, disable_rollback,
+ previous_stack=None):
+ """Fail a create or update that doesn't pass pre-deployment validation
+ before provisioning anything. The errors themselves are kept on the stack
+ for DescribeEvents, which the stack event points the caller to. A failed
+ update rolls back to ``previous_stack`` (observed on AWS 2026-10-16)."""
+ is_update = previous_stack is not None
+ owned = {r.get("PhysicalResourceId") for r in (previous_stack or {}).get("_resources", {}).values()
+ if r.get("ResourceType") == "AWS::S3::Bucket"}
errors = _validation_errors(resources_defs, ordered, param_values, conditions, mappings,
- stack_name, stack_id)
+ stack_name, stack_id, frozenset(owned))
if not errors:
return False
operation_id = new_uuid()
+ operation_type = "UPDATE_STACK" if is_update else "CREATE_STACK"
operation_events = []
for logical_id, rtype, validation_name, path, reason in errors:
logger.warning("Stack %s validation: %s: %s", stack_name, path, reason)
operation_events.append(_operation_event(
- stack_id, operation_id, "VALIDATION_ERROR", LogicalResourceId=logical_id, ResourceType=rtype,
+ stack_id, operation_id, "VALIDATION_ERROR", operation_type,
+ LogicalResourceId=logical_id, ResourceType=rtype,
ValidationFailureMode="FAIL", ValidationName=validation_name, ValidationStatus="FAILED",
ValidationStatusReason=reason, ValidationPath=path))
@@ -676,10 +688,25 @@ def _fail_property_validation(stack, stack_id, stack_name, resources_defs, order
_add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack", status, reason, stack_id,
detailed_status=detailed_status)
operation_events.append(_operation_event(
- stack_id, operation_id, "PROVISIONING_ERROR", LogicalResourceId=stack_name,
+ stack_id, operation_id, "PROVISIONING_ERROR", operation_type, LogicalResourceId=stack_name,
PhysicalResourceId=stack_id, ResourceType="AWS::CloudFormation::Stack", ResourceStatus=status,
ResourceStatusReason=reason, **({"DetailedStatus": detailed_status} if detailed_status else {})))
+ if is_update:
+ stack_event("UPDATE_FAILED", _VALIDATION_FAILED.format(count=len(errors)), "VALIDATION_FAILED")
+ for key in ("_template", "_resolved_params", "_template_body", "Parameters", "Tags", "Outputs",
+ "_conditions"):
+ if key in previous_stack:
+ stack[key] = previous_stack[key]
+ if disable_rollback:
+ stack["StackStatus"] = "UPDATE_FAILED"
+ else:
+ stack_event("UPDATE_ROLLBACK_IN_PROGRESS", _UPDATE_VALIDATION_ROLLBACK)
+ stack_event("UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", "")
+ stack_event("UPDATE_ROLLBACK_COMPLETE", "")
+ stack["StackStatus"] = "UPDATE_ROLLBACK_COMPLETE"
+ stack["_operation_events"] = operation_events
+ return True
stack_event("CREATE_FAILED", _VALIDATION_FAILED.format(count=len(errors)), "VALIDATION_FAILED")
if disable_rollback:
stack_event("CREATE_FAILED", _VALIDATION_ROLLBACK)
@@ -730,9 +757,10 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
str(exc), stack_id)
return
- if not is_update and _fail_property_validation(
+ if not stack.get("_disable_validation") and _fail_property_validation(
stack, stack_id, stack_name, resources_defs, ordered, param_values,
- conditions, mappings, disable_rollback):
+ conditions, mappings, disable_rollback,
+ previous_stack=(previous_stack or {}) if is_update else None):
return
provisioned_resources: dict = stack.get("_resources", {})
diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.py
index 460110bd..82b26add 100644
--- a/ministack/services/cloudfront.py
+++ b/ministack/services/cloudfront.py
@@ -314,9 +314,7 @@ def _xml_response(root_tag: str, builder_fn, status: int = 200, extra_headers: d
def _error(code: str, message: str, status: int) -> tuple:
- # rest-xml error envelope per real-AWS captures (17-region sweep):
- # <?xml?> declaration present and <Type> inside <Error> (Sender for
- # 4xx, Receiver for 5xx).
+ # rest-xml error envelope: <?xml?> declaration and <Type> (AWS captures).
root = Element("ErrorResponse", xmlns=NS)
err = SubElement(root, "Error")
SubElement(err, "Type").text = "Sender" if status < 500 else "Receiver"
@@ -748,12 +746,12 @@ def _function_arns_in(dist):
def _function_dev_status(fn):
"""DEVELOPMENT-stage Status: UNPUBLISHED until PublishFunction has copied
the current development version to LIVE (an UpdateFunction since then makes
- it UNPUBLISHED again), then ASSOCIATED while a distribution's cache behavior
+ it UNPUBLISHED again), then DEPLOYED while a distribution's cache behavior
references the function and UNASSOCIATED otherwise."""
if not fn.get("live_etag") or fn.get("published_dev_etag") != fn["dev_etag"]:
return "UNPUBLISHED"
if any(fn["arn"] in _function_arns_in(d) for d in _distributions.values()):
- return "ASSOCIATED"
+ return "DEPLOYED"
return "UNASSOCIATED"
diff --git a/ministack/services/cloudtrail.py b/ministack/services/cloudtrail.py
index 699ffc43..5df036cf 100644
--- a/ministack/services/cloudtrail.py
+++ b/ministack/services/cloudtrail.py
@@ -591,7 +591,7 @@ def _start_logging(body: dict):
if error:
return error
trail["IsLogging"] = True
- trail["_StartedAt"] = round(time.time(), 3)
+ trail["_StartedAt"] = int(time.time())
return _ok({})
@@ -604,7 +604,7 @@ def _stop_logging(body: dict):
return error
# Only a running trail records a stop; stopping a stopped trail keeps the last time.
if trail.get("IsLogging", True):
- trail["_StoppedAt"] = round(time.time(), 3)
+ trail["_StoppedAt"] = int(time.time())
trail["IsLogging"] = False
return _ok({})
diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.py
index 186a7e2b..25cd4581 100644
--- a/ministack/services/cloudwatch.py
+++ b/ministack/services/cloudwatch.py
@@ -1935,9 +1935,7 @@ def _error(code, message, status, use_json=False, use_cbor=False):
{"Content-Type": "application/x-amz-json-1.0", "x-amzn-errortype": code},
json.dumps({"__type": code, "message": message}).encode(),
)
- # Query-protocol error envelope per real-AWS captures (17-region
- # sweep): <Type> inside <Error> (Sender for 4xx, Receiver for 5xx)
- # and no <?xml?> declaration.
+ # Query error envelope: <Type> in <Error>, no <?xml?> (AWS captures).
fault_type = "Sender" if status < 500 else "Receiver"
body = (
f'<ErrorResponse xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">\n'
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 83051ebb..97aa2f7b 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -1296,6 +1296,8 @@ def _access_token_error(data: dict):
message = "Access Token has expired"
elif claims.get("origin_jti") in _revoked_tokens:
message = "Access Token has been revoked"
+ elif _API_TOKEN_SCOPE not in str(claims.get("scope", _API_TOKEN_SCOPE)).split():
+ message = "Access Token does not have required scopes"
else:
return None
return error_response_json("NotAuthorizedException", message, 400)
@@ -5171,6 +5173,9 @@ def _update_user_pool_domain(data):
"InvalidParameterException", "The domain is not configured for this user pool.", 400)
is_custom = pool.get("CustomDomain") == domain
custom_config = data.get("CustomDomainConfig")
+ if is_custom and custom_config is None:
+ return error_response_json(
+ "InvalidParameterException", "Cannot convert custom domain to prefix domain.", 400)
if custom_config is not None:
if not is_custom:
return error_response_json(
@@ -6253,6 +6258,14 @@ def handle_oauth2_authorize(method, path, headers, query_params):
if callback_urls and redirect_uri not in callback_urls:
return _oauth2_error("invalid_request", f"redirect_uri is not allowed: {redirect_uri}")
+ allowed_scopes = client.get("AllowedOAuthScopes") or []
+ if scope and allowed_scopes and any(s not in allowed_scopes for s in scope.split()):
+ sep = "&" if "?" in redirect_uri else "?"
+ location = f"{redirect_uri}{sep}error=invalid_request&error_description=invalid_scope"
+ if state:
+ location += f"&state={quote(state)}"
+ return 302, {"Location": location, "Cache-Control": "no-store"}, b""
+
if _use_choice_based_ui(client):
html_body = _username_page_html(
client_id, redirect_uri, scope, state, response_type,
@@ -7223,10 +7236,14 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Non
except (json.JSONDecodeError, TypeError):
pass
+ scope = _granted_scopes(client, form.get("scope"), "client_credentials")
+ if scope == "" and form.get("scope"):
+ # Nothing requested was granted: a resource-server scope the client lacks, or a non-custom scope.
+ error = "invalid_grant" if any("/" in s for s in form.get("scope", "").split()) else "invalid_scope"
+ return 400, {"Content-Type": "application/json"}, json.dumps({"error": error}).encode()
access_token = _fake_token(cid, pool_id, cid, "access",
trigger_source="TokenGeneration_ClientCredentials",
- client_metadata=client_metadata,
- scope=_granted_scopes(client, form.get("scope"), "client_credentials"))
+ client_metadata=client_metadata, scope=scope)
resp = {
"access_token": access_token,
"token_type": "Bearer",
diff --git a/ministack/services/documentdb.py b/ministack/services/documentdb.py
index bafce5d0..01b1e566 100644
--- a/ministack/services/documentdb.py
+++ b/ministack/services/documentdb.py
@@ -1694,8 +1694,7 @@ def _xml(status, root_tag, inner):
def _error(code, message, status):
"""Build an RDS-style XML error response."""
- # Real AWS Query-protocol error envelopes carry <Type>Sender|Receiver
- # </Type> and no <?xml?> declaration (17-region capture sweep).
+ # Query error envelope: <Type> in <Error>, no <?xml?> (AWS captures).
fault_type = "Sender" if 400 <= status < 500 else "Receiver"
body = f"""<ErrorResponse xmlns="http://rds.amazonaws.com/doc/2014-10-31/">
<Error><Type>{fault_type}</Type><Code>{code}</Code><Message>{message}</Message></Error>
diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.py
index 348231cd..01a4703a 100644
--- a/ministack/services/elasticache.py
+++ b/ministack/services/elasticache.py
@@ -3052,9 +3052,7 @@ def _xml(status, root_tag, inner):
def _error(code, message, status):
- # Query-protocol error envelope per real-AWS captures (17-region
- # sweep): <Type> inside <Error> (Sender for 4xx, Receiver for 5xx)
- # and no <?xml?> declaration.
+ # Query error envelope: <Type> in <Error>, no <?xml?> (AWS captures).
fault_type = "Sender" if 400 <= status < 500 else "Receiver"
body = f"""<ErrorResponse xmlns="http://elasticache.amazonaws.com/doc/2015-02-02/">
<Error><Type>{fault_type}</Type><Code>{code}</Code><Message>{message}</Message></Error>
diff --git a/ministack/services/iam.py b/ministack/services/iam.py
index 0bfcaa75..17ca78e8 100644
--- a/ministack/services/iam.py
+++ b/ministack/services/iam.py
@@ -3196,9 +3196,7 @@ def _error(status, code, message, ns="iam"):
"iam": "https://iam.amazonaws.com/doc/2010-05-08/",
"sts": "https://sts.amazonaws.com/doc/2011-06-15/",
}.get(ns, "")
- # Query-protocol error envelope per real-AWS captures (17-region
- # sweep): <Type> inside <Error> (Sender for 4xx, Receiver for 5xx)
- # and no <?xml?> declaration.
+ # Query error envelope: <Type> in <Error>, no <?xml?> (AWS captures).
fault_type = "Sender" if status < 500 else "Receiver"
body = (f'<ErrorResponse xmlns="{ns_url}">'
f'<Error><Type>{fault_type}</Type><Code>{code}</Code><Message>{message}</Message></Error>'
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 5d024c0a..a296c2b8 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -24,9 +24,9 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:
``CreateProvisioningClaim``, and fleet provisioning over MQTT
(``$aws/certificates/create/json`` and
``$aws/provisioning-templates/{name}/provision/json``, after the
- template's pre-provisioning hook allows it);
- ``provisioningRoleArn`` is presence-checked but not resolved
- (MiniStack does not validate IAM role ARNs elsewhere either)
+ template's pre-provisioning hook allows it); with ``AUTH=true``
+ RegisterThing needs a ``provisioningRoleArn`` that IoT may assume and
+ that allows its writes
- Policies: ``CreatePolicy``, ``CreatePolicyVersion``, ``AttachPolicy``,
``DetachPolicy``, etc., plus the deprecated principal-policy family
(``AttachPrincipalPolicy`` / ``DetachPrincipalPolicy`` /
@@ -529,7 +529,6 @@ _NOT_FOUND_MESSAGES = {
"ThingType": "Thing Type {account}:{name} not found.",
"ThingGroup": "ThingGroup {account}:{name} not found.",
"UpdateThingGroup": "Group {name} does not exist",
- "CreateThingGroup": "Cannot create group using non-existing group as parent : {name}",
"ThingGroupMember": "Cannot find requested thing group for accountId: {account} and thing group name: {name}",
"Certificate": "CertificateId {name} does not exist",
"CACertificate": "Requested CA Certificate does not exist.",
@@ -1744,7 +1743,9 @@ def _create_thing_group(name: str, payload: dict) -> tuple:
attr_payload = props.get("attributePayload") or {}
parent = payload.get("parentGroupName")
if parent and parent not in _thing_groups:
- return _error_not_found("CreateThingGroup", parent)
+ return error_response_json(
+ "InvalidRequestException", f"Cannot create group using non-existing group as parent : {parent}", 400
+ )
record = {
"thingGroupName": name,
"thingGroupId": new_uuid(),
@@ -1936,10 +1937,10 @@ async def _remove_thing_from_group(payload: dict) -> tuple:
#
# CRUD, CreateProvisioningClaim and the fleet provisioning MQTT API (JSON
# topics) that applies a template to a certificate created over MQTT, once the
-# template's pre-provisioning hook allows it. provisioningRoleArn is
-# presence-checked but never resolved — MiniStack does
-# not validate IAM role ARNs elsewhere either. A template keeps up to five
-# body versions; Describe and RegisterThing use the default one. Wire shapes and
+# template's pre-provisioning hook allows it; with AUTH=true RegisterThing
+# answers AccessDenied unless provisioningRoleArn names a role IoT may assume
+# that allows every write it makes. Template versions are not
+# modeled: a template always carries defaultVersionId 1. Wire shapes and
# error messages mirror a live probe of the real service (2026-08-26).
# ---------------------------------------------------------------------------
@@ -2496,6 +2497,10 @@ async def _fleet_register_thing(
if not template.get("enabled"):
return _fleet_rejected("InvalidTemplate", f"Template {template_name} is not enabled.")
token = request.get("certificateOwnershipToken")
+ if token is None or token == "":
+ return _fleet_rejected(
+ "InvalidCertificateOwnershipToken", "Certificate ownership token cannot be empty."
+ )
record = _ownership_tokens.get(token) if isinstance(token, str) else None
cert = (
_certificates.get(record["certificateId"])
@@ -2522,7 +2527,7 @@ async def _fleet_register_thing(
"InvalidCertificateOwnershipToken", "Certificate ownership token is invalid."
)
plan = _provisioning_plan(template, parameters, cert["certificateId"])
- thing_name = await _apply_provisioning_plan(plan, cert)
+ thing_name = await _apply_provisioning_plan(plan, cert, template.get("provisioningRoleArn") or "")
reply = {"deviceConfiguration": plan["deviceConfiguration"]}
if thing_name is not None:
reply["thingName"] = thing_name
@@ -2594,7 +2599,7 @@ def _provisioning_hook_overrides(result: dict) -> dict:
def _provisioning_plan(template: dict, parameters: dict, cert_id: str) -> dict:
- """The template's resources with ``Ref`` and ``Fn::Join`` resolved against the parameters."""
+ """The template's resources with ``Ref`` and the intrinsic functions resolved against the parameters."""
body = _provisioning_template_body(template)
body = json.loads(body) if isinstance(body, str) else body
declared = body.get("Parameters")
@@ -2605,6 +2610,26 @@ def _provisioning_plan(template: dict, parameters: dict, cert_id: str) -> dict:
}
values.update(parameters)
values[_CERTIFICATE_ID_PARAMETER] = cert_id
+ mappings = body.get("Mappings") if isinstance(body.get("Mappings"), dict) else {}
+
+ def invalid(function):
+ return _ProvisioningRejected(
+ "InvalidTemplate", f"Template {template['templateName']} has an invalid {function}."
+ )
+
+ def reference(name):
+ if values.get(name) is None:
+ raise _ProvisioningRejected("InvalidParameters", f"Cannot resolve reference value: {name}")
+ return values[name]
+
+ def substitute(text, variables):
+ def one(match):
+ name = match.group(1)
+ if name.startswith("!"):
+ return "${" + name[1:] + "}"
+ return str(variables[name]) if name in variables else str(reference(name))
+
+ return re.sub(r"\$\{([^}]*)\}", one, text)
def resolve(value):
if isinstance(value, list):
@@ -2614,24 +2639,46 @@ def _provisioning_plan(template: dict, parameters: dict, cert_id: str) -> dict:
if len(value) == 1:
function, argument = next(iter(value.items()))
if function == "Ref":
- if values.get(argument) is None:
- raise _ProvisioningRejected(
- "InvalidParameters", f"Cannot resolve reference value: {argument}"
- )
- return values[argument]
- if (
- function == "Fn::Join"
- and isinstance(argument, list)
- and len(argument) == 2
- and isinstance(argument[1], list)
- ):
- return str(argument[0]).join(str(resolve(v)) for v in argument[1])
- if function.startswith("Fn::"):
- raise _ProvisioningRejected(
- "InvalidTemplate",
- f"Template {template['templateName']} uses {function}, "
- "which MiniStack does not resolve.",
- )
+ return reference(argument)
+ if not function.startswith("Fn::"):
+ return {function: resolve(argument)}
+ argument = resolve(argument)
+ if function == "Fn::Join":
+ if not (isinstance(argument, list) and len(argument) == 2 and isinstance(argument[1], list)):
+ raise invalid(function)
+ return str(argument[0]).join(str(v) for v in argument[1])
+ if function == "Fn::Select":
+ if not (isinstance(argument, list) and len(argument) == 2 and isinstance(argument[1], list)):
+ raise invalid(function)
+ try:
+ index = int(argument[0])
+ except (TypeError, ValueError):
+ raise invalid(function) from None
+ if not 0 <= index < len(argument[1]) or argument[1][index] is None:
+ raise invalid(function)
+ return argument[1][index]
+ if function == "Fn::Split":
+ if not (isinstance(argument, list) and len(argument) == 2
+ and isinstance(argument[0], str) and isinstance(argument[1], str) and argument[0]):
+ raise invalid(function)
+ return argument[1].split(argument[0])
+ if function == "Fn::FindInMap":
+ if not (isinstance(argument, list) and len(argument) == 3):
+ raise invalid(function)
+ found = mappings.get(argument[0])
+ found = found.get(argument[1]) if isinstance(found, dict) else None
+ found = found.get(argument[2]) if isinstance(found, dict) else None
+ if found is None:
+ raise invalid(function)
+ return found
+ if function == "Fn::Sub":
+ if isinstance(argument, str):
+ return substitute(argument, {})
+ if (isinstance(argument, list) and len(argument) == 2
+ and isinstance(argument[0], str) and isinstance(argument[1], dict)):
+ return substitute(argument[0], argument[1])
+ raise invalid(function)
+ raise invalid(function)
return {k: resolve(v) for k, v in value.items()}
plan = {"thing": None, "status": "ACTIVE", "policies": []}
@@ -2646,13 +2693,19 @@ def _provisioning_plan(template: dict, parameters: dict, cert_id: str) -> dict:
elif kind == "AWS::IoT::Certificate":
plan["status"] = str(properties.get("Status") or "ACTIVE").upper()
elif kind == "AWS::IoT::Policy":
- if "PolicyDocument" in properties:
- raise _ProvisioningRejected(
- "InvalidTemplate",
- f"Template {template['templateName']} creates a policy from a "
- "PolicyDocument, which MiniStack does not support.",
- )
- plan["policies"].append(properties.get("PolicyName"))
+ document = properties.get("PolicyDocument")
+ if document is None:
+ plan["policies"].append((properties.get("PolicyName"), None))
+ continue
+ if "PolicyName" in properties:
+ raise invalid("AWS::IoT::Policy")
+ document = document if isinstance(document, str) else json.dumps(document)
+ try:
+ json.loads(document)
+ except ValueError:
+ raise invalid("AWS::IoT::Policy") from None
+ # The developer guide: PolicyName "Defaults to a hash of the policy document".
+ plan["policies"].append((hashlib.sha256(document.encode("utf-8")).hexdigest(), document))
plan["deviceConfiguration"] = resolve(body.get("DeviceConfiguration") or {})
return plan
@@ -2661,17 +2714,23 @@ def _java_map(attributes: dict) -> str:
return "{" + ", ".join(f"{k}={v}" for k, v in sorted(attributes.items())) + "}"
-async def _apply_provisioning_plan(plan: dict, cert: dict) -> str | None:
+async def _apply_provisioning_plan(plan: dict, cert: dict, role_arn: str) -> str | None:
"""Create or update the thing, then activate and attach the certificate; a rejection changes nothing."""
account = get_account_id()
- for policy in plan["policies"]:
- if _policies.get(policy) is None:
+ for policy, document in plan["policies"]:
+ if document is None and _policies.get(policy) is None:
raise _provisioning_failed(
"Register thing workflow execution terminates due to: Policy default version not found"
)
- if plan["thing"] is None:
- name = None
- else:
+ cert_arn = cert["certificateArn"]
+ requests = [("iot:UpdateCertificate", cert_arn)]
+ for policy, document in plan["policies"]:
+ if document is not None and _policies.get(policy) is None:
+ requests.append(("iot:CreatePolicy", _policy_arn(policy)))
+ requests.append(("iot:AttachPolicy", cert_arn))
+ name = update = None
+ join = leave = []
+ if plan["thing"] is not None:
properties, overrides = plan["thing"]
name = properties.get("ThingName")
if not isinstance(name, str) or not _NAME_RE.match(name):
@@ -2692,34 +2751,81 @@ async def _apply_provisioning_plan(plan: dict, cert: dict) -> str | None:
)
thing = _things.get(name)
if thing is None:
- _create_thing(name, {
- "attributePayload": {"attributes": attributes or {}},
- "thingTypeName": type_name or None,
- })
- join, leave = list(groups or ()), []
+ join = list(groups or ())
+ requests.append(("iot:CreateThing", _thing_arn(name)))
else:
update, join, leave = _provisioning_thing_changes(
thing, attributes, type_name, groups, overrides
)
if update:
- _update_thing(name, update)
+ requests.append(("iot:UpdateThing", _thing_arn(name)))
+ requests += [("iot:AddThingToThingGroup", _thing_group_arn(g)) for g in join]
+ requests += [("iot:RemoveThingFromThingGroup", _thing_group_arn(g)) for g in leave]
+ requests.append(("iot:AttachThingPrincipal", _thing_arn(name)))
+ if not _provisioning_role_allows(role_arn, requests):
+ raise _ProvisioningRejected("AccessDenied", "Access Denied", 403)
+ if name is not None:
+ if _things.get(name) is None:
+ _create_thing(name, {
+ "attributePayload": {"attributes": attributes or {}},
+ "thingTypeName": type_name or None,
+ })
+ elif update:
+ _update_thing(name, update)
for group in join:
await _add_thing_to_group({"thingGroupName": group, "thingName": name})
for group in leave:
await _remove_thing_from_group({"thingGroupName": group, "thingName": name})
thing = _things[name]
- if cert["certificateArn"] not in thing.setdefault("principals", []):
- thing["principals"].append(cert["certificateArn"])
+ if cert_arn not in thing.setdefault("principals", []):
+ thing["principals"].append(cert_arn)
_things[name] = thing
if thing["thingArn"] not in cert.setdefault("attachedThings", []):
cert["attachedThings"].append(thing["thingArn"])
cert["status"] = plan["status"]
_certificates[cert["certificateId"]] = cert
- for policy in plan["policies"]:
- _change_policy_target(policy, cert["certificateArn"], attach=True)
+ for policy, document in plan["policies"]:
+ if document is not None and _policies.get(policy) is None:
+ _create_policy(policy, {"policyDocument": document})
+ _change_policy_target(policy, cert_arn, attach=True)
return name
+def _provisioning_role_allows(role_arn: str, requests: list[tuple[str, str]]) -> bool:
+ """Under AUTH=true, whether the template's provisioning role is one IoT may assume and allows every write."""
+ from ministack import app
+
+ if not app.AUTH:
+ return True
+ if not _iot_role_usable(role_arn):
+ return False
+ from ministack.core.iam_evaluator import (
+ EvalContext,
+ _gather_role_policies,
+ _permissions_boundary,
+ evaluate,
+ )
+ from ministack.services import iam as _iam
+
+ account = get_account_id()
+ role_name = role_arn.rsplit("/", 1)[-1]
+ policies = _gather_role_policies(role_name, account)
+ limits = _permissions_boundary(_iam._roles, role_name, account)
+ principal = f"arn:aws:sts::{account}:assumed-role/{role_name}/IoTProvisioning"
+ for action, resource in requests:
+ ctx = EvalContext(
+ principal_arn=principal,
+ principal_type="AssumedRole",
+ principal_account=account,
+ action=action,
+ resource_arn=resource,
+ region=get_region(),
+ )
+ if evaluate(ctx, policies, *limits).decision != "Allow":
+ return False
+ return True
+
+
def _provisioning_thing_changes(
thing: dict, attributes, type_name, groups, overrides: dict
) -> tuple[dict, list, list]:
@@ -3772,7 +3878,7 @@ def _set_default_policy_version(name: str, version_id: str) -> tuple:
)
p = _policies.get(name)
if p is None:
- return _error_not_found("Policy", name)
+ return error_response_json("ResourceNotFoundException", "Policy not found", 404)
if version_id not in p["versions"]:
return error_response_json(
"ResourceNotFoundException",
@@ -7982,6 +8088,37 @@ _JOB_PRESIGN_SESSION_REUSE_SECONDS = 3600
_jobs_presign_sessions: dict[tuple[str, str], str] = {}
+def _iot_role_usable(role_arn: str) -> bool:
+ """Under AUTH=true, whether the role exists in the caller's account and its trust policy lets IoT assume it."""
+ from ministack import app
+
+ if not app.AUTH:
+ return True
+ from ministack.core.iam_evaluator import _action_matches, _service_principal_matches
+ from ministack.services import iam as _iam
+
+ parts = role_arn.split(":", 5)
+ if len(parts) != 6 or parts[4] != get_account_id() or not parts[5].startswith("role/"):
+ return False
+ role = _iam._roles.get(parts[5].rsplit("/", 1)[-1])
+ try:
+ statements = json.loads((role or {}).get("AssumeRolePolicyDocument") or "{}").get("Statement", [])
+ except (ValueError, AttributeError):
+ return False
+ allowed = False
+ for stmt in statements if isinstance(statements, list) else [statements]:
+ if not isinstance(stmt, dict) or not _service_principal_matches(stmt.get("Principal"), "iot.amazonaws.com"):
+ continue
+ actions, not_actions = stmt.get("Action", []), stmt.get("NotAction", [])
+ if not _action_matches("sts:AssumeRole", [actions] if isinstance(actions, str) else actions,
+ [not_actions] if isinstance(not_actions, str) else not_actions):
+ continue
+ if stmt.get("Effect") == "Deny":
+ return False
+ allowed = allowed or stmt.get("Effect") == "Allow"
+ return allowed
+
+
def _jobs_presign_session(role_arn: str, expires: int) -> tuple[str, dict]:
"""A session of the presign role, registered with STS, that outlives a URL signed now."""
from ministack.services import iam as _iam
@@ -8015,7 +8152,7 @@ def _jobs_presigned_document(job: dict) -> str:
config = job.get("presignedUrlConfig")
if "${aws:iot:s3-presigned-url" not in document or not (
isinstance(config, dict) and config.get("roleArn")
- ):
+ ) or not _iot_role_usable(config["roleArn"]):
return document
from ministack.core.sigv4 import (
build_canonical_query_string,
@@ -10780,6 +10917,11 @@ class _WSSession:
def _publish_allowed(self, topic: str, retain: bool) -> bool:
"""iot:Publish on the topic, and iot:RetainPublish too for a retained message."""
+ from ministack import app
+
+ if app.AUTH and self.certificate_id is None and _parse_fleet_provisioning_topic(topic):
+ # Fleet provisioning writes the registry: under AUTH=true it needs an authenticated device.
+ return False
resource = f"topic/{topic}"
return self._policy_allows("iot:Publish", resource) and (
not retain or self._policy_allows("iot:RetainPublish", resource)
@@ -11065,6 +11207,12 @@ class _WSSession:
if self.protocol_version == MQTT_5:
await self.send_bytes(_make_disconnect(RC5_NOT_AUTHORIZED))
return False
+ if self.provisioning_template is not None and _mtls_claim_scope(self.certificate_id) is None:
+ # AWS acknowledges a PUBLISH on an expired claim's connection, then closes it.
+ _broker_logger.warning("IoT broker: the provisioning claim of %r has expired", self._client_id)
+ if qos == 1 and packet_id is not None:
+ await self.send_bytes(_make_puback(packet_id))
+ return await self._close_unauthorized()
if not self._publish_allowed(topic, retain):
# MQTT 5 answers a refused QoS 1 PUBLISH with PUBACK 0x87 and
# keeps the connection.
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index e0492132..53ffca36 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -5630,15 +5630,12 @@ def _begin_instance_reboot(p):
return invalid_arn
return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)
if instance.get("DBInstanceStatus") != "available":
- return _error("InvalidDBInstanceState", "DB instance must be available to reboot.", 400)
- # A local fault-injection setting, not an AWS request parameter. Keep the
- # engine stopped during this interval so clients experience real downtime.
- try:
- downtime = float(os.environ.get("RDS_REBOOT_DOWNTIME_SECONDS", "0"))
- if not 0 <= downtime <= 3600:
- raise ValueError
- except ValueError:
- return _error("InvalidParameterValue", "RDS_REBOOT_DOWNTIME_SECONDS must be between 0 and 3600.", 400)
+ return _error(
+ "InvalidDBInstanceState",
+ f"DBInstance {db_id} is in {instance.get('DBInstanceStatus')} state but expected "
+ "it to be one of available.",
+ 400,
+ )
cluster_id = instance.get("_shared_cluster_id") or instance.get("DBClusterIdentifier")
cluster = _resolve_cluster_in_request_region(cluster_id) if cluster_id else None
if cluster and (switch_error := _begin_mysql_global_instance_mutation(cluster)):
@@ -5649,7 +5646,7 @@ def _begin_instance_reboot(p):
response = _single_instance_response("RebootDBInstanceResponse", "RebootDBInstanceResult", instance)
context = contextvars.copy_context()
threading.Thread(
- target=context.run, args=(_finish_instance_reboot, instance, cluster, downtime),
+ target=context.run, args=(_finish_instance_reboot, instance, cluster),
daemon=True,
).start()
return response
@@ -5664,7 +5661,7 @@ def _record_reboot_event(instance):
_events[new_uuid()] = {
"SourceIdentifier": instance["DBInstanceIdentifier"],
"SourceType": "db-instance", "SourceArn": instance.get("DBInstanceArn", ""),
- "Message": "DB instance restarted", "Date": now,
+ "Message": "DB instance restarted.", "Date": now,
"EventCategories": ["availability"],
}
@@ -5675,7 +5672,9 @@ def _describe_events(p):
kind = _p(p, "SourceType")
if source and not kind:
return _error("InvalidParameterCombination", "SourceIdentifier requires SourceType.", 400)
- if kind and kind not in ("db-instance", "db-cluster", "db-parameter-group", "db-security-group", "db-snapshot", "db-cluster-snapshot", "db-proxy", "blue-green-deployment", "zero-etl"):
+ if kind and kind not in ("db-instance", "db-parameter-group", "db-security-group", "db-snapshot", "db-cluster",
+ "db-cluster-snapshot", "custom-engine-version", "db-proxy", "blue-green-deployment",
+ "db-shard-group", "zero-etl"):
return _error("InvalidParameterValue", "Invalid SourceType.", 400)
def timestamp(value, default):
if not value:
@@ -5719,7 +5718,7 @@ def _describe_events(p):
return _xml(200, "DescribeEventsResponse", f"<DescribeEventsResult><Events>{members}</Events>{next_marker}</DescribeEventsResult>")
-def _finish_instance_reboot(instance, cluster, downtime):
+def _finish_instance_reboot(instance, cluster):
db_id = instance["DBInstanceIdentifier"]
def current():
@@ -5731,8 +5730,6 @@ def _finish_instance_reboot(instance, cluster, downtime):
if client and container_id:
container = client.containers.get(container_id)
container.stop(timeout=5)
- if downtime:
- time.sleep(downtime)
if not current():
return
container.start()
@@ -5753,8 +5750,6 @@ def _finish_instance_reboot(instance, cluster, downtime):
instance.get("DBName"), alive,
):
raise RuntimeError("database stopped before reboot readiness")
- elif downtime:
- time.sleep(downtime)
if current():
_record_reboot_event(instance)
instance["DBInstanceStatus"] = "available"
@@ -11402,11 +11397,7 @@ def _xml(status, root_tag, inner):
def _error(code, message, status):
- # Real AWS Query-protocol error envelopes include
- # <Type>Sender|Receiver</Type> — Sender for 4xx (caller's fault),
- # Receiver for 5xx — and carry no <?xml?> declaration (17-region
- # real-AWS capture sweep). Most SDKs ignore the field but it's part
- # of the observed AWS shape.
+ # Query error envelope: <Type> in <Error>, no <?xml?> (AWS captures).
fault_type = "Sender" if 400 <= status < 500 else "Receiver"
body = f"""<ErrorResponse xmlns="http://rds.amazonaws.com/doc/2014-10-31/">
<Error><Type>{fault_type}</Type><Code>{code}</Code><Message>{message}</Message></Error>
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index f6844ef2..482cb89f 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -958,14 +958,10 @@ def _foreign_bucket_allows(owner_account: str, bucket_name: str, key: str,
groups = [_ACL_GROUP_ALL_USERS] if not caller else [
_ACL_GROUP_ALL_USERS, _ACL_GROUP_AUTHENTICATED]
- acls = [_bucket_acl.get_scoped(owner_account, None, bucket_name)]
- record = _buckets.get_scoped(owner_account, None, bucket_name)
- if key and record is not None:
- version_id = _resolve_subresource_version(query_params, record, key)
- acls.append(_object_acl.get_scoped(owner_account, None, (bucket_name, key, version_id)))
- for stored in acls:
- for uri, permission in _acl_group_grants(stored):
- if uri in groups and permission in wants:
+ for stored, granted in ((_bucket_acl.get_scoped(owner_account, None, bucket_name), wants),
+ (object_acl, object_wants)):
+ for uri, permission in _acl_grants(stored):
+ if uri in groups and permission in granted:
return True
policy = _bucket_policies.get_scoped(owner_account, None, bucket_name)
@@ -2106,6 +2102,7 @@ async def handle_request(
body: bytes,
query_params: dict,
signed_path: str | None = None,
+ enforce_bucket_region: bool = True,
internal: bool = False,
) -> tuple:
bucket, key = _parse_bucket_key(path, headers)
@@ -2128,6 +2125,9 @@ async def handle_request(
headers = _merge_hoisted_amz_headers(headers, query_params)
denied = _apply_bucket_scope(method, bucket, key, headers, query_params, body, internal)
+ if denied is None and enforce_bucket_region:
+ # After the scope is pinned, so the owner's record names the home region.
+ denied = _check_bucket_region(method, bucket, key, headers, query_params)
if denied is not None:
status, resp_headers, resp_body = denied
resp_headers.setdefault("x-amz-request-id", new_uuid())
@@ -2509,6 +2509,12 @@ def _create_bucket(name: str, body: bytes, headers: dict = None, endpoint_region
# request was signed for, like real AWS.
region = region or get_region()
_buckets[name] = {"created": now_iso(), "objects": {}, "region": region}
+ ownership = headers.get("x-amz-object-ownership")
+ if ownership:
+ # The same document PutBucketOwnershipControls stores.
+ root = Element("OwnershipControls", xmlns=S3_NS)
+ SubElement(SubElement(root, "Rule"), "ObjectOwnership").text = ownership
+ _buckets[name]["_ownership_controls"] = _xml_body(root).decode()
if tags:
_bucket_tags[name] = tags
if canned_acl:
@@ -5046,18 +5052,20 @@ def _replication_destination(bucket_name: str, key: str, rule: dict, role: str):
def _maybe_replicate_delete_marker(bucket_name: str, key: str) -> None:
- """Replicate a delete marker the way AWS does: only for a V2 rule (one with
- ``Filter``) that has ``DeleteMarkerReplication`` Enabled and no tag filter.
- Called only for deletes without a version id; version-id deletes never
- replicate. Replica markers are not re-replicated, so two-way setups don't
- loop."""
+ """Replicate a delete marker the way AWS does: always for a V1 rule (no
+ ``Filter``), and for a V2 rule only with ``DeleteMarkerReplication`` Enabled
+ and no tag filter. Called only for deletes without a version id; version-id
+ deletes never replicate. Replica markers are not re-replicated, so two-way
+ setups don't loop."""
config = _bucket_replication.get(bucket_name)
if not config or _bucket_versioning.get(bucket_name) != "Enabled":
return
rule = next((r for r in config.get("Rules", [])
if r.get("Status") == "Enabled" and key.startswith(_replication_rule_prefix(r))), None)
- if (rule is None or "Filter" not in rule or _replication_rule_tags(rule)
- or (rule.get("DeleteMarkerReplication") or {}).get("Status") != "Enabled"):
+ if rule is None:
+ return
+ if "Filter" in rule and (_replication_rule_tags(rule)
+ or (rule.get("DeleteMarkerReplication") or {}).get("Status") != "Enabled"):
return
target = _replication_destination(bucket_name, key, rule, config.get("Role", ""))
if target is None:
diff --git a/ministack/services/ses.py b/ministack/services/ses.py
index fa7775a7..4846da51 100644
--- a/ministack/services/ses.py
+++ b/ministack/services/ses.py
@@ -1412,9 +1412,7 @@ def _xml(status, root_tag, inner):
def _error(code, message, status, error_type="", fields=None):
- # Query-protocol error envelope per real-AWS captures (17-region
- # sweep): <Type> inside <Error> (Sender for 4xx, Receiver for 5xx —
- # callers may pin an explicit value) and no <?xml?> declaration.
+ # Query error envelope: <Type> in <Error>, no <?xml?> (AWS captures).
error_type = error_type or ("Sender" if status < 500 else "Receiver")
message_xml = f"<Message>{_esc(message)}</Message>" if message is not None else ""
message_xml += "".join(f"<{k}>{_esc(v)}</{k}>" for k, v in (fields or {}).items())
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index e2382d07..f1ed8ab4 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -132,8 +132,6 @@ def _get_topic(topic_arn: str, action: str | None = None):
Returns ``(topic, None)`` on success or ``(None, error_tuple)`` with a
``NotFound`` (404) or ``AuthorizationError`` (403) response.
- ``not_found_error`` overrides the NotFound response for the APIs where
- real AWS evaluates authorization before existence.
"""
arn = _normalize_arn(topic_arn)
topic = _topic_by_arn_any_scope(arn)
@@ -489,16 +487,7 @@ def _list_topics(params):
def _get_topic_attributes(params):
- # Real AWS evaluates authorization before existence on this API:
- # GetTopicAttributes on a nonexistent topic answers
- # InvalidClientTokenId at 403, not NotFound/404 (real AWS wire
- # capture). Neighboring topic APIs were not captured, so they keep
- # their existing NotFound/404 ordering.
- topic, err = _get_topic(
- _p(params, "TopicArn"), "sns:GetTopicAttributes",
- not_found_error=_error(
- "InvalidClientTokenId",
- "The security token included in the request is invalid.", 403))
+ topic, err = _get_topic(_p(params, "TopicArn"), "sns:GetTopicAttributes")
if err is not None:
return err
_refresh_subscription_counts(topic)
@@ -1685,8 +1674,7 @@ def _xml(status, root_tag, inner):
def _error(code, message, status):
- # Query-protocol error envelope per real-AWS captures (17-region
- # sweep): <Type> inside <Error> and no <?xml?> declaration.
+ # Query error envelope: <Type> in <Error>, no <?xml?> (AWS captures).
error_type = "Sender" if status < 500 else "Receiver"
body = (
f'<ErrorResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">'
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 617582ea..0e42583f 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -515,15 +515,9 @@ def _describe_state_machine(data):
"loggingConfiguration": base_sm.get("loggingConfiguration", {"level": "OFF"}),
"revisionId": base_sm.get("revisionId", ""),
})
- # Real AWS evaluates authorization before existence on
- # DescribeStateMachine: a stateMachineArn that resolves to nothing
- # (no machine, version, or alias) answers AccessDeniedException, not
- # StateMachineDoesNotExist (real AWS wire capture; also the API
- # reference's error list). Other lookups were not captured and keep
- # StateMachineDoesNotExist.
return error_response_json(
- "AccessDeniedException",
- "User is not authorized to access this resource.", 400)
+ "StateMachineDoesNotExist",
+ f"State machine {arn} not found", 400)
def _update_state_machine(data):
diff --git a/ministack/services/waf.py b/ministack/services/waf.py
index 53e742a5..dd0519fd 100644
--- a/ministack/services/waf.py
+++ b/ministack/services/waf.py
@@ -630,7 +630,12 @@ def _regex_pattern_set_body(rps):
def _create_regex_pattern_set(data):
name = data.get("Name", "")
+ if not name:
+ return _waf_err("WAFInvalidParameterException", "Name is required")
scope = _normalize_scope(data.get("Scope", "REGIONAL"))
+ for existing in _values_for_scope(_regex_pattern_sets, scope):
+ if existing["Name"] == name and existing.get("Scope") == scope:
+ return _waf_err("WAFDuplicateItemException", f"A RegexPatternSet with name '{name}' already exists.")
uid = new_uuid()
lock_token = new_uuid()
arn = _regex_pattern_set_arn(name, uid, scope)
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 8ee927df..6aefd4a8 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -27864,7 +27864,7 @@ def test_cfn_apigateway_deployment_update_in_place_and_replacement(cfn, apigw_v1
def test_cfn_iot_thing_group_missing_parent_fails_and_unmodelled_properties_are_accepted(cfn, iot_client):
"""A parent that does not exist fails the stack with the service's own
- ResourceNotFoundException; QueryString (dynamic groups), which the service
+ InvalidRequestException; QueryString (dynamic groups), which the service
does not model, is accepted without effect."""
uid = _uuid_mod.uuid4().hex[:8]
stack_name = f"cfn-thing-group-edge-{uid}"
@@ -27875,7 +27875,7 @@ def test_cfn_iot_thing_group_missing_parent_fails_and_unmodelled_properties_are_
try:
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "ROLLBACK_COMPLETE", stack.get("StackStatusReason")
- assert "ResourceNotFoundException" in _stack_event_reasons(cfn, stack_name)
+ assert "InvalidRequestException" in _stack_event_reasons(cfn, stack_name)
with pytest.raises(ClientError):
iot_client.describe_thing_group(thingGroupName=f"cfn-tg-orphan-{uid}")
finally:
@@ -30016,6 +30016,18 @@ def test_cognito_change_set_reports_mfa_configuration_in_place(cfn, stack):
assert change["Replacement"] == "False"
+def test_appsync_change_set_reports_graphql_schema_api_id_in_place(cfn, appsync, stack):
+ """AWS::AppSync::GraphQLSchema ApiId is "Update requires: No interruption" in the CloudFormation reference."""
+ apis = [appsync.create_graphql_api(name=f"schema-{_uuid_mod.uuid4().hex[:8]}",
+ authenticationType="API_KEY")["graphqlApi"]["apiId"] for _ in range(2)]
+ definition = "type Query { a: String }"
+ old = _template("AWS::AppSync::GraphQLSchema", {"ApiId": apis[0], "Definition": definition})
+ new = _template("AWS::AppSync::GraphQLSchema", {"ApiId": apis[1], "Definition": definition})
+ change = _change(cfn, stack(old), new)
+ assert _requirements(change) == {"ApiId": "Never"}
+ assert change["Replacement"] == "False"
+
+
@pytest.mark.parametrize("prop,value,recreation,replacement", [
("ManagedLoginVersion", 2, "Never", "False"),
("Domain", None, "Always", "True"),
@@ -36326,22 +36338,20 @@ def foreign_bucket():
s3_svc._buckets.pop_scoped("111122223333", None, name, None)
-def test_cfn_s3_bucket_other_account_name_is_refused(foreign_bucket, monkeypatch):
+def test_cfn_s3_bucket_other_account_name_is_refused(foreign_bucket):
from ministack.services import s3 as s3_svc
from ministack.services.cloudformation import provisioners
- for adopt in (True, False):
- monkeypatch.setattr(provisioners, "CFN_S3_ADOPT_EXISTING_BUCKET", adopt)
- with pytest.raises(ValueError) as exc:
- provisioners._s3_create("B", {"BucketName": foreign_bucket}, "stack")
- assert str(exc.value) == _NAME_EXISTS.format(foreign_bucket)
- # Rename on update and recreate go through the same check.
- with pytest.raises(ValueError):
- provisioners._s3_update("old-name", {"BucketName": "old-name"}, {"BucketName": foreign_bucket}, "stack")
+ with pytest.raises(ValueError) as exc:
+ provisioners._s3_create("B", {"BucketName": foreign_bucket}, "stack")
+ assert str(exc.value) == f"{foreign_bucket} already exists"
+ # Rename on update and recreate go through the same check.
+ with pytest.raises(ValueError):
+ provisioners._s3_update("old-name", {"BucketName": "old-name"}, {"BucketName": foreign_bucket}, "stack")
assert s3_svc._buckets.get(foreign_bucket) is None
-def test_cfn_s3_bucket_adopt_existing_setting(monkeypatch):
+def test_cfn_s3_bucket_existing_own_name_is_refused_and_auto_names_are_fresh():
import contextvars
from ministack.services import s3 as s3_svc
@@ -36350,30 +36360,19 @@ def test_cfn_s3_bucket_adopt_existing_setting(monkeypatch):
name = f"cfn-own-{_uuid_mod.uuid4().hex[:8]}"
s3_svc._buckets[name] = {"created": "", "objects": {"k": {}}, "region": "us-east-1"}
try:
- monkeypatch.setattr(provisioners, "CFN_S3_ADOPT_EXISTING_BUCKET", True)
- assert provisioners._s3_create("B", {"BucketName": name}, "stack")[0] == name
- assert s3_svc._buckets[name]["objects"] == {"k": {}}
-
- monkeypatch.setattr(provisioners, "CFN_S3_ADOPT_EXISTING_BUCKET", False)
with pytest.raises(ValueError) as exc:
provisioners._s3_create("B", {"BucketName": name}, "stack")
- assert str(exc.value) == _NAME_EXISTS.format(name)
+ assert str(exc.value) == f"{name} already exists"
+ assert s3_svc._buckets[name]["objects"] == {"k": {}}
finally:
s3_svc._buckets.pop(name, None)
- def create_auto_named():
- return provisioners._s3_create("Assets", {}, "seeded-stack")[0]
-
created = []
try:
- monkeypatch.setattr(provisioners, "CFN_S3_ADOPT_EXISTING_BUCKET", True)
- first, again = (contextvars.copy_context().run(create_auto_named) for _ in range(2))
- assert first == again # adoption keeps the deterministic name
- created.append(first)
- monkeypatch.setattr(provisioners, "CFN_S3_ADOPT_EXISTING_BUCKET", False)
- one, two = (contextvars.copy_context().run(create_auto_named) for _ in range(2))
+ one, two = (contextvars.copy_context().run(provisioners._s3_create, "Assets", {}, "seeded-stack")[0]
+ for _ in range(2))
created += [one, two]
- assert len({first, one, two}) == 3 # a fresh name per stack instance
+ assert one != two # a fresh name per stack instance
assert one.startswith("seeded-stack-assets-")
finally:
for bucket in created:
@@ -36437,15 +36436,72 @@ def test_cfn_s3_name_conflict_validation(cfn, other_account_bucket, disable_roll
assert {e["OperationId"] for e in ops} == {error["OperationId"]}
failed_only = cfn.describe_events(StackName=stack_name, Filters={"FailedEvents": True})["OperationEvents"]
assert error["EventId"] in {e["EventId"] for e in failed_only}
+ # Every DescribeEvents member is optional: the operation id alone finds the same events.
+ by_operation = cfn.describe_events(OperationId=error["OperationId"])["OperationEvents"]
+ assert {e["EventId"] for e in by_operation} == {e["EventId"] for e in ops}
finally:
_delete_cfn_test_stack(cfn, stack_name)
-def test_cfn_s3_name_conflict_own_bucket_when_adoption_is_off(monkeypatch):
- """In-process: with CFN_S3_ADOPT_EXISTING_BUCKET=0, an own existing name
- is a NAME_CONFLICT_VALIDATION error too."""
+def _events_since_last_update(cfn, stack_name):
+ events = _stack_level_events(cfn, stack_name)
+ start = max(i for i, e in enumerate(events)
+ if e["LogicalResourceId"] == stack_name and e["ResourceStatus"] == "UPDATE_IN_PROGRESS")
+ return events[start:]
+
+
+def test_cfn_update_validation_rolls_back_like_aws(cfn, s3):
+ """An update that fails pre-deployment validation rolls back without touching a resource; the stack's
+ own bucket is not a conflict; DisableValidation moves the refusal to the resource (AWS 2026-10-16)."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name, own, taken = f"cfn-upd-val-{uid}", f"cfn-upd-own-{uid}", f"cfn-upd-taken-{uid}"
+
+ def template(versioning, with_taken=False):
+ resources = {"Own": {"Type": "AWS::S3::Bucket", "Properties": {
+ "BucketName": own, "VersioningConfiguration": {"Status": versioning}}}}
+ if with_taken:
+ resources["Taken"] = {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": taken}}
+ return json.dumps({"Resources": resources})
+
+ s3.create_bucket(Bucket=taken)
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("Enabled"))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("Suspended"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("Suspended", with_taken=True))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ events = _events_since_last_update(cfn, stack_name)
+ assert [(e["LogicalResourceId"], e["ResourceStatus"], e.get("ResourceStatusReason", "")) for e in events] == [
+ (stack_name, "UPDATE_IN_PROGRESS", "User Initiated"),
+ (stack_name, "UPDATE_FAILED", _VALIDATION_FAILED_ONE),
+ (stack_name, "UPDATE_ROLLBACK_IN_PROGRESS",
+ "Validation failure detected. See operation's FAILED event for details."),
+ (stack_name, "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", ""),
+ (stack_name, "UPDATE_ROLLBACK_COMPLETE", ""),
+ ]
+ assert events[1]["DetailedStatus"] == "VALIDATION_FAILED"
+ [error] = [e for e in cfn.describe_events(StackName=stack_name)["OperationEvents"]
+ if e["EventType"] == "VALIDATION_ERROR"]
+ assert (error["OperationType"], error["LogicalResourceId"], error["ValidationName"]) == (
+ "UPDATE_STACK", "Taken", "NAME_CONFLICT_VALIDATION")
+ assert "Taken" not in json.dumps(cfn.get_template(StackName=stack_name)["TemplateBody"])
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("Suspended", with_taken=True),
+ DisableValidation=True)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ assert f"{taken} already exists" in _stack_event_reasons(cfn, stack_name)
+ s3.head_bucket(Bucket=taken)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ s3.delete_bucket(Bucket=taken)
+
+
+def test_cfn_s3_name_conflict_own_bucket():
+ """In-process: an own existing name is a NAME_CONFLICT_VALIDATION error too."""
from ministack.services import s3 as s3_svc
- from ministack.services.cloudformation import _stack_events, provisioners, stacks
+ from ministack.services.cloudformation import _stack_events, stacks
name = f"cfn-own-conflict-{_uuid_mod.uuid4().hex[:8]}"
s3_svc._buckets[name] = {"created": "", "objects": {}, "region": "us-east-1"}
@@ -36453,10 +36509,6 @@ def test_cfn_s3_name_conflict_own_bucket_when_adoption_is_off(monkeypatch):
resources = {"B": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": name}}}
stack = {"StackId": stack_id, "StackName": "own-conflict"}
try:
- monkeypatch.setattr(provisioners, "CFN_S3_ADOPT_EXISTING_BUCKET", True)
- assert not stacks._fail_property_validation(stack, stack_id, "own-conflict", resources, ["B"], {}, {}, {},
- True)
- monkeypatch.setattr(provisioners, "CFN_S3_ADOPT_EXISTING_BUCKET", False)
assert stacks._fail_property_validation(stack, stack_id, "own-conflict", resources, ["B"], {}, {}, {}, True)
assert stack["StackStatus"] == "CREATE_FAILED"
[error] = [e for e in stack["_operation_events"] if e["EventType"] == "VALIDATION_ERROR"]
@@ -36466,6 +36518,23 @@ def test_cfn_s3_name_conflict_own_bucket_when_adoption_is_off(monkeypatch):
_stack_events.pop(stack_id, None)
+def test_cfn_s3_name_conflict_with_validation_disabled_fails_the_resource(cfn, s3):
+ """DisableValidation skips pre-deployment validation; the bucket's create still refuses the name."""
+ name = f"cfn-own-disabled-{_uuid_mod.uuid4().hex[:8]}"
+ stack_name = f"cfn-novalidate-{_uuid_mod.uuid4().hex[:8]}"
+ s3.create_bucket(Bucket=name)
+ template = {"Resources": {"Bucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": name}}}}
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template), DisableValidation=True)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "ROLLBACK_COMPLETE"
+ assert f"{name} already exists" in _stack_event_reasons(cfn, stack_name)
+ assert cfn.describe_events(StackName=stack_name)["OperationEvents"] == []
+ s3.head_bucket(Bucket=name)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ s3.delete_bucket(Bucket=name)
+
+
@pytest.mark.parametrize("custom_bus", [True, False])
def test_cfn_events_rule_bus_arn_delivery_and_lifecycle(cfn, eb, sqs, custom_bus):
"""ARN/name aliases share a rule on create, update, delivery, drift and delete."""
diff --git a/tests/test_ci_sharding.py b/tests/test_ci_sharding.py
deleted file mode 100644
index b8246b7c..00000000
--- a/tests/test_ci_sharding.py
+++ /dev/null
@@ -1,37 +0,0 @@
-"""Exercise CI collection with real pytest markers, including auth exclusions."""
-
-import json
-import os
-import subprocess
-import sys
-from pathlib import Path
-
-
-def test_auth_contracts_are_excluded_from_existing_shards(tmp_path):
- (tmp_path / "pytest.ini").write_text(
- "[pytest]\nmarkers =\n serial\n data_plane\n auth_contract\n"
- )
- (tmp_path / "test_lanes.py").write_text(
- "import pytest\n"
- "def test_parallel(): pass\n"
- "@pytest.mark.serial\ndef test_serial(): pass\n"
- "@pytest.mark.data_plane\ndef test_data_plane(): pass\n"
- "@pytest.mark.auth_contract\n"
- "@pytest.mark.parametrize('value', [1, 2])\ndef test_auth(value): pass\n"
- "@pytest.mark.auth_contract\[email protected]\ndef test_auth_serial(): pass\n"
- "@pytest.mark.auth_contract\[email protected]_plane\ndef test_auth_data_plane(): pass\n"
- )
- (tmp_path / "test_auth_only.py").write_text(
- "import pytest\[email protected]_contract\ndef test_only_auth(): pass\n"
- )
- scripts = Path(__file__).resolve().parents[1] / "scripts"
- env = {**os.environ, "PYTHONPATH": str(scripts)}
- # Parent pytest flags must not change the nested collection's selection.
- env.pop("PYTEST_ADDOPTS", None)
- result = subprocess.run(
- [sys.executable, "-m", "pytest", "--collect-only", "-q", "-p", "_collect_plan_plugin"],
- cwd=tmp_path, env=env, capture_output=True, text=True, timeout=30,
- )
- assert result.returncode == 0, result.stdout + result.stderr
- counts = json.loads((tmp_path / ".pytest_collect_plan.json").read_text())
- assert counts == {"test_lanes.py": {"parallel": 1, "serial": 1, "data_plane": 1}}
diff --git a/tests/test_cloudfront.py b/tests/test_cloudfront.py
index fa806c0a..11e116c1 100644
--- a/tests/test_cloudfront.py
+++ b/tests/test_cloudfront.py
@@ -899,7 +899,7 @@ def test_cloudfront_function_update_keeps_the_published_live_stage(cloudfront):
def test_cloudfront_function_development_status_follows_publish_and_association(cloudfront):
"""The DEVELOPMENT stage reports UNPUBLISHED only while it holds changes that
- were never published, then UNASSOCIATED, or ASSOCIATED while a cache
+ were never published, then UNASSOCIATED, or DEPLOYED while a cache
behavior references the function. Terraform's aws_cloudfront_function.status
reads this stage."""
name = f"fn-status-{_uuid_mod.uuid4().hex[:8]}"
@@ -944,8 +944,8 @@ def test_cloudfront_function_development_status_follows_publish_and_association(
"Items": [{"FunctionARN": fn_arn, "EventType": "viewer-request"}],
}
dist = cloudfront.create_distribution(DistributionConfig=cfg)
- assert dev_status() == "ASSOCIATED"
- assert listed_dev_status() == "ASSOCIATED"
+ assert dev_status() == "DEPLOYED"
+ assert listed_dev_status() == "DEPLOYED"
dist_id = dist["Distribution"]["Id"]
cfg["Enabled"] = False
diff --git a/tests/test_cloudtrail.py b/tests/test_cloudtrail.py
index 52c60ccc..2f995df7 100644
--- a/tests/test_cloudtrail.py
+++ b/tests/test_cloudtrail.py
@@ -416,11 +416,11 @@ def test_get_trail_status_returns_the_deprecated_string_members(ct):
status = ct.get_trail_status(Name=name)
assert {key: status[key] for key in EMPTY_DEPRECATED_STATUS} == {
**EMPTY_DEPRECATED_STATUS,
- "TimeLoggingStarted": status["StartLoggingTime"].strftime("%Y-%m-%dT%H:%M:%SZ"),
- "TimeLoggingStopped": status["StopLoggingTime"].strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "TimeLoggingStarted": status["StartLoggingTime"].astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "TimeLoggingStopped": status["StopLoggingTime"].astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
}
raw = _raw_body(ct, "get_trail_status", Name=name)
- assert all(isinstance(raw[key], float) for key in ("StartLoggingTime", "StopLoggingTime"))
+ assert all(isinstance(raw[key], int) for key in ("StartLoggingTime", "StopLoggingTime"))
def test_get_trail_status_not_found(ct):
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 934d5bf0..9e362bff 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -1706,6 +1706,17 @@ def test_cognito_access_token_must_be_a_signed_access_token_under_auth(monkeypat
assert call("GetUser", AccessToken=alice["AccessToken"])["Username"] == "alice"
+def test_cognito_access_token_without_the_admin_scope_is_refused_under_auth(monkeypatch):
+ mod, call = _idp_in_process(monkeypatch, auth=True)
+ pid, cid, sign_in = _password_client_with_users(call, "alice")
+ sub = _decode_jwt_claims(sign_in("alice")["AccessToken"])["sub"]
+ scoped = mod._fake_token(sub, pid, cid, "access", username="alice", scope="openid email")
+ assert call("GetUser", AccessToken=scoped) == (
+ "NotAuthorizedException", "Access Token does not have required scopes")
+ admin = mod._fake_token(sub, pid, cid, "access", username="alice", scope="openid aws.cognito.signin.user.admin")
+ assert call("GetUser", AccessToken=admin)["Username"] == "alice"
+
+
def test_cognito_sign_out_and_revoke_token_revoke_access_tokens_under_auth(monkeypatch):
_, call = _idp_in_process(monkeypatch, auth=True)
pid, cid, sign_in = _password_client_with_users(call, "alice", "bob")
@@ -4671,6 +4682,21 @@ def test_oauth2_token_authorization_code_drops_scopes_the_client_does_not_allow(
assert _decode_jwt_claims(tokens['access_token'])['scope'] == 'openid email'
[email protected]('scope', ['openid api/admin', 'openid bogus'])
+def test_oauth2_authorize_refuses_a_scope_the_client_does_not_allow(scope):
+ """AWS redirects to the callback with invalid_scope instead of showing the login page."""
+ cognito_idp = make_client('cognito-idp')
+ client = _scoped_code_client(cognito_idp, _SCOPED_CLIENT_SCOPES)
+ query = urllib.parse.urlencode({'response_type': 'code', 'client_id': client['ClientId'],
+ 'redirect_uri': 'http://localhost:3000/callback', 'scope': scope})
+ status, headers, _ = _get(f'{ENDPOINT}/oauth2/authorize?{query}', follow_redirects=False)
+ assert status == 302
+ location = urllib.parse.urlparse(headers['location'])
+ assert location._replace(query='').geturl() == 'http://localhost:3000/callback'
+ assert urllib.parse.parse_qs(location.query) == {'error': ['invalid_request'],
+ 'error_description': ['invalid_scope']}
+
+
def test_oauth2_refreshed_tokens_keep_the_granted_scopes():
"""Both refresh paths keep the code grant's scopes; API sign-ins keep the admin scope."""
cognito_idp = make_client('cognito-idp')
@@ -4726,7 +4752,6 @@ def test_oauth2_token_client_credentials():
'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret,
- 'scope': 'openid',
})
assert status == 200
@@ -4750,7 +4775,6 @@ def test_oauth2_token_client_credentials_expires_with_the_client():
'grant_type': 'client_credentials',
'client_id': client['ClientId'],
'client_secret': client['ClientSecret'],
- 'scope': 'openid',
})
assert status == 200
@@ -4790,6 +4814,26 @@ def test_oauth2_token_client_credentials_carries_granted_scopes(requested, scope
assert _decode_jwt_claims(json.loads(body)['access_token'])['scope'] == scope
[email protected]('requested,error', [('api/admin', 'invalid_grant'), ('openid', 'invalid_scope')])
+def test_oauth2_token_client_credentials_refuses_scopes_it_cannot_grant(requested, error):
+ """A resource-server scope the client lacks is invalid_grant; a non-custom scope is invalid_scope."""
+ cognito_idp = make_client('cognito-idp')
+ pool_id, _ = _setup_pool_with_user(cognito_idp)
+ cognito_idp.create_resource_server(
+ UserPoolId=pool_id, Identifier='api', Name='api',
+ Scopes=[{'ScopeName': n, 'ScopeDescription': n} for n in ('read', 'admin')],
+ )
+ client = cognito_idp.create_user_pool_client(
+ UserPoolId=pool_id, ClientName='m2m', GenerateSecret=True, AllowedOAuthFlows=['client_credentials'],
+ AllowedOAuthScopes=['api/read'], AllowedOAuthFlowsUserPoolClient=True,
+ )['UserPoolClient']
+ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {
+ 'grant_type': 'client_credentials', 'client_id': client['ClientId'],
+ 'client_secret': client['ClientSecret'], 'scope': requested,
+ })
+ assert (status, json.loads(body)) == (400, {'error': error})
+
+
def test_oauth2_token_client_auth_basic():
cognito_idp = make_client('cognito-idp')
pool_id, client = _setup_pool_with_user(cognito_idp, generate_secret=True)
@@ -4802,7 +4846,6 @@ def test_oauth2_token_client_auth_basic():
f'{ENDPOINT}/oauth2/token',
{
'grant_type': 'client_credentials',
- 'scope': 'openid',
},
headers={'Authorization': f'Basic {basic}'},
)
@@ -9000,6 +9043,21 @@ def test_cognito_update_custom_domain_certificate(cognito_idp):
assert cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"].get("CustomDomain") == domain
+def test_cognito_update_custom_domain_without_certificate_is_refused(cognito_idp):
+ """A custom domain update must carry CustomDomainConfig; without it AWS refuses the conversion."""
+ pid = cognito_idp.create_user_pool(PoolName="CustomDomainNoCertPool")["UserPool"]["Id"]
+ domain = _pool_unique_domain(pid, "nocert")
+ cognito_idp.create_user_pool_domain(
+ UserPoolId=pid, Domain=domain, CustomDomainConfig={"CertificateArn": _CUSTOM_CERT_ARN})
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.update_user_pool_domain(UserPoolId=pid, Domain=domain, ManagedLoginVersion=2)
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"
+ assert exc.value.response["Error"]["Message"] == "Cannot convert custom domain to prefix domain."
+ dd = cognito_idp.describe_user_pool_domain(Domain=domain)["DomainDescription"]
+ assert dd["ManagedLoginVersion"] == 1
+ assert dd["CustomDomainConfig"] == {"CertificateArn": _CUSTOM_CERT_ARN}
+
+
def test_cognito_prefix_domain_unchanged_by_custom_domain_support(cognito_idp):
"""Regression: no CustomDomainConfig still means a prefix domain that expands."""
pid = cognito_idp.create_user_pool(PoolName="PrefixDomainPool")["UserPool"]["Id"]
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 8d7a3a93..861c14ac 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -5076,6 +5076,92 @@ class TestHeaderSignatures:
_local_client("dynamodb", user_key[0], "wrong-secret").list_tables()
+def _presigned(key, secret, service, query, token=None, edit=None):
+ """A GET presigned in its query string, as botocore's SigV4QueryAuth signs it: (code or None, status, body)."""
+ from botocore.auth import SigV4QueryAuth
+ from botocore.awsrequest import AWSRequest
+ from botocore.credentials import Credentials
+
+ request = AWSRequest(method="GET", url=f"http://localhost:4566/?{query}")
+ SigV4QueryAuth(Credentials(key, secret, token), service, "us-east-1", 300).add_auth(request)
+ url = edit(request.url) if edit else request.url
+ response = _asgi_send(AWSRequest(method="GET", url=url).prepare())
+ body = response.content.decode()
+ code = re.search(r"<Code>([^<]*)</Code>", body) or re.search(r'"__type": "([^"]*)"', body)
+ return (code.group(1) if code else None), response.status_code, body
+
+
+_LIST_USERS = "Action=ListUsers&Version=2010-05-08"
+_LIST_QUEUES = "Action=ListQueues&Version=2012-11-05"
+
+
+def _drop(name):
+ return lambda url: re.sub(rf"&?{name}=[^&]*", "", url)
+
+
+class TestQuerySignatures:
+ def test_right_secret_passes(self, user_key):
+ assert _presigned(*user_key, "iam", _LIST_USERS)[:2] == (None, 200)
+
+ @pytest.mark.parametrize("service,query", [("iam", _LIST_USERS), ("sqs", _LIST_QUEUES)])
+ def test_wrong_or_forged_signature_is_refused(self, user_key, service, query):
+ assert _presigned(user_key[0], "wrong-secret", service, query)[:2] == ("SignatureDoesNotMatch", 403)
+ forged = _presigned(*user_key, service, query,
+ edit=lambda url: re.sub(r"X-Amz-Signature=\w+", "X-Amz-Signature=" + "0" * 64, url))
+ assert forged[:2] == ("SignatureDoesNotMatch", 403)
+
+ def test_query_mode_sqs_failure_is_sqs_query_xml(self, user_key):
+ code, status, body = _presigned(user_key[0], "wrong-secret", "sqs", _LIST_QUEUES)
+ assert (code, status) == ("SignatureDoesNotMatch", 403)
+ assert body.startswith('<?xml version="1.0"?><ErrorResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/">'
+ "<Error><Type>Sender</Type><Code>SignatureDoesNotMatch</Code>")
+ assert "</Message><Detail/></Error><RequestId>" in body
+ assert _failure(lambda: _local_client("sqs", user_key[0], "wrong-secret").list_queues()) == (
+ "SignatureDoesNotMatch", 403)
+
+ def test_session_key_needs_its_token_and_signature(self, user_key):
+ session = _local_client("sts", *user_key).get_session_token()["Credentials"]
+ key, secret, token = session["AccessKeyId"], session["SecretAccessKey"], session["SessionToken"]
+ assert _presigned(key, secret, "sqs", _LIST_QUEUES, token)[:2] == (None, 200)
+ assert _presigned(key, secret, "sqs", _LIST_QUEUES)[:2] == ("InvalidClientTokenId", 403)
+ forged = _presigned(key, secret, "sqs", _LIST_QUEUES, token,
+ edit=lambda url: re.sub(r"X-Amz-Signature=\w+", "X-Amz-Signature=" + "0" * 64, url))
+ assert forged[:2] == ("SignatureDoesNotMatch", 403)
+
+ def test_signature_outside_the_time_window_is_refused(self, user_key):
+ def to_2020(url):
+ url = re.sub(r"X-Amz-Date=\d{8}T\d{6}Z", "X-Amz-Date=20200101T000000Z", url)
+ return re.sub(r"%2F\d{8}%2F", "%2F20200101%2F", url)
+
+ code, status, body = _presigned(*user_key, "iam", _LIST_USERS, edit=to_2020)
+ assert (code, status) == ("SignatureDoesNotMatch", 403)
+ assert "Signature expired: 20200101T000000Z is now earlier than " in body
+
+ @pytest.mark.parametrize("name", ["X-Amz-Date", "X-Amz-SignedHeaders", "X-Amz-Signature"])
+ def test_missing_query_parameter_is_refused(self, user_key, name):
+ code, status, body = _presigned(*user_key, "sqs", _LIST_QUEUES, edit=_drop(name))
+ assert (code, status) == ("IncompleteSignature", 400)
+ assert (f"AWS query-string parameters must include &apos;{name}&apos;. "
+ "Re-examine the query-string parameters.") in body or (
+ f"AWS query-string parameters must include '{name}'. Re-examine the query-string parameters.") in body
+
+ def test_credential_must_have_five_elements(self, user_key):
+ code, status, body = _presigned(
+ *user_key, "sqs", _LIST_QUEUES,
+ edit=lambda url: re.sub(r"X-Amz-Credential=([^%]+)%2F[^&]*", r"X-Amz-Credential=\1%2Fus-east-1", url))
+ assert (code, status) == ("IncompleteSignature", 400)
+ assert "Credential must have exactly 5 slash-delimited elements" in body
+
+ def test_root_key_signs_with_any_secret(self, user_key):
+ assert _presigned("test", "anything", "iam", _LIST_USERS)[:2] == (None, 200)
+
+ def test_signature_is_not_checked_without_auth(self, user_key, monkeypatch):
+ from ministack import app as app_mod
+
+ monkeypatch.setattr(app_mod, "AUTH", False)
+ assert _presigned(user_key[0], "wrong-secret", "iam", _LIST_USERS)[:2] == (None, 200)
+
+
class TestSessionTokens:
@pytest.fixture
def session(self, user_key):
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 5d3cf8a3..f7e5d517 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -540,8 +540,6 @@ _NO_PRINCIPAL = "because the principal does not exist in your account"
("describe_thing_group", {"thingGroupName": "{nogroup}"}, "ThingGroup {account}:{nogroup} not found."),
("update_thing_group", {"thingGroupName": "{nogroup}", "thingGroupProperties": {}},
"Group {nogroup} does not exist"),
- ("create_thing_group", {"thingGroupName": "{nothing}", "parentGroupName": "{nogroup}"},
- "Cannot create group using non-existing group as parent : {nogroup}"),
("list_things_in_thing_group", {"thingGroupName": "{nogroup}"},
"Cannot find requested thing group for accountId: {account} and thing group name: {nogroup}"),
("add_thing_to_thing_group", {"thingGroupName": "{nogroup}", "thingName": "{thing}"},
@@ -605,6 +603,15 @@ def test_iot_not_found_messages(iot_client, operation, kwargs, message):
iot_client.delete_thing(thingName=thing)
+def test_iot_create_thing_group_with_unknown_parent_is_invalid(iot_client):
+ nogroup = _unique("nogroup")
+ with pytest.raises(ClientError) as ei:
+ iot_client.create_thing_group(thingGroupName=_unique("group"), parentGroupName=nogroup)
+ error = ei.value.response["Error"]
+ assert (ei.value.response["ResponseMetadata"]["HTTPStatusCode"], error["Code"], error["Message"]) == (
+ 400, "InvalidRequestException", f"Cannot create group using non-existing group as parent : {nogroup}")
+
+
def test_iot_update_thing_increments_version(iot_client):
name = _unique("thing")
iot_client.create_thing(thingName=name)
@@ -1701,8 +1708,11 @@ def test_iot_set_default_policy_version_refusals(iot_client):
err = ei.value.response
assert (err["ResponseMetadata"]["HTTPStatusCode"], err["Error"]["Code"], err["Error"]["Message"]) == (
status, code, message)
- with pytest.raises(iot_client.exceptions.ResourceNotFoundException):
+ with pytest.raises(ClientError) as ei:
iot_client.set_default_policy_version(policyName=_unique("nope"), policyVersionId="1")
+ err = ei.value.response
+ assert (err["ResponseMetadata"]["HTTPStatusCode"], err["Error"]["Code"], err["Error"]["Message"]) == (
+ 404, "ResourceNotFoundException", "Policy not found")
assert iot_client.get_policy(policyName=name)["defaultVersionId"] == "1"
finally:
iot_client.delete_policy(policyName=name)
@@ -2780,11 +2790,11 @@ def test_fleet_provisioning_register_thing_refusals_change_nothing():
reset()
no_policy = _fleet_template()
no_policy["Resources"]["policy"]["Properties"]["PolicyName"] = "fleet-none"
- sub = _fleet_template()
- sub["Resources"]["thing"]["Properties"]["ThingName"] = {"Fn::Sub": "fleet-${SerialNumber}"}
+ select = _fleet_template()
+ select["Resources"]["thing"]["Properties"]["ThingName"] = {"Fn::Select": [5, ["fleet-a"]]}
templates = {
"fleet": _fleet_template(), "fleet-cdk": _fleet_cdk_template({}),
- "fleet-nopol": no_policy, "fleet-sub": sub,
+ "fleet-nopol": no_policy, "fleet-select": select,
}
async def _run():
@@ -2831,15 +2841,12 @@ def test_fleet_provisioning_register_thing_refusals_change_nothing():
reply, "fleet-nopol",
"Register thing workflow execution terminates due to: Policy default version not found",
)
- reply = await _fleet_publish(
- session, sent, _fleet_provision_topic("fleet-sub"),
+ topic, doc = await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet-select"),
_fleet_register(token, SerialNumber="SN4"),
)
- assert reply == _fleet_rejection(
- "fleet-sub", "InvalidTemplate",
- "Template fleet-sub uses Fn::Sub, which MiniStack does not resolve.",
- )
- for name in ("fleet-c", "fleet-SN2", "fleet-SN3", "fleet-SN4"):
+ assert (topic.rsplit("/", 1)[1], doc["errorCode"]) == ("rejected", "InvalidTemplate")
+ for name in ("fleet-c", "fleet-SN2", "fleet-SN3", "fleet-SN4", "fleet-a"):
assert await _fleet_thing(name) is None
assert await _fleet_certificate_state(created["certificateId"]) == (
"PENDING_ACTIVATION", [], [],
@@ -3263,6 +3270,148 @@ def test_fleet_provisioning_claims_and_tokens_are_scoped_persisted_and_expire():
reset()
+def test_fleet_provisioning_resolves_the_documented_intrinsics_and_policy_documents():
+ """Fn::FindInMap, Fn::Split, Fn::Select and Fn::Sub resolve; a PolicyDocument policy is created; no token is "empty"."""
+ import hashlib
+
+ from ministack.services import iot as iot_module
+
+ iot_module.reset()
+ reset()
+ document = {"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "iot:Publish", "Resource": "*"}]}
+ body = _fleet_template(
+ Mappings={"Sites": {"vienna": {"Url": "https://example.com/vie"}}},
+ DeviceConfiguration={
+ "url": {"Fn::FindInMap": ["Sites", {"Ref": "Site"}, "Url"]},
+ "zone": {"Fn::Select": [1, {"Fn::Split": [",", "a,b,c"]}]},
+ "literal": {"Fn::Sub": "${!Keep}"},
+ },
+ )
+ body["Parameters"]["Site"] = {"Type": "String"}
+ body["Resources"]["thing"]["Properties"]["ThingName"] = {
+ "Fn::Sub": ["${Prefix}-${SerialNumber}", {"Prefix": "fleet"}]}
+ body["Resources"]["policy"] = {"Type": "AWS::IoT::Policy", "Properties": {"PolicyDocument": document}}
+
+ async def _run():
+ await _fleet_setup({"fleet": body})
+ session, sent = await _fleet_client("fleet-claim", ["fleet"])
+ created = await _fleet_certificate(session, sent)
+ provision = _fleet_provision_topic("fleet")
+ for token in (None, ""):
+ reply = await _fleet_publish(session, sent, provision, _fleet_register(token, SerialNumber="SN1"))
+ assert reply == _fleet_rejection(
+ "fleet", "InvalidCertificateOwnershipToken", "Certificate ownership token cannot be empty."
+ )
+ reply = await _fleet_publish(session, sent, provision, _fleet_register(
+ created["certificateOwnershipToken"], SerialNumber="SN1", Site="vienna"))
+ assert reply == (f"{provision}/accepted", {
+ "deviceConfiguration": {"url": "https://example.com/vie", "zone": "b", "literal": "${Keep}"},
+ "thingName": "fleet-SN1",
+ })
+ policy = hashlib.sha256(json.dumps(document).encode()).hexdigest()
+ assert await _fleet_certificate_state(created["certificateId"]) == ("ACTIVE", [policy], ["fleet-SN1"])
+ await session.cleanup()
+
+ try:
+ asyncio.run(_run())
+ finally:
+ iot_module.reset()
+ reset()
+
+
[email protected]("trust,policies,accepted", [
+ (None, [], False),
+ ({"Service": "lambda.amazonaws.com"}, ["service-role/AWSIoTThingsRegistration"], False),
+ ({"Service": "iot.amazonaws.com"}, [], False),
+ ({"Service": "iot.amazonaws.com"}, ["service-role/AWSIoTThingsRegistration"], True),
+])
+def test_fleet_provisioning_under_auth_needs_a_certificate_and_a_usable_role(monkeypatch, trust, policies, accepted):
+ """With AUTH=true a session without a certificate may not provision, and RegisterThing needs the provisioning role."""
+ import ministack.app as app_mod
+ from ministack.services import iam as iam_svc
+ from ministack.services import iot as iot_module
+
+ iot_module.reset()
+ reset()
+ monkeypatch.setattr(app_mod, "AUTH", True)
+ role = _FLEET_ROLE.rsplit("/", 1)[1]
+
+ async def _run():
+ await _fleet_setup({"fleet": _fleet_template()})
+ if trust is not None:
+ with iot_module.request_scope(_FLEET_ACCOUNT, _FLEET_REGION):
+ iam_svc._roles[role] = {
+ "RoleName": role,
+ "AssumeRolePolicyDocument": json.dumps({"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Principal": trust, "Action": "sts:AssumeRole"}]}),
+ "AttachedPolicies": [f"arn:aws:iam::aws:policy/{p}" for p in policies],
+ }
+ _status, claim = await _fleet_request("POST", "/provisioning-templates/fleet/provisioning-claim")
+
+ anonymous, anonymous_sent = await _fleet_client("fleet-anonymous", ["fleet"])
+ anonymous_sent.clear()
+ assert await anonymous.handle_packet(
+ PKT_PUBLISH, 0x02, _encode_string(_FLEET_CREATE) + struct.pack("!H", 9)
+ ) is False
+ assert _extract_publish_frames(anonymous_sent) == []
+ await anonymous.cleanup()
+
+ session, sent = await _fleet_client("fleet-claim", ["fleet"])
+ session.certificate_id, session.provisioning_template = claim["certificateId"], "fleet"
+ created = await _fleet_certificate(session, sent)
+ provision = _fleet_provision_topic("fleet")
+ reply = await _fleet_publish(session, sent, provision, _fleet_register(
+ created["certificateOwnershipToken"], SerialNumber="SN1"))
+ if accepted:
+ assert reply[0] == f"{provision}/accepted"
+ assert (await _fleet_certificate_state(created["certificateId"]))[0] == "ACTIVE"
+ else:
+ assert reply == (f"{provision}/rejected",
+ {"statusCode": 403, "errorCode": "AccessDenied", "errorMessage": "Access Denied"})
+ assert await _fleet_thing("fleet-SN1") is None
+ assert await _fleet_certificate_state(created["certificateId"]) == ("PENDING_ACTIVATION", [], [])
+ await session.cleanup()
+
+ try:
+ asyncio.run(_run())
+ finally:
+ with iot_module.request_scope(_FLEET_ACCOUNT, _FLEET_REGION):
+ iam_svc._roles.pop(role, None)
+ iot_module.reset()
+ reset()
+
+
+def test_fleet_provisioning_expired_claim_connection_is_closed_after_the_puback():
+ """A PUBLISH on the connection of an expired claim gets its PUBACK, no reply, and the connection closes."""
+ from ministack.services import iot as iot_module
+
+ iot_module.reset()
+ reset()
+
+ async def _run():
+ await _fleet_setup({"fleet": _fleet_template()})
+ _status, claim = await _fleet_request("POST", "/provisioning-templates/fleet/provisioning-claim")
+ session, sent = await _fleet_client("fleet-claim", ["fleet"])
+ session.certificate_id, session.provisioning_template = claim["certificateId"], "fleet"
+ await _fleet_certificate(session, sent)
+ for record in iot_module._provisioning_claims._data.values():
+ record["expiration"] = time.time() - 1
+ sent.clear()
+ assert await session.handle_packet(
+ PKT_PUBLISH, 0x02, _encode_string(_FLEET_CREATE) + struct.pack("!H", 9)
+ ) is False
+ assert _extract_publish_frames(sent) == []
+ assert [m["bytes"] for m in sent if m.get("bytes")] == [bytes([PKT_PUBACK << 4, 2, 0, 9])]
+ await session.cleanup()
+
+ try:
+ asyncio.run(_run())
+ finally:
+ iot_module.reset()
+ reset()
+
+
# ---------------------------------------------------------------------------
# Fleet indexing (indexing configuration + SearchIndex)
# ---------------------------------------------------------------------------
@@ -9530,7 +9679,7 @@ def test_iot_job_abort_events():
timeoutConfig={"inProgressTimeoutInMinutes": 1})
await call("POST", "/things/ev-t1/jobs/ev-timeout", {"status": "IN_PROGRESS"}, device=True)
iot_module._job_executions[("ev-t1", "ev-timeout")]["startedAt"] -= 61_000
- await call("GET", "/things/ev-t1/jobs/ev-timeout", device=True)
+ await call("GET", "/things/ev-t1/jobs", device=True)
events = _registry_events(calls, enable=("JOB", "JOB_EXECUTION"))
assert [t for t, _e in events] == [
diff --git a/tests/test_iot_data.py b/tests/test_iot_data.py
index 5d12cca4..e1ed6b13 100644
--- a/tests/test_iot_data.py
+++ b/tests/test_iot_data.py
@@ -4409,7 +4409,12 @@ def test_mtls_auth_provisioning_claim_is_held_to_its_templates_topics(tmp_path):
try:
_wait_ready(f"http://127.0.0.1:{http_port}/_ministack/ready")
private = _Broker(http_port, mqtt_port)
- iot = private.client("iot")
+ iot, iam = private.client("iot"), private.client("iam")
+ iam.create_role(RoleName="provisioning", AssumeRolePolicyDocument=json.dumps({
+ "Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Principal": {"Service": "iot.amazonaws.com"}, "Action": "sts:AssumeRole"}]}))
+ iam.attach_role_policy(
+ RoleName="provisioning", PolicyArn="arn:aws:iam::aws:policy/service-role/AWSIoTThingsRegistration")
name = _unique("fleet")
iot.create_provisioning_template(
templateName=name,
diff --git a/tests/test_iot_jobs_data.py b/tests/test_iot_jobs_data.py
index 28c0baca..ce4d4291 100644
--- a/tests/test_iot_jobs_data.py
+++ b/tests/test_iot_jobs_data.py
@@ -549,6 +549,33 @@ def test_iot_jobs_presigned_url_host(host, expected):
assert urlsplit(url).netloc == (expected or f"{iot._MINISTACK_HOST}:{iot._GATEWAY_PORT}")
[email protected]("trust,signed", [
+ (None, False),
+ ({"Service": "lambda.amazonaws.com"}, False),
+ ({"Service": "iot.amazonaws.com"}, True),
+])
+def test_iot_jobs_presigned_url_needs_a_role_iot_may_assume_under_auth(monkeypatch, trust, signed):
+ """With AUTH=true no session is minted for a role that is missing or does not trust IoT: the placeholder stays."""
+ import ministack.app as app_mod
+ from ministack.services import iam as iam_svc
+ from ministack.services import iot
+
+ monkeypatch.setattr(app_mod, "AUTH", True)
+ name = _unique("presign")
+ if trust is not None:
+ iam_svc._roles[name] = {"RoleName": name, "AssumeRolePolicyDocument": json.dumps({
+ "Version": "2012-10-17",
+ "Statement": [{"Effect": "Allow", "Principal": trust, "Action": "sts:AssumeRole"}]})}
+ job = {"document": json.dumps({"fw": _presign("s3://bucket/fw.bin")}),
+ "presignedUrlConfig": {"roleArn": f"arn:aws:iam::000000000000:role/{name}"}}
+ try:
+ url = json.loads(iot._jobs_presigned_document(job))["fw"]
+ finally:
+ iam_svc._roles.pop(name, None)
+ assert ("X-Amz-Credential=" in url) is signed
+ assert url.startswith("http") is signed
+
+
def test_iot_jobs_presigned_url_placeholders_refusals(iot_client, s3):
"""A placeholder without presignedUrlConfig.roleArn, or naming no S3 object, refuses the job."""
thing, bucket = _unique("jobs-thing"), _unique("jobs-presign")
diff --git a/tests/test_ministack.py b/tests/test_ministack.py
index 6281fd7d..1a064f60 100644
--- a/tests/test_ministack.py
+++ b/tests/test_ministack.py
@@ -3,10 +3,13 @@
import asyncio
import json
import os
+import urllib.error
+import urllib.request
import xml.etree.ElementTree as ET
from urllib.parse import urlparse
import pytest
+from botocore.exceptions import ClientError
from ministack import app as app_module
@@ -1277,6 +1280,208 @@ def test_failed_docker_hub_pull_falls_back_to_a_mirror_and_keeps_the_name(monkey
assert pulled == ["public.ecr.aws/lambda/python:3.12"]
+# Wire envelopes and success Content-Types, from real-AWS captures: query errors carry
+# <Type> and no <?xml?>; ec2 keeps its declaration and charset; rest-xml carries <Type>.
+
+
+def _wire_ct(resp):
+ return resp["ResponseMetadata"]["HTTPHeaders"]["content-type"]
+
+
+def _wire_status(err):
+ return err["ResponseMetadata"]["HTTPStatusCode"]
+
+
+def test_iam_query_error_envelope(iam):
+ with pytest.raises(ClientError) as exc:
+ iam.get_user(UserName="wire-missing-user")
+ err = exc.value.response
+ assert err["Error"]["Code"] == "NoSuchEntity"
+ assert err["Error"]["Type"] == "Sender"
+ assert _wire_status(err) == 404
+ assert _wire_ct(err) == "text/xml"
+
+
+def test_sns_query_error_envelope(sns):
+ with pytest.raises(ClientError) as exc:
+ sns.set_topic_attributes(
+ TopicArn="arn:aws:sns:us-east-1:000000000000:wire-missing",
+ AttributeName="DisplayName",
+ AttributeValue="x",
+ )
+ err = exc.value.response
+ assert err["Error"]["Code"] == "NotFound"
+ assert err["Error"]["Type"] == "Sender"
+ assert _wire_ct(err) == "text/xml"
+
+
+def test_elbv2_query_error_envelope(elbv2):
+ with pytest.raises(ClientError) as exc:
+ elbv2.describe_load_balancers(Names=["wire-missing"])
+ err = exc.value.response
+ assert err["Error"]["Code"] == "LoadBalancerNotFound"
+ assert err["Error"]["Type"] == "Sender"
+ assert _wire_ct(err) == "text/xml"
+
+
+def test_autoscaling_query_error_envelope(autoscaling):
+ with pytest.raises(ClientError) as exc:
+ autoscaling.update_auto_scaling_group(
+ AutoScalingGroupName="wire-missing")
+ err = exc.value.response
+ assert err["Error"]["Code"] == "ValidationError"
+ assert err["Error"]["Type"] == "Sender"
+ assert _wire_ct(err) == "text/xml"
+
+
+def test_elasticache_query_error_envelope(ec):
+ with pytest.raises(ClientError) as exc:
+ ec.describe_cache_clusters(CacheClusterId="wire-missing")
+ err = exc.value.response
+ assert err["Error"]["Code"] == "CacheClusterNotFound"
+ assert err["Error"]["Type"] == "Sender"
+ assert _wire_ct(err) == "text/xml"
+
+
+def test_rds_query_error_envelope(rds):
+ with pytest.raises(ClientError) as exc:
+ rds.describe_db_instances(DBInstanceIdentifier="wire-missing")
+ err = exc.value.response
+ assert err["Error"]["Code"] == "DBInstanceNotFound"
+ assert err["Error"]["Type"] == "Sender"
+ assert _wire_status(err) == 404
+ assert _wire_ct(err) == "text/xml"
+
+
+def test_docdb_query_error_envelope(docdb):
+ with pytest.raises(ClientError) as exc:
+ docdb.describe_db_instances(DBInstanceIdentifier="wire-missing")
+ err = exc.value.response
+ assert err["Error"]["Type"] == "Sender"
+ assert _wire_ct(err) == "text/xml"
+
+
+def test_cloudwatch_query_error_envelope():
+ # boto3 1.42+ speaks smithy-rpc-v2-cbor to CloudWatch: the Query path needs a raw request.
+ req = urllib.request.Request(
+ f"{ENDPOINT}/",
+ data=b"Action=GetDashboard&Version=2010-08-01&DashboardName=wire-missing",
+ headers={
+ "Content-Type": "application/x-www-form-urlencoded",
+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/"
+ "us-east-1/monitoring/aws4_request, "
+ "SignedHeaders=host, Signature=x",
+ },
+ )
+ with pytest.raises(urllib.error.HTTPError) as exc:
+ urllib.request.urlopen(req)
+ http_err = exc.value
+ body = http_err.read().decode()
+ assert http_err.headers["content-type"] == "text/xml"
+ assert not body.startswith("<?xml")
+ assert "<Type>Sender</Type>" in body
+ assert "ResourceNotFound" in body
+
+
+def test_ses_query_error_envelope(ses):
+ with pytest.raises(ClientError) as exc:
+ ses.describe_receipt_rule_set(RuleSetName="wire-missing")
+ err = exc.value.response
+ assert err["Error"]["Code"] == "RuleSetDoesNotExist"
+ assert err["Error"]["Type"] == "Sender"
+ assert _wire_ct(err) == "text/xml"
+
+
+def test_cfn_query_error_envelope(cfn):
+ with pytest.raises(ClientError) as exc:
+ cfn.describe_stacks(StackName="wire-missing")
+ err = exc.value.response
+ assert err["Error"]["Code"] == "ValidationError"
+ assert err["Error"]["Type"] == "Sender"
+ assert _wire_ct(err) == "text/xml"
+
+
+def test_ec2_error_envelope_has_no_type_and_charset(ec2):
+ with pytest.raises(ClientError) as exc:
+ ec2.describe_instances(InstanceIds=["i-0123456789abcdef0"])
+ err = exc.value.response
+ assert err["Error"]["Code"] == "InvalidInstanceID.NotFound"
+ assert err["Error"].get("Type") is None
+ assert _wire_ct(err) == "text/xml;charset=UTF-8"
+
+
+def test_route53_restxml_error_envelope(r53):
+ with pytest.raises(ClientError) as exc:
+ r53.get_hosted_zone(Id="/hostedzone/ZWIREMISSING000")
+ err = exc.value.response
+ assert err["Error"]["Type"] == "Sender"
+ assert _wire_ct(err) == "text/xml"
+
+
+def test_query_success_content_types(iam, sns, sts, ec, autoscaling,
+ elbv2, ses, rds, docdb, cfn):
+ calls = [
+ (iam.list_users, {}),
+ (sns.list_topics, {}),
+ (sts.get_caller_identity, {}),
+ (ec.describe_cache_clusters, {}),
+ (autoscaling.describe_auto_scaling_groups, {}),
+ (elbv2.describe_load_balancers, {}),
+ (ses.list_identities, {}),
+ (rds.describe_db_instances, {}),
+ (docdb.describe_db_instances, {}),
+ (cfn.list_stacks, {}),
+ ]
+ for call, kwargs in calls:
+ assert _wire_ct(call(**kwargs)) == "text/xml", call.__name__
+
+
+def test_cloudwatch_query_success_content_type():
+ req = urllib.request.Request(
+ f"{ENDPOINT}/",
+ data=b"Action=ListMetrics&Version=2010-08-01",
+ headers={
+ "Content-Type": "application/x-www-form-urlencoded",
+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/"
+ "us-east-1/monitoring/aws4_request, "
+ "SignedHeaders=host, Signature=x",
+ },
+ )
+ with urllib.request.urlopen(req) as resp:
+ assert resp.headers["content-type"] == "text/xml"
+
+
+def test_json_success_content_types(ddb, sqs, kin):
+ assert _wire_ct(ddb.list_tables()) == "application/x-amz-json-1.0"
+ assert _wire_ct(sqs.list_queues()) == "application/x-amz-json-1.0"
+ assert _wire_ct(kin.list_streams()) == "application/x-amz-json-1.1"
+
+
+def test_restxml_success_content_types(s3, r53):
+ assert _wire_ct(s3.list_buckets()) == "application/xml"
+ assert _wire_ct(r53.list_hosted_zones()) == "text/xml"
+
+
+def test_restjson_success_content_type(lam):
+ assert _wire_ct(lam.list_functions()) == "application/json"
+
+
+def test_ec2_success_content_type(ec2):
+ assert _wire_ct(ec2.describe_regions()) == "text/xml;charset=UTF-8"
+
+
+def test_s3_object_payload_content_type_not_rewritten(s3):
+ # A stored object's Content-Type is payload, not an envelope.
+ bucket = "wire-ct-payload"
+ s3.create_bucket(Bucket=bucket)
+ try:
+ s3.put_object(Bucket=bucket, Key="doc.xml", Body=b"<a/>",
+ ContentType="text/xml")
+ resp = s3.get_object(Bucket=bucket, Key="doc.xml")
+ assert _wire_ct(resp) == "text/xml"
+ finally:
+ s3.delete_object(Bucket=bucket, Key="doc.xml")
+ s3.delete_bucket(Bucket=bucket)
@pytest.mark.auth_contract
def test_ministack_auth_unset_is_permissive(tmp_path):
"""Exercise a fresh HTTP server without AUTH, even in the strict CI job."""
@@ -1331,3 +1536,37 @@ def test_ministack_auth_unset_is_permissive(tmp_path):
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=5)
+
+
+def test_auth_contracts_are_excluded_from_existing_shards(tmp_path):
+ import subprocess
+ import sys
+ from pathlib import Path
+
+ (tmp_path / "pytest.ini").write_text(
+ "[pytest]\nmarkers =\n serial\n data_plane\n auth_contract\n"
+ )
+ (tmp_path / "test_lanes.py").write_text(
+ "import pytest\n"
+ "def test_parallel(): pass\n"
+ "@pytest.mark.serial\ndef test_serial(): pass\n"
+ "@pytest.mark.data_plane\ndef test_data_plane(): pass\n"
+ "@pytest.mark.auth_contract\n"
+ "@pytest.mark.parametrize('value', [1, 2])\ndef test_auth(value): pass\n"
+ "@pytest.mark.auth_contract\[email protected]\ndef test_auth_serial(): pass\n"
+ "@pytest.mark.auth_contract\[email protected]_plane\ndef test_auth_data_plane(): pass\n"
+ )
+ (tmp_path / "test_auth_only.py").write_text(
+ "import pytest\[email protected]_contract\ndef test_only_auth(): pass\n"
+ )
+ scripts = Path(__file__).resolve().parents[1] / "scripts"
+ env = {**os.environ, "PYTHONPATH": str(scripts)}
+ # Parent pytest flags must not change the nested collection's selection.
+ env.pop("PYTEST_ADDOPTS", None)
+ result = subprocess.run(
+ [sys.executable, "-m", "pytest", "--collect-only", "-q", "-p", "_collect_plan_plugin"],
+ cwd=tmp_path, env=env, capture_output=True, text=True, timeout=30,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ counts = json.loads((tmp_path / ".pytest_collect_plan.json").read_text())
+ assert counts == {"test_lanes.py": {"parallel": 1, "serial": 1, "data_plane": 1}}
diff --git a/tests/test_rds.py b/tests/test_rds.py
index 686cc35a..2c6ad37b 100644
--- a/tests/test_rds.py
+++ b/tests/test_rds.py
@@ -4847,7 +4847,7 @@ def test_rds_reboot_db_instance(rds):
desc = rds.describe_db_instances(DBInstanceIdentifier="reboot-test")
assert desc["DBInstances"][0]["DBInstanceStatus"] == "available"
events = rds.describe_events(SourceIdentifier="reboot-test", SourceType="db-instance")["Events"]
- assert any(event["Message"] == "DB instance restarted" for event in events)
+ assert any(event["Message"] == "DB instance restarted." for event in events)
finally:
rds.delete_db_instance(DBInstanceIdentifier="reboot-test", SkipFinalSnapshot=True)
@@ -4859,6 +4859,255 @@ def test_rds_reboot_db_instance_not_found(rds):
assert exc.value.response["Error"]["Code"] == "DBInstanceNotFound"
+def reboot_instance(monkeypatch):
+ """An in-process instance record for the reboot worker; no server or Docker needed."""
+ monkeypatch.setattr(_imm_rds, "_single_instance_response", lambda *args: args[-1].copy())
+ value = {
+ "DBInstanceIdentifier": "reboot-test", "DBInstanceStatus": "available",
+ "Engine": "mysql", "MasterUsername": "root", "_MasterUserPassword": "test",
+ "_docker_container_id": "owned", "_HostPort": 13306,
+ "Endpoint": {"Address": "localhost", "Port": 13306},
+ }
+ _imm_rds._instances["reboot-test"] = value
+ yield value
+ _imm_rds._instances.pop("reboot-test", None)
+
+
+def test_rds_reboot_is_async_and_waits_for_sql(monkeypatch, reboot_instance):
+ entered, release, done = threading.Event(), threading.Event(), threading.Event()
+ calls = []
+
+ class Container:
+ status = "running"
+
+ def stop(self, timeout):
+ calls.append("stop")
+
+ def start(self):
+ calls.append("start")
+
+ def reload(self):
+ pass
+
+ monkeypatch.setattr(_imm_rds, "_get_docker",
+ lambda: types.SimpleNamespace(containers=types.SimpleNamespace(get=lambda ident: Container())))
+
+ def ready(*args):
+ calls.append("ready")
+ entered.set()
+ assert release.wait(5)
+ return True
+
+ monkeypatch.setattr(_imm_rds, "_wait_for_database_ready", ready)
+ original = _imm_rds._finish_instance_reboot
+
+ def finish(*args):
+ try:
+ original(*args)
+ finally:
+ done.set()
+
+ monkeypatch.setattr(_imm_rds, "_finish_instance_reboot", finish)
+ try:
+ _imm_rds._reboot_db_instance({"DBInstanceIdentifier": "reboot-test"})
+ assert entered.wait(5)
+ assert reboot_instance["DBInstanceStatus"] == "rebooting"
+ assert calls == ["stop", "start", "ready"]
+ finally:
+ release.set()
+ assert done.wait(5)
+ assert reboot_instance["DBInstanceStatus"] == "available"
+
+
+def test_rds_reboot_refuses_an_instance_that_is_not_available(reboot_instance):
+ reboot_instance["DBInstanceStatus"] = "stopped"
+ status, _, body = _imm_rds._reboot_db_instance({"DBInstanceIdentifier": "reboot-test"})
+ assert status == 400
+ assert b"InvalidDBInstanceState" in body
+ assert b"DBInstance reboot-test is in stopped state but expected it to be one of available." in body
+
+
+def test_rds_reboot_preserves_mysql_data_and_breaks_sessions(monkeypatch, reboot_instance):
+ import docker
+ import pymysql
+
+ client = docker.from_env()
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ port = sock.getsockname()[1]
+ container = client.containers.run(
+ "mysql:8.0", detach=True, ports={"3306/tcp": ("127.0.0.1", port)},
+ environment={"MYSQL_ROOT_PASSWORD": "test", "MYSQL_ROOT_HOST": "%"},
+ )
+ connection = None
+ try:
+ container.reload()
+ port = int(container.attrs["NetworkSettings"]["Ports"]["3306/tcp"][0]["HostPort"])
+ reboot_instance["_HostPort"] = port
+ reboot_instance["_docker_container_id"] = container.id
+
+ def connect():
+ return pymysql.connect(host="127.0.0.1", port=port, user="root", password="test", connect_timeout=2,
+ read_timeout=2, autocommit=True)
+
+ deadline = time.monotonic() + 90
+ while time.monotonic() < deadline:
+ try:
+ connection = connect()
+ break
+ except pymysql.Error:
+ time.sleep(0.5)
+ assert connection is not None
+ with connection.cursor() as cursor:
+ cursor.execute("CREATE DATABASE reboot_test")
+ cursor.execute("CREATE TABLE reboot_test.evidence (value INT)")
+ cursor.execute("INSERT INTO reboot_test.evidence VALUES (42)")
+ monkeypatch.setattr(_imm_rds, "_get_docker", lambda: client)
+ response = _imm_rds._reboot_db_instance({"DBInstanceIdentifier": "reboot-test"})
+ assert response["DBInstanceStatus"] == "rebooting"
+ deadline = time.monotonic() + 90
+ while reboot_instance["DBInstanceStatus"] == "rebooting" and time.monotonic() < deadline:
+ time.sleep(0.2)
+ assert reboot_instance["DBInstanceStatus"] == "available"
+ with pytest.raises(pymysql.Error):
+ connection.ping(reconnect=False)
+ with connect() as recovered:
+ with recovered.cursor() as cursor:
+ cursor.execute("SELECT value FROM reboot_test.evidence")
+ assert cursor.fetchone() == (42,)
+ finally:
+ if connection:
+ connection.close()
+ container.remove(force=True, v=True)
+
+
+def test_rds_reboot_failed_restart_does_not_report_available(monkeypatch, reboot_instance):
+ def fail():
+ raise RuntimeError("Docker unavailable")
+
+ monkeypatch.setattr(_imm_rds, "_get_docker", fail)
+ reboot_instance["DBInstanceStatus"] = "rebooting"
+ _imm_rds._finish_instance_reboot(reboot_instance, None)
+ assert reboot_instance["DBInstanceStatus"] == "failed"
+
+
+def test_rds_reboot_does_not_resurrect_a_replaced_instance(monkeypatch, reboot_instance):
+ replacement = dict(reboot_instance)
+
+ def ready(*args):
+ _imm_rds._instances["reboot-test"] = replacement
+ return True
+
+ container = types.SimpleNamespace(stop=lambda **kw: None, start=lambda: None)
+ monkeypatch.setattr(_imm_rds, "_get_docker",
+ lambda: types.SimpleNamespace(containers=types.SimpleNamespace(get=lambda ident: container)))
+ monkeypatch.setattr(_imm_rds, "_wait_for_database_ready", ready)
+ reboot_instance["DBInstanceStatus"] = "rebooting"
+ _imm_rds._finish_instance_reboot(reboot_instance, None)
+ assert _imm_rds._instances["reboot-test"] is replacement
+ assert reboot_instance["DBInstanceStatus"] == "rebooting"
+
+
+def clean_rds_events():
+ saved = dict(_imm_rds._events.items())
+ for key in list(_imm_rds._events):
+ del _imm_rds._events[key]
+ yield
+ for key in list(_imm_rds._events):
+ del _imm_rds._events[key]
+ _imm_rds._events.update(saved)
+
+
+def _describe_rds_events(**params):
+ """In-process DescribeEvents, parsed with botocore's Query parser."""
+ import botocore.session
+ from botocore.parsers import QueryParser
+
+ status, headers, body = _imm_rds._describe_events(params)
+ shape = botocore.session.get_session().get_service_model("rds").operation_model("DescribeEvents").output_shape
+ return status, QueryParser().parse({"status_code": status, "headers": headers, "body": body}, shape)
+
+
+def _record_rds_reboot_event(name="example"):
+ _imm_rds._record_reboot_event({"DBInstanceIdentifier": name,
+ "DBInstanceArn": f"arn:aws:rds:us-east-1:000000000000:db:{name}"})
+
+
+def test_rds_reboot_event_wire_shape_and_filters(clean_rds_events):
+ _record_rds_reboot_event("example")
+ _record_rds_reboot_event("other")
+ status, result = _describe_rds_events(SourceIdentifier="example", SourceType="db-instance")
+ assert status == 200
+ event, = result["Events"]
+ assert event["Message"] == "DB instance restarted."
+ assert event["EventCategories"] == ["availability"]
+ assert event["SourceArn"].endswith(":db:example")
+ assert abs(event["Date"].timestamp() - time.time()) < 2
+ assert _describe_rds_events(SourceType="db-cluster")[1]["Events"] == []
+ assert _describe_rds_events(SourceType="db-shard-group")[0] == 200
+ assert _describe_rds_events(**{"EventCategories.member.1": "failure"})[1]["Events"] == []
+ assert _describe_rds_events(StartTime="2100-01-01T00:00:00Z", EndTime="2100-01-02T00:00:00Z")[1]["Events"] == []
+
+
+def test_rds_events_pagination_has_no_duplicates(clean_rds_events):
+ for i in range(23):
+ _record_rds_reboot_event(str(i))
+ _, first = _describe_rds_events(MaxRecords="20")
+ _, second = _describe_rds_events(MaxRecords="20", Marker=first["Marker"])
+ assert len(first["Events"]) == 20
+ assert len(second["Events"]) == 3
+ assert "Marker" not in second
+ assert len({e["SourceIdentifier"] for e in first["Events"] + second["Events"]}) == 23
+
+
[email protected]("params", [{"SourceIdentifier": "x"}, {"MaxRecords": "19"}, {"MaxRecords": "101"},
+ {"Duration": "bad"}, {"Marker": "missing"}, {"StartTime": "bad"}])
+def test_rds_events_invalid_requests(clean_rds_events, params):
+ assert _describe_rds_events(**params)[0] == 400
+
+
+def test_rds_events_survive_persistence_and_are_region_scoped(clean_rds_events):
+ from ministack.core.responses import get_region, set_request_region
+
+ region = get_region()
+ _record_rds_reboot_event()
+ snapshot = _imm_rds.get_state()
+ try:
+ set_request_region("eu-north-1" if region != "eu-north-1" else "us-east-2")
+ assert _describe_rds_events()[1]["Events"] == []
+ finally:
+ set_request_region(region)
+ for key in list(_imm_rds._events):
+ del _imm_rds._events[key]
+ _imm_rds.load_persisted_state(snapshot)
+ assert len(_describe_rds_events()[1]["Events"]) == 1
+
+
+def test_rds_reboot_event_recorded_only_after_success(clean_rds_events, monkeypatch):
+ instance = {"DBInstanceIdentifier": "event-reboot", "DBInstanceStatus": "rebooting"}
+ _imm_rds._instances["event-reboot"] = instance
+ try:
+ monkeypatch.setattr(_imm_rds, "_get_docker", lambda: None)
+ _imm_rds._finish_instance_reboot(instance, None)
+ assert len(_describe_rds_events()[1]["Events"]) == 1
+ instance["DBInstanceStatus"] = "rebooting"
+ instance["_docker_container_id"] = "missing"
+
+ def fail(_):
+ raise RuntimeError("missing container")
+
+ monkeypatch.setattr(_imm_rds, "_get_docker",
+ lambda: types.SimpleNamespace(containers=types.SimpleNamespace(get=fail)))
+ _imm_rds._finish_instance_reboot(instance, None)
+ assert len(_describe_rds_events()[1]["Events"]) == 1
+ assert instance["DBInstanceStatus"] == "failed"
+ finally:
+ _imm_rds._instances.pop("event-reboot", None)
+
+
def test_rds_restore_from_snapshot(rds):
"""RestoreDBInstanceFromDBSnapshot creates a new instance from a snapshot."""
rds.create_db_instance(
diff --git a/tests/test_rds_events.py b/tests/test_rds_events.py
deleted file mode 100644
index 1db813c2..00000000
--- a/tests/test_rds_events.py
+++ /dev/null
@@ -1,96 +0,0 @@
-"""DescribeEvents wire contract checked with the botocore Query parser."""
-import time
-from types import SimpleNamespace
-
-import botocore.session
-import pytest
-from botocore.parsers import QueryParser
-
-from ministack.services import rds
-
-
[email protected](autouse=True)
-def clean_events():
- saved = dict(rds._events.items())
- for key in list(rds._events):
- del rds._events[key]
- yield
- for key in list(rds._events):
- del rds._events[key]
- rds._events.update(saved)
-
-
-def describe(**params):
- status, headers, body = rds._describe_events(params)
- shape = botocore.session.get_session().get_service_model("rds").operation_model("DescribeEvents").output_shape
- return status, QueryParser().parse({"status_code": status, "headers": headers, "body": body}, shape)
-
-
-def record(name="example"):
- rds._record_reboot_event({"DBInstanceIdentifier": name, "DBInstanceArn": f"arn:aws:rds:us-east-1:000000000000:db:{name}"})
-
-
-def test_reboot_event_wire_shape_and_filters():
- record("example")
- record("other")
- status, result = describe(SourceIdentifier="example", SourceType="db-instance")
- assert status == 200
- event, = result["Events"]
- assert event["Message"] == "DB instance restarted"
- assert event["EventCategories"] == ["availability"]
- assert event["SourceArn"].endswith(":db:example")
- assert abs(event["Date"].timestamp() - time.time()) < 2
- assert describe(SourceType="db-cluster")[1]["Events"] == []
- assert describe(**{"EventCategories.member.1": "failure"})[1]["Events"] == []
- assert describe(StartTime="2100-01-01T00:00:00Z", EndTime="2100-01-02T00:00:00Z")[1]["Events"] == []
-
-
-def test_pagination_has_no_duplicates():
- for i in range(23):
- record(str(i))
- _, first = describe(MaxRecords="20")
- _, second = describe(MaxRecords="20", Marker=first["Marker"])
- assert len(first["Events"]) == 20
- assert len(second["Events"]) == 3
- assert "Marker" not in second
- assert len({e["SourceIdentifier"] for e in first["Events"] + second["Events"]}) == 23
-
-
[email protected]("params", [{"SourceIdentifier": "x"}, {"MaxRecords": "19"}, {"MaxRecords": "101"}, {"Duration": "bad"}, {"Marker": "missing"}, {"StartTime": "bad"}])
-def test_invalid_requests(params):
- assert describe(**params)[0] == 400
-
-
-def test_events_survive_persistence_and_are_region_scoped():
- from ministack.core.responses import get_region, set_request_region
- region = get_region()
- record()
- snapshot = rds.get_state()
- try:
- set_request_region("eu-north-1" if region != "eu-north-1" else "us-east-2")
- assert describe()[1]["Events"] == []
- finally:
- set_request_region(region)
- for key in list(rds._events):
- del rds._events[key]
- rds.load_persisted_state(snapshot)
- assert len(describe()[1]["Events"]) == 1
-
-
-def test_completion_only_after_success(monkeypatch):
- instance = {"DBInstanceIdentifier": "event-reboot", "DBInstanceStatus": "rebooting"}
- rds._instances["event-reboot"] = instance
- try:
- monkeypatch.setattr(rds, "_get_docker", lambda: None)
- rds._finish_instance_reboot(instance, None, 0)
- assert len(describe()[1]["Events"]) == 1
- instance["DBInstanceStatus"] = "rebooting"
- instance["_docker_container_id"] = "missing"
- def fail(_):
- raise RuntimeError("missing container")
- monkeypatch.setattr(rds, "_get_docker", lambda: SimpleNamespace(containers=SimpleNamespace(get=fail)))
- rds._finish_instance_reboot(instance, None, 0)
- assert len(describe()[1]["Events"]) == 1
- assert instance["DBInstanceStatus"] == "failed"
- finally:
- rds._instances.pop("event-reboot", None)
diff --git a/tests/test_rds_reboot.py b/tests/test_rds_reboot.py
deleted file mode 100644
index c5e015af..00000000
--- a/tests/test_rds_reboot.py
+++ /dev/null
@@ -1,156 +0,0 @@
-"""RDS reboot lifecycle; direct handler tests do not require a running server."""
-import threading
-import time
-from types import SimpleNamespace
-
-import pytest
-
-from ministack.services import rds
-
-
-def instance(monkeypatch):
- monkeypatch.setattr(rds, "_single_instance_response", lambda *args: args[-1].copy())
- value = {
- "DBInstanceIdentifier": "reboot-test", "DBInstanceStatus": "available",
- "Engine": "mysql", "MasterUsername": "root", "_MasterUserPassword": "test",
- "_docker_container_id": "owned", "_HostPort": 13306,
- "Endpoint": {"Address": "localhost", "Port": 13306},
- }
- rds._instances["reboot-test"] = value
- yield value
- rds._instances.pop("reboot-test", None)
-
-
-def test_reboot_is_async_and_waits_for_sql(monkeypatch, instance):
- entered = threading.Event()
- release = threading.Event()
- done = threading.Event()
- calls = []
- class Container:
- status = "running"
- def stop(self, timeout):
- calls.append("stop")
- def start(self):
- calls.append("start")
- def reload(self):
- pass
- monkeypatch.setattr(rds, "_get_docker", lambda: SimpleNamespace(containers=SimpleNamespace(get=lambda ident: Container())))
- def ready(*args):
- calls.append("ready")
- entered.set()
- assert release.wait(5)
- return True
- monkeypatch.setattr(rds, "_wait_for_database_ready", ready)
- original = rds._finish_instance_reboot
- def finish(*args):
- try:
- original(*args)
- finally:
- done.set()
- monkeypatch.setattr(rds, "_finish_instance_reboot", finish)
- try:
- rds._reboot_db_instance({"DBInstanceIdentifier": "reboot-test"})
- assert entered.wait(5)
- assert instance["DBInstanceStatus"] == "rebooting"
- assert calls == ["stop", "start", "ready"]
- finally:
- release.set()
- assert done.wait(5)
- assert instance["DBInstanceStatus"] == "available"
-
-
-def test_reboot_preserves_mysql_data_and_breaks_sessions(monkeypatch, instance):
- import socket
-
- import docker
- import pymysql
- client = docker.from_env()
- with socket.socket() as sock:
- sock.bind(("127.0.0.1", 0))
- port = sock.getsockname()[1]
- container = client.containers.run(
- "mysql:8.0", detach=True, ports={"3306/tcp": ("127.0.0.1", port)},
- environment={"MYSQL_ROOT_PASSWORD": "test", "MYSQL_ROOT_HOST": "%"},
- )
- connection = None
- try:
- container.reload()
- port = int(container.attrs["NetworkSettings"]["Ports"]["3306/tcp"][0]["HostPort"])
- instance["_HostPort"] = port
- instance["_docker_container_id"] = container.id
- def connect():
- return pymysql.connect(host="127.0.0.1", port=port, user="root", password="test", connect_timeout=2, read_timeout=2, autocommit=True)
- deadline = time.monotonic() + 90
- while time.monotonic() < deadline:
- try:
- connection = connect()
- break
- except pymysql.Error:
- time.sleep(0.5)
- assert connection is not None
- with connection.cursor() as cursor:
- cursor.execute("CREATE DATABASE reboot_test")
- cursor.execute("CREATE TABLE reboot_test.evidence (value INT)")
- cursor.execute("INSERT INTO reboot_test.evidence VALUES (42)")
- monkeypatch.setattr(rds, "_get_docker", lambda: client)
- monkeypatch.setenv("RDS_REBOOT_DOWNTIME_SECONDS", "2")
- response = rds._reboot_db_instance({"DBInstanceIdentifier": "reboot-test"})
- assert response["DBInstanceStatus"] == "rebooting"
- deadline = time.monotonic() + 90
- while instance["DBInstanceStatus"] == "rebooting" and time.monotonic() < deadline:
- time.sleep(0.2)
- assert instance["DBInstanceStatus"] == "available"
- with pytest.raises(pymysql.Error):
- connection.ping(reconnect=False)
- with connect() as recovered:
- with recovered.cursor() as cursor:
- cursor.execute("SELECT value FROM reboot_test.evidence")
- assert cursor.fetchone() == (42,)
- finally:
- if connection:
- connection.close()
- container.remove(force=True, v=True)
-
-
-def test_downtime_is_between_stop_and_start(monkeypatch, instance):
- calls = []
- container = SimpleNamespace(stop=lambda **kw: calls.append("stop"), start=lambda: calls.append("start"))
- monkeypatch.setattr(rds, "_get_docker", lambda: SimpleNamespace(containers=SimpleNamespace(get=lambda ident: container)))
- monkeypatch.setattr(rds.time, "sleep", lambda seconds: calls.append(seconds))
- monkeypatch.setattr(rds, "_wait_for_database_ready", lambda *a: True)
- instance["DBInstanceStatus"] = "rebooting"
- rds._finish_instance_reboot(instance, None, 7)
- assert calls == ["stop", 7, "start"]
- assert instance["DBInstanceStatus"] == "available"
-
-
-def test_failed_restart_does_not_report_available(monkeypatch, instance):
- def fail():
- raise RuntimeError("Docker unavailable")
- monkeypatch.setattr(rds, "_get_docker", fail)
- instance["DBInstanceStatus"] = "rebooting"
- rds._finish_instance_reboot(instance, None, 0)
- assert instance["DBInstanceStatus"] == "failed"
-
-
-def test_deleted_instance_is_not_resurrected(monkeypatch, instance):
- replacement = dict(instance)
- def ready(*args):
- rds._instances["reboot-test"] = replacement
- return True
- container = SimpleNamespace(stop=lambda **kw: None, start=lambda: None)
- monkeypatch.setattr(rds, "_get_docker", lambda: SimpleNamespace(containers=SimpleNamespace(get=lambda ident: container)))
- monkeypatch.setattr(rds, "_wait_for_database_ready", ready)
- instance["DBInstanceStatus"] = "rebooting"
- rds._finish_instance_reboot(instance, None, 0)
- assert rds._instances["reboot-test"] is replacement
- assert instance["DBInstanceStatus"] == "rebooting"
-
-
[email protected]("delay", ["-1", "nan", "inf", "bad", "3601"])
-def test_invalid_downtime_is_rejected(monkeypatch, instance, delay):
- monkeypatch.setenv("RDS_REBOOT_DOWNTIME_SECONDS", delay)
- rds._reboot_db_instance({"DBInstanceIdentifier": "reboot-test"})
- assert instance["DBInstanceStatus"] == "available"
diff --git a/tests/test_s3.py b/tests/test_s3.py
index 9d50ee1f..43be6497 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -8237,9 +8237,813 @@ def test_s3_create_owned_bucket_again(s3):
s3.delete_bucket(Bucket=west)
-# IAM contracts: real HTTP against the server mode selected by CI.
-# Evidence: existing IAM/action extraction tests and local MiniStack SDK calls;
-# these tests are not observations from a real AWS account.
+# Under AUTH=true a request without credentials is anonymous. S3 answers it only
+# through the bucket owner's public grants (AllUsers ACL grants or a bucket policy
+# for Principal "*", unless Public Access Block shuts them off); otherwise 403
+# AccessDenied. Source: the S3 User Guide on anonymous requests and Block Public
+# Access; not measured against AWS here.
+
+def _anonymous_bucket(monkeypatch, auth=True, **bucket_headers):
+ import ministack.app as app_mod
+
+ monkeypatch.setattr(app_mod, "AUTH", auth)
+ bucket = f"anon-{uuid.uuid4().hex[:10]}"
+ assert _lock_call("PUT", f"/{bucket}", bucket_headers)[0] == 200
+ assert _lock_call("PUT", f"/{bucket}/k", {}, b"secret")[0] == 200
+ return bucket
+
+
+def _anonymous_call(method, path, headers=None, body=b"", internal=False):
+ import asyncio
+
+ from ministack.core.responses import request_scope
+ from ministack.services import s3 as s3mod
+
+ with request_scope("000000000000", "us-east-1"):
+ return asyncio.run(s3mod.handle_request(method, path, headers or {}, body, {}, internal=internal))
+
+
+def _public_read_policy(bucket):
+ return json.dumps({"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject",
+ "Resource": f"arn:aws:s3:::{bucket}/*",
+ }]}).encode()
+
+
+def test_anonymous_request_to_a_private_bucket_is_denied_under_auth(monkeypatch):
+ bucket = _anonymous_bucket(monkeypatch)
+ for method, path, body in [("GET", f"/{bucket}/k", b""), ("HEAD", f"/{bucket}/k", b""),
+ ("GET", f"/{bucket}/missing", b""), ("GET", f"/{bucket}", b""),
+ ("PUT", f"/{bucket}/new", b"x"), ("DELETE", f"/{bucket}/k", b"")]:
+ status, _, resp = _anonymous_call(method, path, body=body)
+ assert status == 403, (method, path)
+ if method != "HEAD":
+ assert b"<Code>AccessDenied</Code>" in resp
+ # The owner still reads it, and the object is still there.
+ status, _, resp = _lock_call("GET", f"/{bucket}/k")
+ assert (status, resp) == (200, b"secret")
+
+
+def test_s3_create_bucket_object_ownership_header(s3):
+ name = f"own-hdr-{uuid.uuid4().hex[:10]}"
+ s3.create_bucket(Bucket=name, ObjectOwnership="ObjectWriter")
+ try:
+ rules = s3.get_bucket_ownership_controls(Bucket=name)["OwnershipControls"]["Rules"]
+ assert rules == [{"ObjectOwnership": "ObjectWriter"}]
+ finally:
+ s3.delete_bucket(Bucket=name)
+
+
+def test_anonymous_request_reads_a_public_object_under_auth(monkeypatch):
+ # Object ACLs only count on a bucket with ACLs enabled (not BucketOwnerEnforced).
+ bucket = _anonymous_bucket(monkeypatch, **{"x-amz-object-ownership": "BucketOwnerPreferred"})
+ assert _lock_call("PUT", f"/{bucket}/pub", {"x-amz-acl": "public-read"}, b"open")[0] == 200
+ status, _, resp = _anonymous_call("GET", f"/{bucket}/pub")
+ assert (status, resp) == (200, b"open")
+ assert _anonymous_call("GET", f"/{bucket}/k")[0] == 403
+
+
+def test_anonymous_request_follows_a_public_bucket_policy_and_public_access_block(monkeypatch):
+ bucket = _anonymous_bucket(monkeypatch)
+ import asyncio
+
+ from ministack.core.responses import request_scope
+ from ministack.services import s3 as s3mod
+
+ with request_scope("000000000000", "us-east-1"):
+ status, _, _ = asyncio.run(s3mod.handle_request(
+ "PUT", f"/{bucket}", {"authorization": _ROOT_AUTHORIZATION}, _public_read_policy(bucket),
+ {"policy": [""]}))
+ assert status == 204
+ status, _, resp = _anonymous_call("GET", f"/{bucket}/k")
+ assert (status, resp) == (200, b"secret")
+ # The policy allows only s3:GetObject.
+ assert _anonymous_call("PUT", f"/{bucket}/k", body=b"overwrite")[0] == 403
+
+ block = (b"<PublicAccessBlockConfiguration><RestrictPublicBuckets>true</RestrictPublicBuckets>"
+ b"</PublicAccessBlockConfiguration>")
+ with request_scope("000000000000", "us-east-1"):
+ status, _, _ = asyncio.run(s3mod.handle_request(
+ "PUT", f"/{bucket}", {"authorization": _ROOT_AUTHORIZATION}, block, {"publicAccessBlock": [""]}))
+ assert status == 200
+ assert _anonymous_call("GET", f"/{bucket}/k")[0] == 403
+
+
+def test_anonymous_request_is_served_without_auth(monkeypatch):
+ bucket = _anonymous_bucket(monkeypatch, auth=False)
+ status, _, resp = _anonymous_call("GET", f"/{bucket}/k")
+ assert (status, resp) == (200, b"secret")
+
+
+def test_internal_call_without_credentials_is_not_anonymous(monkeypatch):
+ bucket = _anonymous_bucket(monkeypatch)
+ assert _anonymous_call("PUT", f"/{bucket}/delivered", body=b"x", internal=True)[0] == 200
+# ---------------------------------------------------------------------------
+# Bucket home region (#2158)
+# ---------------------------------------------------------------------------
+
+
[email protected]("headers,query,expected", [
+ ({"authorization": "AWS4-HMAC-SHA256 Credential=AKID/20261012/eu-west-1/s3/aws4_request, "
+ "SignedHeaders=host, Signature=abc"}, {}, "eu-west-1"),
+ ({}, {"X-Amz-Algorithm": ["AWS4-HMAC-SHA256"],
+ "X-Amz-Credential": ["AKID/20261012/us-west-2/s3/aws4_request"]}, "us-west-2"),
+ ({"authorization": "AWS4-HMAC-SHA256 Credential=AKID/20261012/eu-west-1/sqs/aws4_request, "
+ "SignedHeaders=host, Signature=abc"}, {}, None),
+ ({"authorization": "AWS4-ECDSA-P256-SHA256 Credential=AKID/20261012/s3/aws4_request, "
+ "SignedHeaders=host, Signature=abc", "x-amz-region-set": "eu-west-1"}, {}, None),
+ ({"authorization": "AWS AKID:sig"}, {}, None),
+ ({}, {}, None),
+ ({"authorization": "AWS4-HMAC-SHA256 Credential=broken"}, {}, None),
+])
+def test_s3_signed_region(headers, query, expected):
+ from ministack.services import s3 as s3_svc
+
+ assert s3_svc._signed_region(headers, query) == expected
+
+
+def test_s3_error_extra_elements_and_headers():
+ from xml.etree.ElementTree import fromstring
+
+ from ministack.services import s3 as s3_svc
+
+ status, headers, body = s3_svc._error("Plain", "msg", 400, "/b")
+ assert status == 400 and headers == {"Content-Type": "application/xml"}
+ assert [c.tag for c in fromstring(body)] == ["Code", "Message", "Resource", "RequestId"]
+
+ status, headers, body = s3_svc._error(
+ "PermanentRedirect", "moved", 301, "/b",
+ extra={"Endpoint": "b.s3-eu-west-1.amazonaws.com", "Bucket": "b"},
+ headers={"x-amz-bucket-region": "eu-west-1"},
+ )
+ root = fromstring(body)
+ assert status == 301
+ assert headers == {"Content-Type": "application/xml", "x-amz-bucket-region": "eu-west-1"}
+ assert [c.tag for c in root] == ["Code", "Message", "Resource", "Endpoint", "Bucket", "RequestId"]
+ assert root.findtext("Endpoint") == "b.s3-eu-west-1.amazonaws.com"
+
+
+def test_s3_list_buckets_region_filter(s3):
+ tag = _uuid_mod.uuid4().hex[:8]
+ east = [f"lbr-{tag}-e{i}" for i in range(2)]
+ west = [f"lbr-{tag}-w{i}" for i in range(3)]
+ for name in east:
+ s3.create_bucket(Bucket=name)
+ for name in west:
+ s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})
+ euw1 = _regional_client("s3", "eu-west-1")
+ prefix = f"lbr-{tag}-"
+ try:
+ listed = euw1.list_buckets(Prefix=prefix, BucketRegion="eu-west-1")["Buckets"]
+ assert [b["Name"] for b in listed] == west
+ assert {b["BucketRegion"] for b in listed} == {"eu-west-1"}
+
+ listed = s3.list_buckets(Prefix=prefix, BucketRegion="us-east-1")["Buckets"]
+ assert [b["Name"] for b in listed] == east
+
+ # Pagination stays within the filter.
+ names, token = [], None
+ while True:
+ kwargs = {"Prefix": prefix, "BucketRegion": "eu-west-1", "MaxBuckets": 1}
+ if token:
+ kwargs["ContinuationToken"] = token
+ page = euw1.list_buckets(**kwargs)
+ names += [b["Name"] for b in page["Buckets"]]
+ token = page.get("ContinuationToken")
+ if not token:
+ break
+ assert names == west
+
+ # No filter lists every region.
+ listed = euw1.list_buckets(Prefix=prefix)["Buckets"]
+ assert [b["Name"] for b in listed] == sorted(east + west)
+ finally:
+ for name in east:
+ s3.delete_bucket(Bucket=name)
+ for name in west:
+ euw1.delete_bucket(Bucket=name)
+
+
+def test_s3_list_buckets_region_filter_must_match_endpoint(s3):
+ with pytest.raises(ClientError) as exc:
+ s3.list_buckets(BucketRegion="eu-west-1")
+ err = exc.value.response["Error"]
+ assert err["Code"] == "InvalidArgument"
+ assert err["Message"] == ("Requests with bucket-region specified must be made to the "
+ "corresponding regional endpoint")
+ assert err["ArgumentName"] == "bucket-region"
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+
+
+def _raw_signed(method, path, region, host=None, presign=False, body=b""):
+ """Send a SigV4-signed S3 request without any client-side redirect
+ handling. ``host`` overrides the Host header (signed as sent)."""
+ import http.client
+
+ from botocore.auth import S3SigV4Auth, S3SigV4QueryAuth
+ from botocore.awsrequest import AWSRequest
+ from botocore.credentials import Credentials
+
+ parsed = urlparse(ENDPOINT)
+ netloc = host or parsed.netloc
+ req = AWSRequest(method=method, url=f"http://{netloc}{path}", data=body)
+ creds = Credentials("test", "test")
+ if presign:
+ S3SigV4QueryAuth(creds, "s3", region, expires=300).add_auth(req)
+ else:
+ req.headers["x-amz-content-sha256"] = hashlib.sha256(body).hexdigest()
+ S3SigV4Auth(creds, "s3", region).add_auth(req)
+ target = urlparse(req.url)
+ conn = http.client.HTTPConnection(parsed.hostname, parsed.port or 80, timeout=30)
+ headers = {k: v for k, v in req.headers.items()}
+ headers["Host"] = netloc
+ conn.request(method, target.path + (f"?{target.query}" if target.query else ""), body=body or None,
+ headers=headers)
+ resp = conn.getresponse()
+ data = resp.read()
+ conn.close()
+ return resp.status, {k.lower(): v for k, v in resp.getheaders()}, data
+
+
+def _xml_error(body):
+ from xml.etree.ElementTree import fromstring
+
+ root = fromstring(body)
+ return {child.tag: child.text for child in root}
+
+
+def euw1_bucket(s3):
+ name = f"home-euw1-{_uuid_mod.uuid4().hex[:8]}"
+ s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})
+ euw1 = _regional_client("s3", "eu-west-1")
+ euw1.put_object(Bucket=name, Key="k.txt", Body=b"hello")
+ yield name
+ for obj in euw1.list_objects_v2(Bucket=name).get("Contents", []):
+ euw1.delete_object(Bucket=name, Key=obj["Key"])
+ euw1.delete_bucket(Bucket=name)
+
+
+_REDIRECT_MSG = ("The bucket you are attempting to access must be addressed using the specified "
+ "endpoint. Please send all future requests to this endpoint.")
+
+
+def test_s3_wrong_region_get_is_permanent_redirect(euw1_bucket):
+ for presign in (False, True):
+ status, headers, body = _raw_signed("GET", f"/{euw1_bucket}/k.txt", "us-west-2", presign=presign)
+ assert status == 301, body
+ assert headers["x-amz-bucket-region"] == "eu-west-1"
+ err = _xml_error(body)
+ assert err["Code"] == "PermanentRedirect"
+ assert err["Message"] == _REDIRECT_MSG
+ assert err["Endpoint"] == f"{euw1_bucket}.s3-eu-west-1.amazonaws.com"
+ assert err["Bucket"] == euw1_bucket
+
+ # A us-east-1 client on the global host is pointed at the global endpoint.
+ status, headers, body = _raw_signed("PUT", f"/{euw1_bucket}/new.txt", "us-east-1", body=b"x")
+ assert status == 301
+ assert _xml_error(body)["Endpoint"] == f"{euw1_bucket}.s3.amazonaws.com"
+ assert headers["x-amz-bucket-region"] == "eu-west-1"
+
+
+def test_s3_wrong_region_head_is_bodiless_redirect(euw1_bucket):
+ for path in (f"/{euw1_bucket}", f"/{euw1_bucket}/k.txt"):
+ status, headers, body = _raw_signed("HEAD", path, "us-east-1")
+ assert (status, body) == (301, b"")
+ assert headers["x-amz-bucket-region"] == "eu-west-1"
+
+
+def test_s3_wrong_region_at_home_endpoint_is_authorization_error(euw1_bucket):
+ host = f"s3.eu-west-1.{urlparse(ENDPOINT).netloc}"
+ status, headers, body = _raw_signed("GET", f"/{euw1_bucket}/k.txt", "us-east-1", host=host)
+ assert status == 400
+ err = _xml_error(body)
+ assert err["Code"] == "AuthorizationHeaderMalformed"
+ assert err["Message"] == ("The authorization header is malformed; the region 'us-east-1' is wrong; "
+ "expecting 'eu-west-1'")
+ assert err["Region"] == "eu-west-1"
+ assert "x-amz-bucket-region" not in headers
+
+ vhost = f"{euw1_bucket}.s3.eu-west-1.{urlparse(ENDPOINT).netloc}"
+ status, headers, body = _raw_signed("GET", "/k.txt", "us-east-1", host=vhost, presign=True)
+ assert status == 400
+ err = _xml_error(body)
+ assert err["Code"] == "AuthorizationQueryParametersError"
+ assert err["Message"] == ("Error parsing the X-Amz-Credential parameter; the region 'us-east-1' is "
+ "wrong; expecting 'eu-west-1'")
+ assert err["Region"] == "eu-west-1"
+
+ status, headers, body = _raw_signed("HEAD", f"/{euw1_bucket}", "us-east-1", host=host)
+ assert (status, body) == (400, b"")
+ assert headers["x-amz-bucket-region"] == "eu-west-1"
+ status, headers, body = _raw_signed("HEAD", f"/{euw1_bucket}/k.txt", "us-east-1", host=host)
+ assert (status, body) == (400, b"")
+ assert "x-amz-bucket-region" not in headers
+
+
+def test_s3_wrong_region_exemptions_and_match(euw1_bucket):
+ status, _, body = _raw_signed("GET", f"/{euw1_bucket}?location", "us-east-1")
+ assert status == 200 and b"eu-west-1" in body
+ status, _, body = _raw_signed("GET", "/", "ap-south-1")
+ assert status == 200 and euw1_bucket.encode() in body
+ status, _, body = _raw_signed("GET", f"/{euw1_bucket}/k.txt", "eu-west-1")
+ assert (status, body) == (200, b"hello")
+ status, _, _ = _raw_signed("GET", f"/no-such-{euw1_bucket}/k.txt", "us-west-2")
+ assert status == 404
+
+
+def test_s3_unsigned_region_request_is_not_redirected(euw1_bucket):
+ """Anonymous requests carry no signing region, so a public-read object in
+ eu-west-1 answers 200 wherever the request lands."""
+ import urllib.request
+
+ _regional_client("s3", "eu-west-1").put_object(Bucket=euw1_bucket, Key="public.txt", Body=b"open",
+ ACL="public-read")
+ with urllib.request.urlopen(f"{ENDPOINT}/{euw1_bucket}/public.txt") as resp:
+ assert (resp.status, resp.read()) == (200, b"open")
+
+
+def test_s3_cross_region_boto3_follows_redirect(s3):
+ """boto3 configured for us-east-1 reaches a us-west-2 bucket through the
+ PermanentRedirect + x-amz-bucket-region it gets back."""
+ name = f"redir-usw2-{_uuid_mod.uuid4().hex[:8]}"
+ usw2 = _regional_client("s3", "us-west-2")
+ usw2.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": "us-west-2"})
+ try:
+ s3.put_object(Bucket=name, Key="a.txt", Body=b"redirected")
+ assert s3.get_object(Bucket=name, Key="a.txt")["Body"].read() == b"redirected"
+ assert [o["Key"] for o in s3.list_objects_v2(Bucket=name)["Contents"]] == ["a.txt"]
+ assert s3.head_bucket(Bucket=name)["ResponseMetadata"]["HTTPHeaders"]["x-amz-bucket-region"] == "us-west-2"
+ assert s3.head_object(Bucket=name, Key="a.txt")["ContentLength"] == 10
+ s3.delete_object(Bucket=name, Key="a.txt")
+ assert usw2.list_objects_v2(Bucket=name)["KeyCount"] == 0
+ finally:
+ usw2.delete_bucket(Bucket=name)
+
+
+def test_s3_cross_region_copy_and_upload_part_copy(s3):
+ tag = _uuid_mod.uuid4().hex[:8]
+ src, dst = f"copy-src-usw2-{tag}", f"copy-dst-euw1-{tag}"
+ usw2, euw1 = _regional_client("s3", "us-west-2"), _regional_client("s3", "eu-west-1")
+ usw2.create_bucket(Bucket=src, CreateBucketConfiguration={"LocationConstraint": "us-west-2"})
+ euw1.create_bucket(Bucket=dst, CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})
+ part = b"p" * (5 * 1024 * 1024)
+ try:
+ usw2.put_object(Bucket=src, Key="obj", Body=b"copy me")
+ usw2.put_object(Bucket=src, Key="big", Body=part)
+ euw1.copy_object(Bucket=dst, Key="copied", CopySource={"Bucket": src, "Key": "obj"})
+ assert euw1.get_object(Bucket=dst, Key="copied")["Body"].read() == b"copy me"
+
+ upload = euw1.create_multipart_upload(Bucket=dst, Key="multi")
+ etag = euw1.upload_part_copy(Bucket=dst, Key="multi", UploadId=upload["UploadId"], PartNumber=1,
+ CopySource={"Bucket": src, "Key": "big"})["CopyPartResult"]["ETag"]
+ euw1.complete_multipart_upload(Bucket=dst, Key="multi", UploadId=upload["UploadId"],
+ MultipartUpload={"Parts": [{"PartNumber": 1, "ETag": etag}]})
+ assert euw1.head_object(Bucket=dst, Key="multi")["ContentLength"] == len(part)
+ finally:
+ for client, bucket in ((usw2, src), (euw1, dst)):
+ for obj in client.list_objects_v2(Bucket=bucket).get("Contents", []):
+ client.delete_object(Bucket=bucket, Key=obj["Key"])
+ client.delete_bucket(Bucket=bucket)
+
+
+# ---------------------------------------------------------------------------
+# Cross-Region Replication (#2158)
+# ---------------------------------------------------------------------------
+
+_REPL_ROLE = "arn:aws:iam::000000000000:role/repl"
+
+
+def _versioned_bucket(region, slug):
+ client = _regional_client("s3", region)
+ name = f"crr-{slug}-{_uuid_mod.uuid4().hex[:8]}"
+ kwargs = {} if region == "us-east-1" else {"CreateBucketConfiguration": {"LocationConstraint": region}}
+ client.create_bucket(Bucket=name, **kwargs)
+ client.put_bucket_versioning(Bucket=name, VersioningConfiguration={"Status": "Enabled"})
+ return client, name
+
+
+def _replicate(client, src, dst, **rule):
+ rule = {"ID": "r1", "Status": "Enabled", "Destination": {"Bucket": f"arn:aws:s3:::{dst}"}, **rule}
+ client.put_bucket_replication(Bucket=src, ReplicationConfiguration={"Role": _REPL_ROLE, "Rules": [rule]})
+
+
+def _purge(client, bucket):
+ lv = client.list_object_versions(Bucket=bucket)
+ for v in lv.get("Versions", []) + lv.get("DeleteMarkers", []):
+ client.delete_object(Bucket=bucket, Key=v["Key"], VersionId=v["VersionId"])
+ client.delete_bucket(Bucket=bucket)
+
+
+def crr_pair():
+ """A us-east-1 source and an eu-west-1 destination, both versioned."""
+ use1, src = _versioned_bucket("us-east-1", "src")
+ euw1, dst = _versioned_bucket("eu-west-1", "dst")
+ yield use1, src, euw1, dst
+ _purge(use1, src)
+ _purge(euw1, dst)
+
+
+def test_s3_replication_cross_region_replica_readable_in_destination(crr_pair):
+ use1, src, euw1, dst = crr_pair
+ _replicate(use1, src, dst, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Disabled"})
+ use1.put_object(Bucket=src, Key="a.txt", Body=b"across regions")
+ assert use1.head_object(Bucket=src, Key="a.txt")["ReplicationStatus"] == "COMPLETED"
+ replica = euw1.get_object(Bucket=dst, Key="a.txt")
+ assert replica["ReplicationStatus"] == "REPLICA"
+ assert replica["Body"].read() == b"across regions"
+
+
+def _delete_markers(client, bucket, key):
+ return [m for m in client.list_object_versions(Bucket=bucket).get("DeleteMarkers", []) if m["Key"] == key]
+
+
+def test_s3_delete_marker_replication_enabled_v2_rule(crr_pair):
+ use1, src, euw1, dst = crr_pair
+ _replicate(use1, src, dst, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Enabled"})
+ use1.put_object(Bucket=src, Key="gone.txt", Body=b"x")
+ use1.put_object(Bucket=src, Key="batch.txt", Body=b"y")
+ use1.delete_object(Bucket=src, Key="gone.txt")
+ use1.delete_objects(Bucket=src, Delete={"Objects": [{"Key": "batch.txt"}]})
+ for key in ("gone.txt", "batch.txt"):
+ assert len(_delete_markers(euw1, dst, key)) == 1
+ with pytest.raises(ClientError) as exc:
+ euw1.get_object(Bucket=dst, Key=key)
+ assert exc.value.response["Error"]["Code"] == "NoSuchKey"
+
+
+def test_s3_delete_marker_replication_v1_rule(crr_pair):
+ """A rule without Filter is V1, which replicates delete markers from user deletes."""
+ use1, src, euw1, dst = crr_pair
+ _replicate(use1, src, dst, Prefix="")
+ use1.put_object(Bucket=src, Key="v1.txt", Body=b"x")
+ use1.delete_object(Bucket=src, Key="v1.txt")
+ assert len(_delete_markers(euw1, dst, "v1.txt")) == 1
+
+
+def test_s3_delete_marker_replication_version_id_delete_stays_local(crr_pair):
+ use1, src, euw1, dst = crr_pair
+ _replicate(use1, src, dst, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Enabled"})
+ vid = use1.put_object(Bucket=src, Key="v.txt", Body=b"x")["VersionId"]
+ use1.delete_object(Bucket=src, Key="v.txt", VersionId=vid)
+ assert euw1.get_object(Bucket=dst, Key="v.txt")["Body"].read() == b"x"
+ assert _delete_markers(euw1, dst, "v.txt") == []
+
+
+ {"Filter": {"Prefix": ""}, "DeleteMarkerReplication": {"Status": "Disabled"}},
+ {"Filter": {"Tag": {"Key": "keep", "Value": "yes"}}, "DeleteMarkerReplication": {"Status": "Enabled"}},
+], ids=["disabled", "tag-filter"])
+def test_s3_delete_marker_replication_not_replicated(crr_pair, rule):
+ use1, src, euw1, dst = crr_pair
+ _replicate(use1, src, dst, **rule)
+ use1.put_object(Bucket=src, Key="k.txt", Body=b"x", Tagging="keep=yes")
+ assert euw1.get_object(Bucket=dst, Key="k.txt")["Body"].read() == b"x"
+ use1.delete_object(Bucket=src, Key="k.txt")
+ assert _delete_markers(euw1, dst, "k.txt") == []
+ assert euw1.get_object(Bucket=dst, Key="k.txt")["Body"].read() == b"x"
+
+
+def _replicated_keys(client, bucket):
+ return sorted(o["Key"] for o in client.list_objects_v2(Bucket=bucket).get("Contents", []))
+
+
+def test_s3_replication_tag_filter_single_tag(crr_pair):
+ use1, src, euw1, dst = crr_pair
+ _replicate(use1, src, dst, Filter={"Tag": {"Key": "replicate", "Value": "yes"}},
+ DeleteMarkerReplication={"Status": "Disabled"})
+ use1.put_object(Bucket=src, Key="tagged", Body=b"1", Tagging="replicate=yes&other=1")
+ use1.put_object(Bucket=src, Key="wrong-value", Body=b"2", Tagging="replicate=no")
+ use1.put_object(Bucket=src, Key="untagged", Body=b"3")
+ use1.copy_object(Bucket=src, Key="copy-replaced", CopySource={"Bucket": src, "Key": "untagged"},
+ TaggingDirective="REPLACE", Tagging="replicate=yes")
+ use1.copy_object(Bucket=src, Key="copy-kept", CopySource={"Bucket": src, "Key": "tagged"})
+ assert _replicated_keys(euw1, dst) == ["copy-kept", "copy-replaced", "tagged"]
+ assert "ReplicationStatus" not in use1.head_object(Bucket=src, Key="untagged")
+
+
+def test_s3_replication_tag_filter_and(crr_pair):
+ use1, src, euw1, dst = crr_pair
+ _replicate(use1, src, dst,
+ Filter={"And": {"Prefix": "logs/", "Tags": [{"Key": "a", "Value": "1"}, {"Key": "b", "Value": "2"}]}},
+ DeleteMarkerReplication={"Status": "Disabled"})
+ use1.put_object(Bucket=src, Key="logs/both", Body=b"x", Tagging="a=1&b=2")
+ use1.put_object(Bucket=src, Key="logs/one", Body=b"x", Tagging="a=1")
+ use1.put_object(Bucket=src, Key="data/both", Body=b"x", Tagging="a=1&b=2")
+ assert _replicated_keys(euw1, dst) == ["logs/both"]
+
+
+def test_s3_two_way_replication_has_no_loop():
+ use1, a = _versioned_bucket("us-east-1", "a")
+ euw1, b = _versioned_bucket("eu-west-1", "b")
+ try:
+ _replicate(use1, a, b, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Disabled"})
+ _replicate(euw1, b, a, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Disabled"})
+ use1.put_object(Bucket=a, Key="from-a", Body=b"a")
+ euw1.put_object(Bucket=b, Key="from-b", Body=b"b")
+ for client, bucket in ((use1, a), (euw1, b)):
+ versions = client.list_object_versions(Bucket=bucket)["Versions"]
+ assert sorted(v["Key"] for v in versions) == ["from-a", "from-b"]
+ assert euw1.head_object(Bucket=b, Key="from-a")["ReplicationStatus"] == "REPLICA"
+ assert use1.head_object(Bucket=a, Key="from-b")["ReplicationStatus"] == "REPLICA"
+ assert use1.head_object(Bucket=a, Key="from-a")["ReplicationStatus"] == "COMPLETED"
+ finally:
+ _purge(use1, a)
+ _purge(euw1, b)
+
+
+# ---------------------------------------------------------------------------
+# Multi-Region Access Points through S3 Control (#2158)
+# ---------------------------------------------------------------------------
+
+_ACCOUNT = "000000000000"
+
+
+def s3control_dns():
+ """boto3 prefixes S3 Control hosts with the account id."""
+ with patch_endpoint_dns():
+ yield
+
+
+def mrap_members():
+ """One bucket in us-east-1 and one in eu-west-1, each holding who.txt."""
+ tag = _uuid_mod.uuid4().hex[:8]
+ use1, use1_bucket = _versioned_bucket("us-east-1", f"mrap-{tag}-use1")
+ euw1, euw1_bucket = _versioned_bucket("eu-west-1", f"mrap-{tag}-euw1")
+ use1.put_object(Bucket=use1_bucket, Key="who.txt", Body=b"use1")
+ euw1.put_object(Bucket=euw1_bucket, Key="who.txt", Body=b"euw1")
+ yield use1, use1_bucket, euw1, euw1_bucket
+ for client, bucket in ((use1, use1_bucket), (euw1, euw1_bucket)):
+ try:
+ _purge(client, bucket)
+ except ClientError:
+ pass
+
+
+def _mrap_name():
+ return f"mrap-{_uuid_mod.uuid4().hex[:10]}"
+
+
+def test_s3_mrap_routes_default_for_records_persisted_before_routes():
+ from ministack.services import s3 as s3_svc
+
+ legacy = {"Name": "old", "Alias": "a.mrap", "Regions": ["b1", "b2"], "CreatedAt": "2026-01-01T00:00:00Z"}
+ assert s3_svc.mrap_routes(legacy) == {"b1": 100, "b2": 100}
+ assert s3_svc.mrap_routes({**legacy, "Routes": {"b1": 0}}) == {"b1": 0, "b2": 100}
+
+
+def _mrap_create(ctl, name, buckets):
+ token = ctl.create_multi_region_access_point(
+ AccountId=_ACCOUNT, ClientToken=_uuid_mod.uuid4().hex,
+ Details={"Name": name, "Regions": [{"Bucket": b} for b in buckets]})["RequestTokenARN"]
+ return ctl.describe_multi_region_access_point_operation(
+ AccountId=_ACCOUNT, RequestTokenARN=token)["AsyncOperation"]
+
+
+def _mrap_delete(ctl, name):
+ token = ctl.delete_multi_region_access_point(
+ AccountId=_ACCOUNT, ClientToken=_uuid_mod.uuid4().hex, Details={"Name": name})["RequestTokenARN"]
+ return ctl.describe_multi_region_access_point_operation(
+ AccountId=_ACCOUNT, RequestTokenARN=token)["AsyncOperation"]
+
+
+def test_s3_mrap_control_async_create_describe_delete(s3control_dns, mrap_members):
+ _, use1_bucket, _, euw1_bucket = mrap_members
+ ctl = _regional_client("s3control", "us-west-2")
+ name = _mrap_name()
+ op = _mrap_create(ctl, name, [use1_bucket, euw1_bucket])
+ assert re.fullmatch(rf"arn:aws:s3:us-west-2:{_ACCOUNT}:async-request/mrap/create/.+", op["RequestTokenARN"])
+ assert op["Operation"] == "CreateMultiRegionAccessPoint"
+ assert op["RequestStatus"] == "SUCCEEDED"
+ assert op["RequestParameters"]["CreateMultiRegionAccessPointRequest"]["Name"] == name
+ regions = op["ResponseDetails"]["MultiRegionAccessPointDetails"]["Regions"]
+ assert sorted(r["Name"] for r in regions) == ["eu-west-1", "us-east-1"]
+
+ again = _mrap_create(ctl, name, [use1_bucket, euw1_bucket])
+ assert again["RequestStatus"] == "FAILED"
+ assert again["ResponseDetails"]["ErrorDetails"]["Code"] == "MultiRegionAccessPointAlreadyOwnedByYou"
+ assert again["ResponseDetails"]["ErrorDetails"]["Message"] == (
+ "You must provide a unique name for each Multi-Region Access Point in your account. "
+ "A MRAP with this name already exists.")
+
+ deleted = _mrap_delete(ctl, name)
+ assert (deleted["Operation"], deleted["RequestStatus"]) == ("DeleteMultiRegionAccessPoint", "SUCCEEDED")
+ with pytest.raises(ClientError) as exc:
+ ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)
+ assert exc.value.response["Error"]["Code"] == "NoSuchMultiRegionAccessPoint"
+
+
+def test_s3_mrap_control_async_validation_failures(s3control_dns, mrap_members):
+ use1, use1_bucket, _, euw1_bucket = mrap_members
+ ctl = _regional_client("s3control", "us-west-2")
+ name = _mrap_name()
+ op = _mrap_create(ctl, name, [use1_bucket, f"missing-{use1_bucket}"])
+ assert op["RequestStatus"] == "FAILED"
+ err = op["ResponseDetails"]["ErrorDetails"]
+ assert (err["Code"], err["Message"], err["Resource"]) == (
+ "NoSuchBucket", "The specified bucket does not exist.", name)
+ assert op["ResponseDetails"]["MultiRegionAccessPointDetails"]["Regions"] == []
+
+ second_use1 = f"{use1_bucket}-2"
+ use1.create_bucket(Bucket=second_use1)
+ try:
+ op = _mrap_create(ctl, name, [use1_bucket, second_use1])
+ assert op["ResponseDetails"]["ErrorDetails"]["Code"] == "MultiRegionAccessPointSameBucketRegion"
+ assert op["ResponseDetails"]["ErrorDetails"]["Message"] == (
+ "The buckets specified must be part of different Regions.")
+ finally:
+ use1.delete_bucket(Bucket=second_use1)
+ with pytest.raises(ClientError):
+ ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)
+
+
+def test_s3_mrap_control_read_get_list_policy(s3control_dns, mrap_members):
+ use1, use1_bucket, _, euw1_bucket = mrap_members
+ ctl = _regional_client("s3control", "us-west-2")
+ names = [_mrap_name(), _mrap_name()]
+ for name in names:
+ assert _mrap_create(ctl, name, [use1_bucket, euw1_bucket])["RequestStatus"] == "SUCCEEDED"
+ try:
+ ap = ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=names[0])["AccessPoint"]
+ assert ap["Name"] == names[0]
+ assert re.fullmatch(r"[a-z][a-z0-9]{12}\.mrap", ap["Alias"])
+ assert ap["Status"] == "READY"
+ assert {(r["Bucket"], r["Region"], r["BucketAccountId"]) for r in ap["Regions"]} == {
+ (use1_bucket, "us-east-1", _ACCOUNT), (euw1_bucket, "eu-west-1", _ACCOUNT)}
+
+ listed, token = [], None
+ while True:
+ kwargs = {"AccountId": _ACCOUNT, "MaxResults": 1, **({"NextToken": token} if token else {})}
+ page = ctl.list_multi_region_access_points(**kwargs)
+ listed += [a["Name"] for a in page["AccessPoints"]]
+ token = page.get("NextToken")
+ if not token:
+ break
+ assert set(names) <= set(listed)
+
+ policy = json.dumps({"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{_ACCOUNT}:root"},
+ "Action": "s3:GetObject", "Resource": f"arn:aws:s3::{_ACCOUNT}:accesspoint/{ap['Alias']}/object/*"}]})
+ token = ctl.put_multi_region_access_point_policy(
+ AccountId=_ACCOUNT, ClientToken="p", Details={"Name": names[0], "Policy": policy})["RequestTokenARN"]
+ op = ctl.describe_multi_region_access_point_operation(AccountId=_ACCOUNT, RequestTokenARN=token)
+ assert op["AsyncOperation"]["RequestStatus"] == "SUCCEEDED"
+ doc = ctl.get_multi_region_access_point_policy(AccountId=_ACCOUNT, Name=names[0])["Policy"]
+ assert doc["Established"]["Policy"] == policy
+ assert doc["Proposed"]["Policy"] == policy
+
+ with pytest.raises(ClientError) as exc:
+ use1.delete_bucket(Bucket=use1_bucket)
+ assert exc.value.response["Error"]["Code"] == "BucketHasAccessPointsAttached"
+ assert exc.value.response["Error"]["Message"] == "Bucket has access points attached and cannot be deleted."
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ finally:
+ for name in names:
+ _mrap_delete(ctl, name)
+
+ with pytest.raises(ClientError) as exc:
+ ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=names[0])
+ err = exc.value.response["Error"]
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert err["Message"] == "The specified Multi-Region Access Point does not exist."
+ assert (err["MultiRegionAccessPointName"], err["AccountId"]) == (names[0], _ACCOUNT)
+
+
+def test_s3_mrap_control_read_routes(s3control_dns, mrap_members):
+ _, use1_bucket, _, euw1_bucket = mrap_members
+ ctl, routes_ctl = _regional_client("s3control", "us-west-2"), _regional_client("s3control", "eu-west-1")
+ name = _mrap_name()
+ _mrap_create(ctl, name, [use1_bucket, euw1_bucket])
+ try:
+ alias = ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)["AccessPoint"]["Alias"]
+ arn = f"arn:aws:s3::{_ACCOUNT}:accesspoint/{alias}"
+ routes = routes_ctl.get_multi_region_access_point_routes(AccountId=_ACCOUNT, Mrap=arn)
+ assert routes["Mrap"] == arn
+ assert {(r["Bucket"], r["Region"], r["TrafficDialPercentage"]) for r in routes["Routes"]} == {
+ (use1_bucket, "us-east-1", 100), (euw1_bucket, "eu-west-1", 100)}
+
+ def submit_error(updates, mrap=arn):
+ with pytest.raises(ClientError) as exc:
+ routes_ctl.submit_multi_region_access_point_routes(AccountId=_ACCOUNT, Mrap=mrap, RouteUpdates=updates)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ return exc.value.response["Error"]
+
+ assert submit_error([{"Bucket": use1_bucket, "TrafficDialPercentage": 50}]) == {
+ "Code": "InvalidRequest", "Message": "Request invalid"}
+ assert submit_error([{"Bucket": f"x-{use1_bucket}", "TrafficDialPercentage": 0}])["Message"] == (
+ "The provided Region or bucket is not part of the Multi-Region Access Point.")
+ assert submit_error([{"Bucket": use1_bucket, "TrafficDialPercentage": 0},
+ {"Bucket": euw1_bucket, "TrafficDialPercentage": 0}])["Message"] == (
+ "At least one Region or bucket in the Multi-Region Access Point must be configured to receive "
+ "traffic. Set at least one Region or bucket to Active, and then try again.")
+ assert submit_error([{"Bucket": use1_bucket, "TrafficDialPercentage": 0}], mrap=name)["Message"] == (
+ "Request invalid")
+
+ routes_ctl.submit_multi_region_access_point_routes(
+ AccountId=_ACCOUNT, Mrap=arn, RouteUpdates=[{"Bucket": use1_bucket, "TrafficDialPercentage": 0}])
+ dials = {r["Bucket"]: r["TrafficDialPercentage"]
+ for r in routes_ctl.get_multi_region_access_point_routes(AccountId=_ACCOUNT, Mrap=arn)["Routes"]}
+ assert dials == {use1_bucket: 0, euw1_bucket: 100}
+ finally:
+ _mrap_delete(ctl, name)
+
+
+def test_s3_mrap_control_region_rules(s3control_dns, mrap_members):
+ """Management operations are served only from us-west-2 and route
+ operations from five regions; anything else is redirected (observed)."""
+ _, use1_bucket, _, euw1_bucket = mrap_members
+ with pytest.raises(ClientError) as exc:
+ _mrap_create(_regional_client("s3control", "us-east-1"), _mrap_name(), [use1_bucket, euw1_bucket])
+ err = exc.value.response["Error"]
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 301
+ assert err["Code"] == "PermanentRedirect"
+ assert err["Message"] == ("This API operation is only available in the following Regions: us-west-2. "
+ "Make sure to send all future requests to a supported Region.")
+ assert err["Endpoint"] == "https://s3-control.us-west-2.amazonaws.com/v20180820/async-requests/mrap/create"
+
+ ctl = _regional_client("s3control", "us-west-2")
+ name = _mrap_name()
+ _mrap_create(ctl, name, [use1_bucket, euw1_bucket])
+ try:
+ alias = ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)["AccessPoint"]["Alias"]
+ arn = f"arn:aws:s3::{_ACCOUNT}:accesspoint/{alias}"
+ with pytest.raises(ClientError) as exc:
+ _regional_client("s3control", "eu-central-1").submit_multi_region_access_point_routes(
+ AccountId=_ACCOUNT, Mrap=arn, RouteUpdates=[{"Bucket": use1_bucket, "TrafficDialPercentage": 0}])
+ assert exc.value.response["Error"]["Message"] == (
+ "This API operation is only available in the following Regions: us-west-2, ap-southeast-2, "
+ "ap-northeast-1, eu-west-1 and us-east-1. Make sure to send all future requests to a supported Region.")
+ for region in ("us-east-1", "us-west-2", "eu-west-1", "ap-northeast-1", "ap-southeast-2"):
+ _regional_client("s3control", region).get_multi_region_access_point_routes(AccountId=_ACCOUNT, Mrap=arn)
+ finally:
+ _mrap_delete(ctl, name)
+
+
+def test_s3_mrap_control_account_check_only_under_auth(monkeypatch):
+ """x-amz-account-id must name the caller's account; that is an authorization check, so AUTH=true only."""
+ import asyncio
+
+ import ministack.app as app_mod
+ from ministack.services import s3 as s3_svc
+
+ headers = {"x-amz-account-id": "111122223333"}
+ status, _, body = s3_svc.s3control_account_error(headers)
+ assert status == 403 and b"<Code>AccessDenied</Code>" in body
+ monkeypatch.setattr(app_mod, "AUTH", False)
+ status, _, _ = asyncio.run(app_mod._handle_s3_control_request(
+ "/v20180820/mrap/instances", "GET", b"", {}, "rid", headers))
+ assert status == 200
+
+
+def _mrap_request(alias, method, key, body=b""):
+ import http.client
+
+ parsed = urlparse(ENDPOINT)
+ conn = http.client.HTTPConnection(parsed.hostname, parsed.port or 80, timeout=30)
+ conn.request(method, f"/{key}", body=body or None,
+ headers={"Host": f"{alias}.accesspoint.s3-global.amazonaws.com"})
+ resp = conn.getresponse()
+ data = resp.read()
+ conn.close()
+ return resp.status, data
+
+
+def test_s3_mrap_end_to_end_routing_failover_and_replication(s3control_dns, mrap_members):
+ use1, use1_bucket, euw1, euw1_bucket = mrap_members
+ _replicate(use1, use1_bucket, euw1_bucket, Filter={"Prefix": "data/"},
+ DeleteMarkerReplication={"Status": "Disabled"})
+ _replicate(euw1, euw1_bucket, use1_bucket, Filter={"Prefix": "data/"},
+ DeleteMarkerReplication={"Status": "Disabled"})
+ ctl, routes_ctl = _regional_client("s3control", "us-west-2"), _regional_client("s3control", "eu-west-1")
+ name = _mrap_name()
+ # Listed eu-west-1 first: the us-east-1 member wins on region, not position.
+ _mrap_create(ctl, name, [euw1_bucket, use1_bucket])
+ alias = ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)["AccessPoint"]["Alias"]
+ arn = f"arn:aws:s3::{_ACCOUNT}:accesspoint/{alias}"
+ try:
+ for region in ("us-east-1", "eu-west-1", None):
+ assert _mrap_get(alias, "who.txt", region=region) == (200, "use1")
+
+ routes_ctl.submit_multi_region_access_point_routes(
+ AccountId=_ACCOUNT, Mrap=arn, RouteUpdates=[{"Bucket": use1_bucket, "TrafficDialPercentage": 0}])
+ assert _mrap_get(alias, "who.txt") == (200, "euw1")
+ with pytest.raises(ClientError):
+ routes_ctl.submit_multi_region_access_point_routes(
+ AccountId=_ACCOUNT, Mrap=arn, RouteUpdates=[{"Bucket": euw1_bucket, "TrafficDialPercentage": 0}])
+ assert _mrap_get(alias, "who.txt") == (200, "euw1")
+
+ assert _mrap_request(alias, "PUT", "data/new.txt", b"through mrap")[0] == 200
+ assert euw1.get_object(Bucket=euw1_bucket, Key="data/new.txt")["ReplicationStatus"] == "COMPLETED"
+ assert use1.get_object(Bucket=use1_bucket, Key="data/new.txt")["Body"].read() == b"through mrap"
+ finally:
+ _mrap_delete(ctl, name)
+ assert _mrap_request(alias, "GET", "who.txt")[0] in (403, 404)
+
+
+# IAM contracts, run by CI with AUTH=false and AUTH=true.
@pytest.fixture
def auth_s3_objects(s3):
"""Two private buckets with one source object; isolate and clean every test."""
diff --git a/tests/test_sns.py b/tests/test_sns.py
index 49e42853..4836e1fc 100644
--- a/tests/test_sns.py
+++ b/tests/test_sns.py
@@ -79,14 +79,9 @@ def test_sns_topics_are_region_scoped_by_name(sns):
assert west_arn in west_arns
assert east_arn not in west_arns
- # Real AWS evaluates authorization before existence on
- # GetTopicAttributes: a topic arn that does not exist in this region
- # answers InvalidClientTokenId/403, not NotFound/404 (real-AWS
- # capture).
with pytest.raises(ClientError) as exc:
sns.get_topic_attributes(TopicArn=west_arn)
- assert exc.value.response["Error"]["Code"] == "InvalidClientTokenId"
- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
+ assert exc.value.response["Error"]["Code"] == "NotFound"
def test_sns_set_topic_attributes(sns):
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index e3c0d65b..42ddf46f 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -105,13 +105,9 @@ def test_sfn_state_machines_are_region_scoped():
assert west_sm["stateMachineArn"] in west_arns
assert west_sm["stateMachineArn"] not in east_arns
- # Real AWS evaluates authorization before existence on
- # DescribeStateMachine: an arn that does not exist in this region
- # answers AccessDeniedException, not StateMachineDoesNotExist
- # (real-AWS capture).
with pytest.raises(ClientError) as exc:
west.describe_state_machine(stateMachineArn=east_sm["stateMachineArn"])
- assert exc.value.response["Error"]["Code"] == "AccessDeniedException"
+ assert exc.value.response["Error"]["Code"] == "StateMachineDoesNotExist"
def test_sfn_executions_are_region_scoped():
@@ -5528,15 +5524,13 @@ def test_sfn_create_idempotency_covers_version_description(sfn):
def test_sfn_describe_not_found(sfn):
- """DescribeStateMachine on a non-existent ARN: real AWS evaluates
- authorization before existence and answers AccessDeniedException
- (real-AWS capture), not StateMachineDoesNotExist."""
+ """DescribeStateMachine on non-existent ARN should fail."""
with pytest.raises(ClientError) as exc:
sfn.describe_state_machine(stateMachineArn="arn:aws:states:us-east-1:000000000000:stateMachine:nonexistent-99")
err = exc.value.response["Error"]["Code"]
- assert err == "AccessDeniedException"
+ assert "StateMachineDoesNotExist" in err or "NotFound" in err or "ResourceNotFound" in err
# Real AWS sends `x-amzn-errortype` on JSON-protocol errors; Java/Go SDK v2 read it.
- assert exc.value.response["ResponseMetadata"]["HTTPHeaders"].get("x-amzn-errortype") == "AccessDeniedException"
+ assert exc.value.response["ResponseMetadata"]["HTTPHeaders"].get("x-amzn-errortype") == "StateMachineDoesNotExist"
def test_sfn_start_execution_not_found(sfn):
"""StartExecution on non-existent SM should fail."""
diff --git a/tests/test_waf.py b/tests/test_waf.py
index 60a5c2f1..134cd1b6 100644
--- a/tests/test_waf.py
+++ b/tests/test_waf.py
@@ -347,6 +347,8 @@ def test_waf_regex_pattern_set_crud(wafv2):
assert summary["Name"] == "test-regex"
assert summary["Description"] == "first"
assert ":regional/regexpatternset/test-regex/" in summary["ARN"]
+ with pytest.raises(wafv2.exceptions.WAFDuplicateItemException):
+ wafv2.create_regex_pattern_set(Name="test-regex", Scope="REGIONAL", RegularExpressionList=[])
get_resp = wafv2.get_regex_pattern_set(Name="test-regex", Scope="REGIONAL", Id=uid)
assert get_resp["RegexPatternSet"]["RegularExpressionList"] == [{"RegexString": "^/admin"}]
diff --git a/tests/test_wire_envelopes.py b/tests/test_wire_envelopes.py
deleted file mode 100644
index 058be9e9..00000000
--- a/tests/test_wire_envelopes.py
+++ /dev/null
@@ -1,285 +0,0 @@
-"""Wire-fidelity assertions on response envelopes (issue #2128).
-
-Expected values are real AWS observations, not model guesses:
-
-- Error envelope shape comes from a 17-region capture sweep: the query
- family (sns/iam/sts/rds/elbv2/cloudformation/...) carries ``<Type>``
- inside ``<Error>`` and no ``<?xml?>`` declaration; ec2 carries the
- declaration, no ``<Type>``, and ``text/xml;charset=UTF-8``; rest-xml
- carries both the declaration and ``<Type>``.
-- Success Content-Types were verified across
- us-east-1/us-west-2/eu-west-1/ap-southeast-2: query -> ``text/xml``,
- ec2 -> ``text/xml;charset=UTF-8``, json -> ``application/x-amz-json-
- 1.{jsonVersion}``, rest-json -> ``application/json``, rest-xml ->
- ``application/xml`` (s3) or ``text/xml`` (route53).
-
-These tests run the enduser surface: boto3 clients against the live
-server, asserting exactly what an SDK caller parses back.
-"""
-
-import os
-import urllib.error
-import urllib.request
-
-import pytest
-from botocore.exceptions import ClientError
-
-ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
-
-
-def _ct(resp):
- """Response Content-Type as botocore exposes it (HTTPHeaderDict is
- case-insensitive)."""
- return resp["ResponseMetadata"]["HTTPHeaders"]["content-type"]
-
-
-def _status(err):
- return err["ResponseMetadata"]["HTTPStatusCode"]
-
-
-# ---------------------------------------------------------------------------
-# Query-protocol error envelopes: <Type> inside <Error>, text/xml
-# ---------------------------------------------------------------------------
-
-
-def test_iam_query_error_envelope(iam):
- with pytest.raises(ClientError) as exc:
- iam.get_user(UserName="wire-missing-user")
- err = exc.value.response
- assert err["Error"]["Code"] == "NoSuchEntity"
- assert err["Error"]["Type"] == "Sender"
- assert _status(err) == 404
- assert _ct(err) == "text/xml"
-
-
-def test_sns_query_error_envelope(sns):
- # set_topic_attributes was not part of the captured auth-ordering
- # change, so it keeps its NotFound/404 on a missing topic — but the
- # envelope still carries the query family's <Type>Sender</Type>.
- with pytest.raises(ClientError) as exc:
- sns.set_topic_attributes(
- TopicArn="arn:aws:sns:us-east-1:000000000000:wire-missing",
- AttributeName="DisplayName",
- AttributeValue="x",
- )
- err = exc.value.response
- assert err["Error"]["Code"] == "NotFound"
- assert err["Error"]["Type"] == "Sender"
- assert _ct(err) == "text/xml"
-
-
-def test_elbv2_query_error_envelope(elbv2):
- with pytest.raises(ClientError) as exc:
- elbv2.describe_load_balancers(Names=["wire-missing"])
- err = exc.value.response
- assert err["Error"]["Code"] == "LoadBalancerNotFound"
- assert err["Error"]["Type"] == "Sender"
- assert _ct(err) == "text/xml"
-
-
-def test_autoscaling_query_error_envelope(autoscaling):
- with pytest.raises(ClientError) as exc:
- autoscaling.update_auto_scaling_group(
- AutoScalingGroupName="wire-missing")
- err = exc.value.response
- assert err["Error"]["Code"] == "ValidationError"
- assert err["Error"]["Type"] == "Sender"
- assert _ct(err) == "text/xml"
-
-
-def test_elasticache_query_error_envelope(ec):
- with pytest.raises(ClientError) as exc:
- ec.describe_cache_clusters(CacheClusterId="wire-missing")
- err = exc.value.response
- assert err["Error"]["Code"] == "CacheClusterNotFound"
- assert err["Error"]["Type"] == "Sender"
- assert _ct(err) == "text/xml"
-
-
-def test_rds_query_error_envelope(rds):
- with pytest.raises(ClientError) as exc:
- rds.describe_db_instances(DBInstanceIdentifier="wire-missing")
- err = exc.value.response
- assert err["Error"]["Code"] == "DBInstanceNotFound"
- assert err["Error"]["Type"] == "Sender"
- assert _status(err) == 404
- assert _ct(err) == "text/xml"
-
-
-def test_docdb_query_error_envelope(docdb):
- with pytest.raises(ClientError) as exc:
- docdb.describe_db_instances(DBInstanceIdentifier="wire-missing")
- err = exc.value.response
- assert err["Error"]["Type"] == "Sender"
- assert _ct(err) == "text/xml"
-
-
-def test_cloudwatch_query_error_envelope():
- # boto3 1.42+ speaks smithy-rpc-v2-cbor to CloudWatch, so the legacy
- # Query API path is exercised with a raw form-encoded request — the
- # shape an XML-mode client still parses.
- req = urllib.request.Request(
- f"{ENDPOINT}/",
- data=b"Action=GetDashboard&Version=2010-08-01&DashboardName=wire-missing",
- headers={
- "Content-Type": "application/x-www-form-urlencoded",
- "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/"
- "us-east-1/monitoring/aws4_request, "
- "SignedHeaders=host, Signature=x",
- },
- )
- with pytest.raises(urllib.error.HTTPError) as exc:
- urllib.request.urlopen(req)
- http_err = exc.value
- body = http_err.read().decode()
- assert http_err.headers["content-type"] == "text/xml"
- # Query family: <Type> inside <Error>, no <?xml?> declaration.
- assert not body.startswith("<?xml")
- assert "<Type>Sender</Type>" in body
- assert "ResourceNotFound" in body
-
-
-def test_ses_query_error_envelope(ses):
- with pytest.raises(ClientError) as exc:
- ses.describe_receipt_rule_set(RuleSetName="wire-missing")
- err = exc.value.response
- assert err["Error"]["Code"] == "RuleSetDoesNotExist"
- assert err["Error"]["Type"] == "Sender"
- assert _ct(err) == "text/xml"
-
-
-def test_cfn_query_error_envelope(cfn):
- with pytest.raises(ClientError) as exc:
- cfn.describe_stacks(StackName="wire-missing")
- err = exc.value.response
- assert err["Error"]["Code"] == "ValidationError"
- assert err["Error"]["Type"] == "Sender"
- assert _ct(err) == "text/xml"
-
-
-# ---------------------------------------------------------------------------
-# Non-query envelopes: ec2 keeps its shape, rest-xml keeps <Type>
-# ---------------------------------------------------------------------------
-
-
-def test_ec2_error_envelope_has_no_type_and_charset(ec2):
- with pytest.raises(ClientError) as exc:
- ec2.describe_instances(InstanceIds=["i-0123456789abcdef0"])
- err = exc.value.response
- assert err["Error"]["Code"] == "InvalidInstanceID.NotFound"
- # ec2 errors carry no <Type> on the real wire (0/17 captures).
- assert err["Error"].get("Type") is None
- assert _ct(err) == "text/xml;charset=UTF-8"
-
-
-def test_route53_restxml_error_envelope(r53):
- with pytest.raises(ClientError) as exc:
- r53.get_hosted_zone(Id="/hostedzone/ZWIREMISSING000")
- err = exc.value.response
- assert err["Error"]["Type"] == "Sender"
- assert _ct(err) == "text/xml"
-
-
-# ---------------------------------------------------------------------------
-# Success Content-Types per protocol family
-# ---------------------------------------------------------------------------
-
-
-def test_query_success_content_types(iam, sns, sts, ec, autoscaling,
- elbv2, ses, rds, docdb, cfn):
- calls = [
- (iam.list_users, {}),
- (sns.list_topics, {}),
- (sts.get_caller_identity, {}),
- (ec.describe_cache_clusters, {}),
- (autoscaling.describe_auto_scaling_groups, {}),
- (elbv2.describe_load_balancers, {}),
- (ses.list_identities, {}),
- (rds.describe_db_instances, {}),
- (docdb.describe_db_instances, {}),
- (cfn.list_stacks, {}),
- ]
- for call, kwargs in calls:
- assert _ct(call(**kwargs)) == "text/xml", call.__name__
-
-
-def test_cloudwatch_query_success_content_type():
- # Raw Query API request — see test_cloudwatch_query_error_envelope.
- req = urllib.request.Request(
- f"{ENDPOINT}/",
- data=b"Action=ListMetrics&Version=2010-08-01",
- headers={
- "Content-Type": "application/x-www-form-urlencoded",
- "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/"
- "us-east-1/monitoring/aws4_request, "
- "SignedHeaders=host, Signature=x",
- },
- )
- with urllib.request.urlopen(req) as resp:
- assert resp.headers["content-type"] == "text/xml"
-
-
-def test_json_success_content_types(ddb, sqs, kin):
- # jsonVersion comes from the botocore service model (dynamodb/sqs are
- # 1.0, kinesis is 1.1) — matching what real AWS puts on the wire.
- assert _ct(ddb.list_tables()) == "application/x-amz-json-1.0"
- assert _ct(sqs.list_queues()) == "application/x-amz-json-1.0"
- assert _ct(kin.list_streams()) == "application/x-amz-json-1.1"
-
-
-def test_restxml_success_content_types(s3, r53):
- assert _ct(s3.list_buckets()) == "application/xml"
- assert _ct(r53.list_hosted_zones()) == "text/xml"
-
-
-def test_restjson_success_content_type(lam):
- assert _ct(lam.list_functions()) == "application/json"
-
-
-def test_ec2_success_content_type(ec2):
- assert _ct(ec2.describe_regions()) == "text/xml;charset=UTF-8"
-
-
-def test_s3_object_payload_content_type_not_rewritten(s3):
- # A stored object's Content-Type is payload, not an envelope — the
- # success fixer must not rewrite text/xml into the s3 envelope value.
- bucket = "wire-ct-payload"
- s3.create_bucket(Bucket=bucket)
- try:
- s3.put_object(Bucket=bucket, Key="doc.xml", Body=b"<a/>",
- ContentType="text/xml")
- resp = s3.get_object(Bucket=bucket, Key="doc.xml")
- assert _ct(resp) == "text/xml"
- finally:
- s3.delete_object(Bucket=bucket, Key="doc.xml")
- s3.delete_bucket(Bucket=bucket)
-
-
-# ---------------------------------------------------------------------------
-# Per-service error-code ordering (real AWS captures)
-# ---------------------------------------------------------------------------
-
-
-def test_sfn_describe_state_machine_authz_before_existence(sfn):
- # Real AWS evaluates authorization before existence: a nonexistent
- # arn answers AccessDeniedException, not StateMachineDoesNotExist.
- with pytest.raises(ClientError) as exc:
- sfn.describe_state_machine(
- stateMachineArn="arn:aws:states:us-east-1:000000000000:"
- "stateMachine:wire-missing")
- err = exc.value.response
- assert err["Error"]["Code"] == "AccessDeniedException"
- assert _status(err) == 400
-
-
-def test_sns_get_topic_attributes_auth_before_existence(sns):
- # Real AWS answers InvalidClientTokenId 403 on a nonexistent topic —
- # auth is evaluated before existence (real-AWS capture).
- with pytest.raises(ClientError) as exc:
- sns.get_topic_attributes(
- TopicArn="arn:aws:sns:us-east-1:000000000000:wire-missing")
- err = exc.value.response
- assert err["Error"]["Code"] == "InvalidClientTokenId"
- assert err["Error"]["Type"] == "Sender"
- assert _status(err) == 403
- assert _ct(err) == "text/xml"