Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
prerelease v1.5.30 (#2297)
Nahuel Nucera796a433076a1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9f62016e..e6946831 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,8 +7,28 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]-### Fixed-- **S3 upload errors under `AUTH=true`** — ordinary header-signed `PutObject` requests now check invalid bucket names, regional endpoint routing and signing regions before credentials, and missing buckets after authentication, matching observed AWS error precedence. The six upload errors include AWS's fixed messages, XML detail fields and matching request identifiers. Pre-authentication regional endpoint checks use `s3.<region>.<host>` hosts. Reserved root credentials and `AUTH=false` keep their existing authentication behavior; bucket home-region checks still apply.+### Added+- **Auth — more calls are authorized under `AUTH=true`** — RDS Data calls are authorized as `rds-data:<operation>` on the cluster its `resourceArn` names, S3 Control `ListTagsForResource`, `TagResource` and `UntagResource` as `s3:<operation>` on the bucket, and SES v2 calls as `ses:<operation>` on the resource the path or create body names (`*` otherwise), each with AWS's 403 denial (`AccessDeniedException`, S3 Control `AccessDenied`) naming the action and resource. S3 bucket and identity policies now see `s3:x-amz-server-side-encryption` (a part and the completion take their `CreateMultipartUpload`'s), `s3:x-amz-acl`, `s3:x-amz-grant-*` and, on `GetObject` and `HeadObject`, `s3:ExistingObjectTag/<key>`. S3 Tables and Glue Iceberg REST calls at `/iceberg` are authorized for the catalog that serves them, whatever service they are signed for: on a table bucket as the `s3tables` actions AWS lists for the operation (`loadTable` needs `GetTableMetadataLocation`, then `GetTableData`) on the bucket or table (`table/*` for one that does not exist), on the Glue catalog as the route's `glue` action on the catalog, then the database, then the table, and `transactions/commit` as `updateTable` on each table it changes; a denial answers 403 in the Iceberg error shape naming the action and resource ("Access Denied" for a later S3 Tables action, no body for `HEAD`), a `{prefix}` that is neither a table bucket ARN nor `<account>:s3tablescatalog/<bucket>` answers 400 `bad_request`, and a call that names a key is served from its own region only. Contributed by @iot-rocket.+- **IoT — MQTT over WebSocket follows the signer's IAM policies under `AUTH=true`** — a session signed with an IAM user or STS key could connect under any client id and publish, subscribe and receive anywhere; its CONNECT, will, PUBLISH, SUBSCRIBE and deliveries now need `iot:Connect`, `iot:Publish` (and `iot:RetainPublish`), `iot:Subscribe` and `iot:Receive` on the client, topic and topic filter ARNs, with a certificate session's refusals. The handshake (and an `AWS_IAM` WebSocket `$connect`) has its signature, date and session token verified: IoT answers 403 `Forbidden` and expects the token after the signed part of the URL, API Gateway names the canonical string it expected, and the session runs in the signer's account. Contributed by @iot-rocket.+- **Cognito — user pool feature plans** — `CreateUserPool`, `UpdateUserPool` and `AWS::Cognito::UserPool` ignored `UserPoolTier`; a pool now stores and describes its tier (`ESSENTIALS` by default, `PLUS` when created with threat protection on), keeps it when an update omits it, and refuses threat protection on `ESSENTIALS` and password history on `LITE` with `FeatureUnavailableInTierException` or, on a tier change, `TierChangeNotAllowedException`. Contributed by @iot-rocket.++### Fixed+- **Auth — unverifiable credentials under `AUTH=true`** — a request naming an IAM user's key in a SigV2 header, another SigV4 algorithm (`AWS4-HMAC-SHA512`), a header without `Credential=` or a query `X-Amz-Credential` the signature does not cover was served as that user; it now answers `IncompleteSignature` (S3: `InvalidRequest`), and SigV2 header and presigned signatures are verified. A request that maps to no IAM action (SES v2, RDS Data, S3 Control, X-Ray) is authenticated and answers the service's credential error (`InvalidSignatureException` 403 from SES v2 and RDS Data, `SignatureDoesNotMatch` 403 from S3 Control), and an SES v2 call selected by `X-Amz-Target` on a path without `/v2/email` is authorized as the operation it performs. A SigV4 header or presigned query that names no access key ran as the account root; it now answers `IncompleteSignature` naming every missing part (Lambda: `MissingAuthenticationTokenException` for a part left out), and an empty key the unknown-key error. Contributed by @iot-rocket.+- **API Gateway — credentials under `AUTH=true`** — a REST method with `NONE` or `COGNITO_USER_POOLS` authorization, or an HTTP API route without authorization, refused a signed caller its policies or signature failed; such a call now reaches the method and its own authorizer whatever it is signed with, and a REST API policy judges a `NONE` method's caller as anonymous (`ACCESS_DENIED` unless the policy allows everyone). A correctly presigned call (`X-Amz-Signature`) to an `AWS_IAM` method is served instead of 403 `MissingAuthenticationTokenException`. `CreateRestApi`, `GetRestApi`, `GetRestApis` and `UpdateRestApi` now return `apiStatus` `AVAILABLE` and `rootResourceId`, which Terraform AWS provider 6.x waits on. Contributed by @iot-rocket. Reported by @kharabasz.+- **AppSync — GraphQL authorization** — under `AUTH=true` a GraphQL call was authorized as `appsync:UpdateGraphqlApi` whatever the API's authentication type, and an `AWS_IAM` API served any `AWS4-HMAC-SHA256` header. On `/v1/apis/{apiId}/graphql` and on the API's own host an API key request now ignores its signature, and an `AWS_IAM` API needs a verified signature and authorizes `appsync:GraphQL` per top-level field (401 `Permission denied` when none is allowed, a field error per denied field, 400 `BadRequestException` for a wrong signature). Contributed by @iot-rocket.+- **AppSync — data-plane errors** — Event API `POST /event` refusals answered `{"__type", "message"}`, and GraphQL answered 500 for a body that is not a JSON object or a non-string `query` or non-object `variables`, a message-only 400 for a missing query and 200 for an unparseable one; both now answer AWS's `{"errors": [{"errorType", "message"}]}` envelope and `x-amzn-ErrorType` (`SerializationException`, `MalformedHttpRequestException`, `ResourceNotFoundException` for an unknown API or key, `UnknownOperationException` for another path on an Event API host), and publish answers `application/json`. Contributed by @iot-rocket.+- **Cognito — tokens under `AUTH=true`** — `/oauth2/userInfo` returned the user's attributes for any JWT with a user's `sub`; it now refuses an ID token, an altered, revoked or expired token, a disabled or deleted user and a token without the `openid` scope with 401 `invalid_token`, AWS's `error_description` and a `WWW-Authenticate` realm of the pool's issuer. `AdminDisableUser` revokes the user's tokens (`User is disabled.`, then `Access Token has been revoked` / `Refresh Token has been revoked` and `invalid_grant` after `AdminEnableUser`), a deleted user's access token gets `UserNotFoundException: User does not exist.`, and refresh tokens are signature-checked and refused for a disabled user or a deleted user's successor. Contributed by @iot-rocket.+- **Cognito — identity `Logins` and OAuth scopes** — under `AUTH=true` `GetId`, `GetCredentialsForIdentity` and `GetOpenIdToken` took any token in `Logins`; they now refuse an unsupported provider, a token that is no ID token of a trusted client, a bad signature, one expired over five minutes or another user's login with `NotAuthorizedException` (`Access to Identity '<id>' is forbidden.` without `Logins`), `GetId` returns the identity that holds the login, and the first login is linked. A call on an identity without a login answers for the identity that holds its login, an identity with a login takes the logins of the identities holding the others, and a merged-away identity is listed with `["DISABLED", "<region>"]` (`ListIdentities` `HideDisabled` leaves it out). `/oauth2/authorize` with an `identity_provider` redirects with `error_description=invalid_scope` for a scope outside `AllowedOAuthScopes`, and `client_credentials` ignores undefined scopes once a defined one is requested (`api/read bogus/x` gets `api/read`). Contributed by @iot-rocket.+- **IoT — reserved MQTT topics** — a client could subscribe to any `$` filter and publish to the replies AWS IoT writes (fleet provisioning, Jobs, Device Defender, file delivery, Device Location, commands); the broker now refuses them before the policy check (SUBACK 0x8F, PUBACK 0x90 or DISCONNECT 0x90 at QoS 0, a closed connection on 3.1.1), judges a `$share/<name>/<filter>` subscription by its filter, and HTTPS `Publish` answers `Topic can't start with $` for fleet provisioning and Device Location replies. Contributed by @iot-rocket.+- **IoT — Jobs** — a stale `expectedVersion` answered 409 and now answers 400 `InvalidRequestException` (`VersionMismatch` over MQTT); a status a device may not set is refused first with `InvalidStateTransitionException`; a `statusDetails` that is not a string map answers 400 instead of 500, an execution has none until a device reports some, and an empty map replaces it; MQTT `get` and `update` answer `ResourceNotFound` for another `executionNumber`; describe and list calls time out expired executions; documents that are not JSON or nest over 1000 levels are refused; and Jobs MQTT messages are compact UTF-8 in AWS's member order, `clientToken` first, characters outside the BMP escaped, `"jobDocument":null` kept. Contributed by @iot-rocket.+- **IoT — shadows, topic rules, sessions and authorization** — `NaN` and `Infinity` in job documents and shadows are refused (`Payload contains invalid json`), and a number beyond a double is stored as `"Infinity"`; unknown topic rules answer 401 `UnauthorizedException` (`Access to topic rule '<name>' was denied`) and bad names, including a trailing newline, AWS's validation message; unacknowledged QoS 1 messages survive a persistent session reconnect without reusing an in-flight packet id. Under `AUTH=true` the data plane answers 403 `ForbiddenException`, `aws:ResourceTag` conditions read the resource's tags, tagging calls are checked on the `resourceArn`, and denials name the resource. Contributed by @iot-rocket.+- **S3 — ACLs and Block Public Access** — `x-amz-grant-*` headers were refused with `MissingSecurityHeader` or dropped; on buckets with ACLs enabled `PutBucketAcl`, `PutObjectAcl`, `CreateBucket`, `PutObject` and `CopyObject` now set exactly the named grants and refuse what S3 refuses, and a `BucketOwnerEnforced` bucket answers 400 `AccessControlListNotSupported`. `BlockPublicAcls` refuses setting a public ACL (403 `AccessDenied`), `IgnorePublicAcls` drops public grants, `RestrictPublicBuckets` the policy, `BlockPublicPolicy` refuses a public bucket policy, and a bucket ACL grants only what its permission covers. Contributed by @iot-rocket.+- **S3 — copy and policy checks under `AUTH=true`** — a copy source in another account's bucket is checked for read access, `x-amz-*` headers sent in the query string are checked like headers, bucket policies for anonymous and cross-account callers use the request's own action and condition keys, and `s3:ExistingObjectTag` resolves through an access point alias. A header-signed `PutObject` checks the bucket name, regional endpoint and signing region before credentials and a missing bucket after them, answering `InvalidBucketName`, `PermanentRedirect`, `AuthorizationHeaderMalformed`, `InvalidAccessKeyId`, `SignatureDoesNotMatch` or `NoSuchBucket` with S3's XML fields. Contributed by @iot-rocket and @gakuto-cw21.+- **S3 — bucket configuration validation** — out-of-enum values in `PutBucketVersioning`, `PutBucketLifecycleConfiguration` and `PutBucketEncryption` now answer 400 `MalformedXML` (`The XML you provided was not well-formed or did not validate against our published schema`), and a non-positive `Days` or `NoncurrentDays` 400 `InvalidArgument` (`'Days' for Expiration action must be a positive integer`).+- **CloudWatch — composite alarms follow their rule** — a composite alarm stayed in `INSUFFICIENT_DATA`; it now evaluates its `AlarmRule` on create, update and every child state change, with AWS's `StateReason`, `StateReasonData` and history. `PutCompositeAlarm` refuses an unknown child or a malformed rule (also one nested over 256 levels) with `ValidationError`, a long `AND`/`OR` chain no longer answers 500, `DeleteAlarms` and stack deletes refuse an alarm a composite depends on and `DeleteAlarms` more than one composite, and `DescribeAlarmHistory` returns composite items only for `AlarmTypes=["CompositeAlarm"]`. Contributed by @iot-rocket.+- **IAM — trust policies with `NotPrincipal`** — `CreateRole`, `UpdateAssumeRolePolicy` and `AWS::IAM::Role` stored them; they now answer `MalformedPolicyDocument` (`Allow with NotPrincipal is not allowed.`, `AssumeRole policy must not contain NotPrincipal field.`). Contributed by @iot-rocket.+- **CloudTrail — `RecursiveLogging` on trails** — `CreateTrail` and `UpdateTrail` ignored it; trails now store it (default `true`, kept by an `UpdateTrail` without it) and return it from every trail response. Contributed by @iot-rocket.+- **CloudFormation — callback URLs under `USE_SSL=1`** — the custom resource `ResponseURL` and the `WaitConditionHandle` URL were always `http://`, which the TLS-only gateway drops, so a handler's `urllib` PUT never arrived and the stack waited out `ServiceTimeout`; both are now `https://` when `USE_SSL` is on, and MiniStack's Lambdas get `SSL_CERT_FILE` set to the gateway's CA bundle, which Python's `ssl` reads. Contributed by @iot-rocket.## [1.5.29] — 2026-10-17diff --git a/ministack/app.py b/ministack/app.pyindex 6ac3273d..372559e8 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -2304,17 +2304,19 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: d)s3_action = _s3_action(method, vhost_path, query_params)+ # x-amz-* headers hoisted into the query string count as the headers they stand for.+ s3_headers = s3._merge_hoisted_amz_headers(headers, query_params)if s3_action:- s3_resource = extract_resource_arn("s3", method, vhost_path, headers, body, query_params, "", "")+ s3_resource = extract_resource_arn("s3", method, vhost_path, s3_headers, body, query_params, "", "")denied = _enforce_data_plane("s3", f"s3:{s3_action}", headers, query_params, "", resource_arn=s3_resource,- service_context=s3_service_context(f"s3:{s3_action}", query_params, vhost_path, headers),+ service_context=s3_service_context(f"s3:{s3_action}", query_params, vhost_path, s3_headers),)if denied:return denied# A copy also reads its source, a batch delete is one check per# key, an attributes call is a pair, a governance bypass its own action.- for extra_action, extra_arn in s3_additional_checks(method, vhost_path, headers, body, query_params):+ for extra_action, extra_arn in s3_additional_checks(method, vhost_path, s3_headers, body, query_params):denied = _enforce_data_plane("s3", extra_action, headers, query_params, "", resource_arn=extra_arn)if denied:return denied@@ -2864,7 +2866,11 @@ async def _dispatch_service_request(if upload_error is not None:return upload_error- if AUTH:+ # AppSync authorizes a GraphQL request by the API's own authorization types.+ appsync_graphql = service == "appsync" and method == "POST" and (+ _APPSYNC_GRAPHQL_RE.match(path)+ or (path == "/graphql" and re.search(r"\.appsync-api\.", headers.get("host", ""))))+ if AUTH and not appsync_graphql:from ministack.core.iam_actions import (access_denied_response,agentcore_endpoint_arn,@@ -2883,7 +2889,14 @@ async def _dispatch_service_request(pin_request_caller(headers, query_params)iam_action = extract_iam_action(service, method, path, headers, body, routing_params)- if iam_action is None and (failure := _authenticate_only(service, headers, query_params, request_id)):+ if service == "ses" and (path.startswith("/v2/") or "sesv2" in headers.get("x-amz-target", "").lower()):+ # SES v2 also answers on paths without /v2/email when the target header names it: authorize the call+ # as the /v2/email operation it performs, never as an action the target header names.+ v2_path = path if path.startswith(_SES_V2_PREFIX) else f"{_SES_V2_PREFIX}/{path.lstrip('/')}"+ if denied := _enforce_ses_v2(method, v2_path, headers, body, query_params, request_id):+ return denied+ iam_action = None+ elif iam_action is None and (failure := _authenticate_only(service, headers, query_params, request_id)):return failureif iam_action is not None:access_key = extract_access_key_id(headers, query_params)@@ -2892,7 +2905,9 @@ async def _dispatch_service_request()service_context = (dynamodb_service_context(body) if service == "dynamodb"- else s3_service_context(iam_action, query_params, path, headers) if service == "s3"+ else s3_service_context(iam_action, query_params, path,+ _get_module("s3")._merge_hoisted_amz_headers(headers, query_params))+ if service == "s3"else None)if service == "logs":@@ -2944,7 +2959,8 @@ async def _dispatch_service_request(if service == "s3" and not denied:from ministack.core.iam_actions import s3_additional_checks- for extra_action, extra_arn in s3_additional_checks(method, path, headers, body, routing_params):+ s3_headers = _get_module("s3")._merge_hoisted_amz_headers(headers, query_params)+ for extra_action, extra_arn in s3_additional_checks(method, path, s3_headers, body, routing_params):denied = enforce(access_key, extra_action, service, region, resource_arn=extra_arn)if denied:iam_action = extra_actiondiff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex 50cd918a..0e0a0920 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -1928,7 +1928,7 @@ def s3_service_context(iam_action: str, query_params: dict | None, path: str = "def _s3_object_context(iam_action: str, query_params: dict, path: str, headers: dict) -> dict:- """s3:x-amz-server-side-encryption and s3:x-amz-acl of a write, s3:ExistingObjectTag/<key> of a read."""+ """s3:x-amz-server-side-encryption, s3:x-amz-acl and s3:x-amz-grant-* of a write, s3:ExistingObjectTag of a read."""from ministack.services import s3 as s3_svcbucket, _, key = path.lstrip("/").partition("/")@@ -1941,8 +1941,11 @@ def _s3_object_context(iam_action: str, query_params: dict, path: str, headers:sse = s3_svc.upload_encryption_header(upload_id) if upload_id else headers.get("x-amz-server-side-encryption")if sse:context["s3:x-amz-server-side-encryption"] = sse- if not upload_id and headers.get("x-amz-acl"):- context["s3:x-amz-acl"] = headers["x-amz-acl"]+ if not upload_id:+ for name in ("x-amz-acl", "x-amz-grant-read", "x-amz-grant-write", "x-amz-grant-read-acp",+ "x-amz-grant-write-acp", "x-amz-grant-full-control"):+ if headers.get(name):+ context[f"s3:{name}"] = headers[name]else:for name, value in s3_svc.object_tags_for_condition(bucket, key, query_params).items():context[f"s3:ExistingObjectTag/{name}"] = value@@ -2089,6 +2092,11 @@ _AUTH_FAILURES: dict[str, tuple[str, int, str, tuple[str, int, str]]] = {),"IncompleteSignature": _INCOMPLETE,"MissingAuthorizationParameter": _INCOMPLETE,+ "UnsupportedSignature": (+ "IncompleteSignature", 400, "IncompleteSignatureException",+ ("InvalidRequest", 400, "The authorization mechanism you have provided is not supported. "+ "Please use AWS4-HMAC-SHA256."),+ ),}_QUERY_COMPATIBLE = frozenset({"sqs"})diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.pyindex 923177f6..1b83b831 100644--- a/ministack/core/iam_evaluator.py+++ b/ministack/core/iam_evaluator.py@@ -1250,10 +1250,27 @@ class SignedRequest:body: bytes = b""presigned: bool = Falsehandshake: bool = False+ # Credentials this server cannot verify (another algorithm, a key the signature does not cover).+ unverifiable: bool = False+ # A SigV2 (HmacV1) header or query signature, checked against the path S3 signs.+ sigv2: bool = False+ auth_path: str = ""_signed_request: contextvars.ContextVar[SignedRequest | None] = contextvars.ContextVar("ministack_signed_request", default=None)+# The access key whose signature this request already passed, once checked.+_verified_key: contextvars.ContextVar[str] = contextvars.ContextVar("ministack_verified_key", default="")+++def caller_verified(access_key_id: str, account_id: str) -> bool:+ """Whether the request's SigV4/SigV2 signature for this key checks out (root keys are not checked)."""+ if not access_key_id:+ return False+ if _is_root_key(access_key_id) or _verified_key.get() == access_key_id:+ return True+ checked = authenticate(access_key_id, account_id)+ return checked is not None and not isinstance(checked, AuthError)def pin_signed_request(@@ -1263,12 +1280,30 @@ def pin_signed_request(from ministack.core.router import extract_access_key_idfrom ministack.core.sigv4 import decode_header_value+ _verified_key.set("")authorization = decode_header_value(next((v for n, v in raw_headers if n.lower() == b"authorization"), b""))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)- # A signature that names no key is checked too: it is incomplete or names an unknown key.- if not (authorization.startswith("AWS4-HMAC-SHA256") or presigned) or (- access_key_id and _is_root_key(access_key_id)):+ # The key the policy check will use; it must be the one the signature is checked for.+ claimed = extract_access_key_id({"authorization": authorization}, query_params)+ verifiable = (authorization.startswith("AWS4-HMAC-SHA256") or presigned) and bool(claimed) and access_key_id == claimed+ sigv2 = authorization.startswith("AWS ") or bool(+ _query_value(query_params or {}, "AWSAccessKeyId") and _query_value(query_params or {}, "Signature")+ and not _query_value(query_params or {}, "SignatureVersion"))+ if sigv2 and claimed and not _is_root_key(claimed) and not authorization.startswith("AWS4-"):+ headers = {name.decode("latin-1").lower(): decode_header_value(value) for name, value in raw_headers}+ from ministack.app import _extract_s3_vhost_bucket+ bucket = _extract_s3_vhost_bucket(headers.get("host", ""))+ _signed_request.set(SignedRequest(claimed, method, raw_path, query_params, headers, sigv2=True,+ auth_path=f"/{bucket}{raw_path}" if bucket else raw_path))+ return+ # A SigV4 signature that names no key is checked too: it is incomplete or names an unknown key.+ names_no_key = not claimed and (authorization.startswith("AWS4-HMAC-SHA256") or presigned)+ if not verifiable and not names_no_key and _signature_attempted(authorization, query_params) and not (+ claimed and _is_root_key(claimed)) and not _s3_presigned_query(query_params):+ _signed_request.set(SignedRequest(claimed, method, raw_path, query_params, {}, unverifiable=True))+ return+ if not (verifiable or names_no_key) or (access_key_id and _is_root_key(access_key_id)):_signed_request.set(None)returnheaders: dict[str, str] = {}@@ -1280,6 +1315,73 @@ def pin_signed_request(access_key_id, method, raw_path, query_params, headers, presigned=presigned, handshake=handshake))+def _sigv2_check(request: SignedRequest, account_id: str) -> AuthError | ResolvedCredential:+ """Verify a SigV2 (HmacV1) header or query signature as S3 computes it."""+ from urllib.parse import urlencode, urlsplit++ from botocore.auth import HmacV1Auth+ from botocore.awsrequest import HTTPHeaders+ from botocore.credentials import Credentials++ from ministack.core.responses import _account_from_sts_session++ query = request.query_params or {}+ presigned = not request.headers.get("authorization", "").startswith("AWS ")+ token = (_query_value(query, "x-amz-security-token") if presigned+ else request.headers.get("x-amz-security-token", ""))+ credential = resolve_credential(request.access_key_id,+ _account_from_sts_session(request.access_key_id) or account_id, token)+ if isinstance(credential, CredentialResolutionError):+ return AuthError(credential.code, credential.message)+ headers = HTTPHeaders()+ for name, value in request.headers.items():+ headers[name] = value+ pairs = [(k, v) for k, values in query.items() for v in (values if isinstance(values, list) else [values])]+ split = urlsplit("http://host" + request.auth_path + ("?" + urlencode(pairs) if pairs else ""))+ if presigned:+ # A query signature signs Expires where a header signature signs Date.+ signed_date = _query_value(query, "Expires")+ if not signed_date.isdigit() or int(signed_date) < time.time():+ return AuthError("SignatureDoesNotMatch", "Request has expired")+ given = _query_value(query, "Signature")+ else:+ signed_date = request.headers.get("date", "")+ given = request.headers["authorization"].split(":", 1)[-1]++ class _Signer(HmacV1Auth):+ def _get_date(self): # the date the client signed, not the time of this check+ return signed_date++ signer = _Signer(Credentials(credential.access_key_id, credential.secret_access_key, token or None))+ expected = signer.get_signature(request.method, split, headers)+ if not hmac.compare_digest(given.encode(), expected.encode()):+ return AuthError("SignatureDoesNotMatch", "The request signature we calculated does not match the signature "+ "you provided. Check your key and signing method.")+ _verified_key.set(request.access_key_id)+ return credential+++def _query_value(query_params: dict, name: str) -> str:+ found = query_params.get(name) or query_params.get(name.lower()) or [""]+ return found[0] if isinstance(found, list) else found+++def _signature_attempted(authorization: str, query_params: dict) -> bool:+ """Whether a request carries any AWS signature or credential, valid or not."""+ if authorization.startswith(("AWS4-", "AWS ")):+ return True+ return any(_query_value(query_params or {}, name) for name in (+ "X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Signature", "AWSAccessKeyId", "Signature"))+++def _s3_presigned_query(query_params: dict) -> bool:+ """A complete SigV4 presigned S3 URL, which S3 verifies itself."""+ query_params = query_params or {}+ scope = _query_value(query_params, "X-Amz-Credential").split("/")+ return (_query_value(query_params, "X-Amz-Algorithm") == "AWS4-HMAC-SHA256" and bool(scope[0])+ and len(scope) == 5 and scope[3] == "s3" and bool(_query_value(query_params, "X-Amz-Signature")))++def _query_signed(query_params: dict) -> bool:"""A SigV4 query-string signature; S3 checks its own presigned URLs."""def value(name):@@ -1307,7 +1409,7 @@ def authenticate_handshake(scope: dict) -> AuthError | ResolvedCredential | Nonequery_params = parse_qs(scope.get("query_string", b"").decode("utf-8", "replace"), keep_blank_values=True)pin_signed_request("GET", raw_path.decode("latin-1"), query_params, scope.get("headers", []), handshake=True)request = _signed_request.get()- if request is None or not request.access_key_id:+ if request is None:return Nonetry:account_id = find_iam_access_key_account(request.access_key_id) or get_account_id()@@ -1330,6 +1432,10 @@ def authenticate(access_key_id: str, account_id: str) -> AuthError | ResolvedCreif 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+ if request.unverifiable:+ return AuthError("UnsupportedSignature", "The request signature does not conform to AWS standards.")+ if request.sigv2:+ return _sigv2_check(request, account_id)if request.presigned:signature = parse_query_signature(request.query_params)else:@@ -1365,6 +1471,7 @@ def authenticate(access_key_id: str, account_id: str) -> AuthError | ResolvedCrecanonical, string_to_sign = header_signing_documents(signature, request.method, request.raw_path, request.query_params, request.headers, request.body,+ presigned=request.presigned,)details = {"AWSAccessKeyId": access_key_id,@@ -1375,6 +1482,7 @@ def authenticate(access_key_id: str, account_id: str) -> AuthError | ResolvedCre"CanonicalRequestBytes": canonical.encode("utf-8").hex(" "),}return AuthError(*failure, details=details)+ _verified_key.set(access_key_id)return credential@@ -1470,9 +1578,10 @@ def enforce(access_key_id: str, iam_action: str, service: str,from ministack.core.responses import get_account_idaccount_id = get_account_id()- # S3, API Gateway methods and function URLs can be called anonymously: a request naming no key is not checked.+ # S3, API Gateway methods and function URLs can be called anonymously: an unsigned request is not checked.anonymous_ok = service == "s3" or iam_action in ("execute-api:Invoke", "lambda:InvokeFunctionUrl")- checked = None if anonymous_ok and not access_key_id else authenticate(access_key_id or "", account_id)+ unsigned = anonymous_ok and not access_key_id and _signed_request.get() is None+ checked = None if unsigned else authenticate(access_key_id or "", account_id)if isinstance(checked, AuthError):return checkeddiff --git a/ministack/core/sigv4.py b/ministack/core/sigv4.pyindex 5448a767..c7c3f75d 100644--- a/ministack/core/sigv4.py+++ b/ministack/core/sigv4.py@@ -322,13 +322,14 @@ def header_signature_failure(body: bytes,*,presigned: bool = False,+ explain: bool = False,) -> tuple[str, str] | None:"""Recompute a header (or, ``presigned``, query-string) signature; S3 signs its path as sent, other servicesthe 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. ")- _, string_to_sign = header_signing_documents(+ canonical_request, string_to_sign = header_signing_documents(signature, method, raw_path, query_params, headers, body, presigned=presigned,)# Only an explicit streaming marker requires chunk verification; an absentdiff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.pyindex ff4cb1ac..de434d59 100644--- a/ministack/services/apigateway_v1.py+++ b/ministack/services/apigateway_v1.py@@ -295,6 +295,11 @@ def _rest_api_view(api):view = dict(api)if "policy" in view:view["policy"] = _encode_rest_api_policy(view["policy"])+ # Nothing provisions in the background, so an API is AVAILABLE as soon as it exists.+ view["apiStatus"] = "AVAILABLE"+ root_id = next((r["id"] for r in (_resources.get(view.get("id")) or {}).values() if r.get("path") == "/"), None)+ if root_id:+ view["rootResourceId"] = root_idreturn view@@ -1950,8 +1955,11 @@ async def _authorize_request_v1(# Under AUTH a presigned request was verified before it got here.from ministack.app import AUTHfrom ministack.core.iam_evaluator import _query_signed+ from ministack.core.router import extract_access_key_id- if not _header_ci(headers, "authorization") and not (AUTH and _query_signed(query_params or {})):+ # A presigned call passes only when its query names a key, whose signature the router then verified.+ if not _header_ci(headers, "authorization") and not (+ AUTH and _query_signed(query_params or {}) and extract_access_key_id({}, query_params or {})):return _gw_error("MISSING_AUTHENTICATION_TOKEN", "Missing Authentication Token"), Nonereturn None, Noneif auth_type == "COGNITO_USER_POOLS":diff --git a/ministack/services/appsync.py b/ministack/services/appsync.pyindex 62ea4bd1..b85b1008 100644--- a/ministack/services/appsync.py+++ b/ministack/services/appsync.py@@ -1071,7 +1071,7 @@ async def handle_request(method, path, headers, body, query_params):allow_cross_region=not _has_sigv4_credentials(headers, query_params),)if not api_id:- return error_response_json("UnauthorizedException", "Valid API key required", 401)+ return _unauthorized_response()authorize = _iam_field_authorizer(api_id, headers, query_params)if isinstance(authorize, tuple):return authorize@@ -1543,7 +1543,14 @@ def _request_is_authenticated(api_id, api, request_headers):if auth and not auth.startswith("AWS4-HMAC-SHA256"):return Trueif "AWS_IAM" in modes and auth.startswith("AWS4-HMAC-SHA256"):- return True+ from ministack.app import AUTH+ if not AUTH:+ return True+ from ministack.core.iam_evaluator import caller_verified+ from ministack.core.router import extract_access_key_id+ # Under AUTH a SigV4 header counts only once its signature checks out.+ if caller_verified(extract_access_key_id(headers, {}), get_account_id()):+ return Trueif "AWS_LAMBDA" in modes and api.get("lambdaAuthorizerConfig"):# The authorizer runs below and may still reject.return True@@ -1660,11 +1667,14 @@ def _execute_graphql(api_id, data, request_headers=None, authorize=None):if data.get("query") is None:return _malformed_graphql_request("Invalid request, `query` can't be null.")+ if not isinstance(query, str) or (variables is not None and not isinstance(variables, dict)):+ return _malformed_graphql_request("Invalid JSON payload in GraphQLAuth POST request.")+ variables = variables or {}if not query.strip():return _malformed_graphql_request("Invalid request, `query` can't be empty.")if api_id not in _apis:- return _json(404, {"errors": [{"message": f"API {api_id} not found"}]})+ return _graphql_error(404, "ResourceNotFoundException", "Unable to find the Api.")# Applied before either execution path, so it does not depend on whether# the API has a schema. AWS refuses a request that satisfies none of thediff --git a/ministack/services/appsync_events.py b/ministack/services/appsync_events.pyindex b6ad76b5..7af12614 100644--- a/ministack/services/appsync_events.py+++ b/ministack/services/appsync_events.py@@ -958,7 +958,7 @@ async def _publish(api_id: str, headers: dict, body: bytes):return _publish_error(400, "BadRequestException", f"Input exceeded {_MAX_EVENTS_PER_BATCH} event limit")- if _validate_channel(channel, allow_wildcard=False):+ if not isinstance(channel, str) or _validate_channel(channel, allow_wildcard=False):return _publish_error(400, "BadRequestException", "Invalid Channel Format")ns_name = _channel_namespace_for(channel)diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 5a6a3bff..414ce5bb 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -10377,7 +10377,7 @@ def _cw_metric_alarm_update(physical_id, old_props, new_props, stack_name,def _cw_metric_alarm_delete(physical_id, props):- _cw.cloudformation_delete_metric_alarm(physical_id)+ _cw.cloudformation_delete_metric_alarm(physical_id, refuse_dependents=True)# ---------------------------------------------------------------------------diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.pyindex a0100f56..14c1f7f2 100644--- a/ministack/services/cloudwatch.py+++ b/ministack/services/cloudwatch.py@@ -1103,13 +1103,15 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):_RULE_TOKEN = re.compile(r'[(),]|"(?:[^"\\]|\\.)*"|[^\s(),"]+|\S')_RULE_STATES = ("ALARM", "OK", "INSUFFICIENT_DATA")_RULE_OPERAND = "'(', 'NOT', AT_LEAST, TRUE or FALSE, ALARM, OK, or INSUFFICIENT_DATA"+# Nesting cap, so the result never depends on the process recursion limit (jsonata raises it).+_RULE_MAX_DEPTH = 256@functools.lru_cache(maxsize=512)def _parse_alarm_rule(rule):"""Parse an AlarmRule into a tree of tuples, raising ValueError with the AWS message."""tokens = [(m.group(), m.start()) for m in _RULE_TOKEN.finditer(rule)] + [("<EOF>", len(rule))]- at = 0+ at = depth = 0def word():return tokens[at][0]@@ -1134,14 +1136,21 @@ def _parse_alarm_rule(rule):return re.sub(r"\\(.)", r"\1", text[1:-1]) if text.startswith('"') else textdef operand():- nonlocal at+ nonlocal at, depthw = word()+ if w in ("NOT", "(") and depth >= _RULE_MAX_DEPTH:+ fail()at += 1if w == "NOT":- return ("not", operand())+ depth += 1+ node = ("not", operand())+ depth -= 1+ return nodeif w == "(":+ depth += 1node = disjunction()take(")")+ depth -= 1return nodeif w in ("TRUE", "FALSE"):return ("const", w == "TRUE")@@ -1177,21 +1186,24 @@ def _parse_alarm_rule(rule):def conjunction():nonlocal at- node = operand()+ nodes = [operand()]while word() == "AND":at += 1- node = ("and", node, operand())- return node+ nodes.append(operand())+ return nodes[0] if len(nodes) == 1 else ("and", *nodes)def disjunction():nonlocal at- node = conjunction()+ nodes = [conjunction()]while word() == "OR":at += 1- node = ("or", node, conjunction())- return node+ nodes.append(conjunction())+ return nodes[0] if len(nodes) == 1 else ("or", *nodes)- tree = disjunction()+ try:+ tree = disjunction()+ except RecursionError:+ fail()if at != len(tokens) - 1:fail("<EOF>, 'AND', 'OR'")return tree@@ -1213,9 +1225,9 @@ def _rule_true(node):if kind == "not":return not _rule_true(node[1])if kind == "and":- return _rule_true(node[1]) and _rule_true(node[2])+ return all(_rule_true(child) for child in node[1:])if kind == "or":- return _rule_true(node[1]) or _rule_true(node[2])+ return any(_rule_true(child) for child in node[1:])_, count, percent, negate, state, refs = nodehits = sum((_rule_alarm_state(r) == state) != negate for r in refs)return hits * 100 >= count * len(refs) if percent else hits >= count@@ -1233,7 +1245,7 @@ def _rule_matches(node, target):return _rule_matches(node[1], not target)if kind == "const":return []- return _rule_matches(node[1], target) + _rule_matches(node[2], target)+ return [r for child in node[1:] for r in _rule_matches(child, target)]def _rule_refs(node):@@ -2276,8 +2288,14 @@ def cloudformation_set_metric_alarm_tags(name: str, tags: list) -> None:_resource_tags[arn] = {t["Key"]: t.get("Value", "") for t in tags}-def cloudformation_delete_metric_alarm(name: str) -> None:- """Remove a metric alarm created from a template (not composite alarms)."""+def cloudformation_delete_metric_alarm(name: str, refuse_dependents: bool = False) -> None:+ """Remove a metric alarm created from a template (not composite alarms).++ ``refuse_dependents`` makes a stack delete fail, as DeleteAlarms does, while a composite alarm still needs it.+ """+ if refuse_dependents and name in _alarms and any(+ name in _composite_children(parent) for parent in _composite_alarms.values()):+ raise ValueError(f"Cannot delete {name} as there are composite alarm(s) depending on it.")_alarms.pop(name, None)_resource_tags.pop(f"arn:aws:cloudwatch:{get_region()}:{get_account_id()}:alarm:{name}", Nonediff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 8a39f6ee..4ed6e8a2 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -3777,6 +3777,10 @@ def _admin_delete_user(data):# can pass an alias (email), which is not the "_users" key.del pool["_users"][user["Username"]]pool["EstimatedNumberOfUsers"] = len(pool["_users"])+ # A deleted user's refresh tokens end with it: a new user of the same name inherits none of them.+ for token in [t for t, e in _refresh_tokens.items()+ if e.get("username") == user["Username"] and e.get("pool_id") == pid]:+ del _refresh_tokens[token]return json_response({})@@ -4481,6 +4485,9 @@ def _refresh_auth_user(pool, pid, cid, refresh_token):if (not isinstance(claims, dict) or claims.get("token_use") != "refresh"or str(claims.get("iss", "")).rsplit("/", 1)[-1] != pid):return None, error_response_json("NotAuthorizedException", "Invalid Refresh Token", 400)+ from ministack.app import AUTH+ if AUTH and _RSA_PRIVATE_KEY is not None and not _signature_valid(refresh_token):+ return None, error_response_json("NotAuthorizedException", "Invalid Refresh Token", 400)if claims.get("client_id") != cid:return None, error_response_json("NotAuthorizedException","Refresh Token has different Client", 400)@@ -4488,10 +4495,10 @@ def _refresh_auth_user(pool, pid, cid, refresh_token):if not user:return None, error_response_json("NotAuthorizedException","The user has been deleted for the associated refresh token", 400)- from ministack.app import AUTHif AUTH and not user.get("Enabled", True):return None, error_response_json("NotAuthorizedException", "User is disabled.", 400)- if _refresh_token_revoked(refresh_token, user) or (AUTH and claims.get("origin_jti") in _revoked_tokens):+ origin = claims.get("origin_jti")+ if _refresh_token_revoked(refresh_token, user) or (AUTH and isinstance(origin, str) and origin in _revoked_tokens):return None, error_response_json("NotAuthorizedException","Refresh Token has been revoked", 400)return user, None@@ -7201,6 +7208,10 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Nonuser = pool["_users"].get(entry["username"])if not user:return _oauth2_error("server_error", "User not found.")+ from ministack.app import AUTH+ if AUTH and not user.get("Enabled", True):+ # A code issued before AdminDisableUser no longer signs the user in.+ return _oauth2_error("invalid_grant", "User is disabled.")scope = _granted_scopes(client, entry.get("scope"))result = _build_auth_result(pool_id, cid, user, nonce=entry.get("nonce", ""),@@ -7287,6 +7298,11 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Nonuser = pool["_users"].get(entry["username"])if not user:return _oauth2_error("server_error", "User not found.")+ from ministack.app import AUTH+ registry_origin = _token_claims(refresh_val).get("origin_jti")+ if AUTH and (not user.get("Enabled", True) or _refresh_token_revoked(refresh_val, user) or (+ isinstance(registry_origin, str) and registry_origin in _revoked_tokens)):+ return _oauth2_error("invalid_grant", "Invalid refresh token.")# Validate client secret if client has one_, _, client = _find_pool_by_client_id(cid or entry["client_id"])@@ -7410,7 +7426,10 @@ def handle_oauth2_userinfo(method, path, headers, body, query_params):error = _userinfo_token_error(token) if AUTH else Noneif error:iss = _token_claims(token).get("iss")- realm = f"realm={iss}, " if isinstance(iss, str) and _get_pool_unscoped(iss.rsplit("/", 1)[-1]) else ""+ pool_id = iss.rsplit("/", 1)[-1] if isinstance(iss, str) else ""+ # The pool's own issuer, never the text a token claims.+ realm = (f"realm=https://cognito-idp.{pool_id.split('_', 1)[0]}.amazonaws.com/{pool_id}, "+ if pool_id and _get_pool_unscoped(pool_id) else "")return 401, {"Content-Type": "application/json", "WWW-Authenticate": f"Bearer {realm}error=INVALID_TOKEN"}, \json.dumps({"error": "invalid_token", "error_description": error}).encode()# Decode JWT payload@@ -7595,14 +7614,14 @@ def _get_id(data):pool = _identity_pools.get(iid)if not pool:return error_response_json("ResourceNotFoundException", f"Identity pool {iid} not found.", 400)+ logins = data.get("Logins") or {}if AUTH:- logins = data.get("Logins") or {}error = _identity_logins_error(pool, None, logins)if error:return error- owner = _link_logins(pool, None, logins)- if owner:- return json_response({"IdentityId": owner})+ owner = _link_logins(pool, None, logins)+ if owner:+ return json_response({"IdentityId": owner})identity_id = _identity_id(iid)pool["_identities"][identity_id] = {"IdentityId": identity_id,@@ -7661,7 +7680,7 @@ def _get_credentials_for_identity(data):error = _identity_logins_error(candidate, identity_id, logins)if error:return error- identity_id = _link_logins(candidate, identity_id, logins)+ identity_id = _link_logins(candidate, identity_id, logins)if not logins:logins = candidate["_identities"][identity_id].get("Logins") or {}break@@ -7722,9 +7741,15 @@ def _identity_logins_error(pool: dict, identity_id: str | None, logins: dict):return Nonereturn error_response_json("NotAuthorizedException", f"Access to Identity '{identity_id}' is forbidden.", 400)unsupported = "Token is not from a supported provider of this identity pool."- not_oidc = "Invalid login token. Not a valid OpenId Connect identity token."mismatch = "Logins don't match. Please include at least one valid login for this identity or identity pool."+ if not isinstance(logins, dict):+ return error_response_json("NotAuthorizedException", unsupported, 400)+ not_oidc = "Invalid login token. Not a valid OpenId Connect identity token."skewed_now = int(time.time()) - _LOGIN_TOKEN_CLOCK_SKEW+ supported = set(pool.get("SupportedLoginProviders") or {}) | set(pool.get("SamlProviderARNs") or [])+ supported |= {arn.split("oidc-provider/", 1)[-1] for arn in pool.get("OpenIdConnectProviderARNs") or []}+ if pool.get("DeveloperProviderName"):+ supported.add("cognito-identity.amazonaws.com")for provider, token in logins.items():clients = [p.get("ClientId") for p in pool.get("CognitoIdentityProviders") or []if p.get("ProviderName") == provider]@@ -7732,9 +7757,15 @@ def _identity_logins_error(pool: dict, identity_id: str | None, logins: dict):is_jwt = isinstance(token, str) and token.count(".") == 2 and bool(claims)if provider == "accounts.google.com" and not is_jwt and provider in (pool.get("SupportedLoginProviders") or {}):message = not_oidc+ elif not provider.startswith("cognito-idp.") and provider not in supported:+ message = unsupportedelif not provider.startswith("cognito-idp."):- # Other providers' tokens are opaque here.- continue+ # A supported provider's token is opaque here; an identity's own login must still be the one it holds.+ if provider in stored and token != stored[provider] and (+ not claims.get("sub") or _token_claims(stored[provider]).get("sub") != claims.get("sub")):+ message = mismatch+ else:+ continueelif not clients:message = unsupportedelif not is_jwt:@@ -7755,19 +7786,23 @@ def _identity_logins_error(pool: dict, identity_id: str | None, logins: dict):continuereturn error_response_json("NotAuthorizedException", message, 400)# An identity with a login needs one of its own; a disabled one, a login another identity holds.- none_of_its_own = stored and not stored.keys() & logins.keys()- if none_of_its_own or identity.get("_merged_into") and not _login_owner(pool, logins):+ if stored and not any(provider in stored for provider in logins) or (+ identity.get("_merged_into") and not _login_owner(pool, logins)):return error_response_json("NotAuthorizedException", mismatch, 400)return Nonedef _login_owner(pool: dict, logins: dict):"""The id of the pool's identity that already holds one of these logins, or None."""+ if not isinstance(logins, dict):+ return Nonefor provider, token in logins.items():sub = _token_claims(token).get("sub")for identity_id, identity in pool["_identities"].items():held = (identity.get("Logins") or {}).get(provider)- if held is not None and (held == token or (sub and _token_claims(held).get("sub") == sub)):+ # Only a user pool token is verified, so only its sub identifies a user.+ if held is not None and (held == token or (+ sub and provider.startswith("cognito-idp.") and _token_claims(held).get("sub") == sub)):return identity_idreturn None@@ -7819,7 +7854,7 @@ def _get_open_id_token(data):error = _identity_logins_error(pool, identity_id, logins)if error:return error- identity_id = _link_logins(pool, identity_id, logins)+ identity_id = _link_logins(pool, identity_id, logins)logins = logins or pool["_identities"][identity_id].get("Logins") or {}breakif not pool_id:diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex e9bc3c18..61b76b62 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -7790,14 +7790,12 @@ def _list_job_executions_for_thing(thing: str, qp: dict) -> tuple:# the jobId beside it (JobExecutionSummaryForThing).summaries = []# A rejoined thing's executions of one job come newest first, as on AWS.- executions = [- execution- for latest in _job_executions.values()- for execution in _jobs_with_history(_jobs_apply_timeout(latest))- ]+ # Time out only this thing's executions, all of them before any is read, so the page agrees with itself.+ latest_executions = [e for e in list(_job_executions.values()) if e["thingName"] == thing]+ for latest in latest_executions:+ _jobs_apply_timeout(latest)+ executions = [execution for latest in latest_executions for execution in _jobs_with_history(latest)]for execution in executions:- if execution["thingName"] != thing:- continueif wanted_status and execution["status"] != wanted_status:continueif wanted_job and execution["jobId"] != wanted_job:@@ -7846,11 +7844,13 @@ def _list_job_executions_for_job(job_id: str, qp: dict) -> tuple:"ResourceNotFoundException", f"Job {job_id} cannot be found.", 404)_jobs_materialize_executions(job_id)+ latest_executions = [e for e in list(_job_executions.values()) if e["jobId"] == job_id]+ for latest in latest_executions:+ _jobs_apply_timeout(latest)executions = [execution- for latest in _job_executions.values()- if latest["jobId"] == job_id- for execution in _jobs_with_history(_jobs_apply_timeout(latest))+ for latest in latest_executions+ for execution in _jobs_with_history(latest)if status is None or execution["status"] == status]executions.sort(key=lambda e: e["lastUpdatedAt"], reverse=True)@@ -7931,7 +7931,7 @@ async def _cancel_job_execution()prev_next = jobs_first_pending_job_id(thing)execution["status"] = "CANCELED"- if payload.get("statusDetails"):+ if isinstance(payload.get("statusDetails"), dict):execution["statusDetails"] = dict(payload["statusDetails"])execution["lastUpdatedAt"] = _jobs_now_ms()execution["versionNumber"] += 1@@ -8066,7 +8066,7 @@ def jobs_start_next_execution(execution["startedAt"] = nowexecution["lastUpdatedAt"] = nowexecution["versionNumber"] += 1- if status_details:+ if isinstance(status_details, dict):execution["statusDetails"] = dict(status_details)return dict(execution)@@ -8350,6 +8350,15 @@ def _jobs_mqtt_json(value) -> str:return _jobs_device_json(value)+def _jobs_status_details_error(status_details):+ """InvalidRequestException unless statusDetails is a map of non-empty strings, as the DetailsMap shape is."""+ if status_details is None or (isinstance(status_details, dict) and all(+ isinstance(k, str) and k and isinstance(v, str) and v for k, v in status_details.items())):+ return None+ return error_response_json(+ "InvalidRequestException", "statusDetails must be a map of non-empty string keys to non-empty strings", 400)++def jobs_update_execution(thing_name: str,job_id: str,@@ -8368,6 +8377,8 @@ def jobs_update_execution(`execution_number` (404), stale or non-numeric `expectedVersion`, and analready-terminal execution. A successful update may complete the job."""+ if error := _jobs_status_details_error(status_details):+ return None, errorif not status or status not in _JOB_EXECUTION_STATUSES:return None, error_response_json("InvalidRequestException",@@ -9017,6 +9028,9 @@ def _reserved_topic_publish_allowed(topic: str) -> bool:def _reserved_filter_subscribe_allowed(topic_filter: str) -> bool:+ if topic_filter.startswith("$share/"):+ # A shared subscription ($share/{ShareName}/{TopicFilter}) is held to the rule for its filter.+ topic_filter = topic_filter.split("/", 2)[2] if topic_filter.count("/") >= 2 else ""return not topic_filter.startswith("$") or _RESERVED_FILTER_RE.fullmatch(topic_filter) is not None@@ -9751,6 +9765,9 @@ async def _handle_jobs_publish(returnif verb == "start-next":+ if error := _jobs_status_details_error(request.get("statusDetails")):+ await _respond("rejected", _jobs_error_tuple_to_rejected(error, client_token))+ returnwith request_scope(account_id, region):execution = jobs_start_next_execution(thing, status_details=request.get("statusDetails"), peek=False@@ -10824,6 +10841,7 @@ class _WSSession:self._send = send_coroself.account_id = account_idself.region = region+ self._cleaned_up = False# The client certificate id or the IAM caller's user id, else the account:# lifecycle events' principalIdentifier and the rule SQL principal().self._principal = principal or account_id@@ -10942,8 +10960,12 @@ class _WSSession:await self.deliver_to_client(reply_topic, json.dumps(doc).encode("utf-8"), max(granted))def _alloc_packet_id(self) -> int:- pid = self._next_pid- self._next_pid = (self._next_pid % 65535) + 1+ # Skip identifiers still in flight: one id never names two messages at once.+ for _ in range(65535):+ pid = self._next_pid+ self._next_pid = (self._next_pid % 65535) + 1+ if pid not in self._in_flight:+ return pidreturn piddef _ensure_retransmit_timer(self) -> None:@@ -11313,6 +11335,13 @@ class _WSSession:if existing_ps is not None and not _is_session_expired(existing_ps):session_present = Trueself._session_identifier = existing_ps.session_identifier+ # Unacknowledged messages keep their packet identifiers: restore them before+ # a resubscription replays a retained message, so no new id collides with them.+ self._next_pid = existing_ps.next_packet_id+ # The resuming connection receives them only where its own policies allow it.+ self._in_flight.update({pid: msg for pid, msg in existing_ps.in_flight.items()+ if self._policy_allows("iot:Receive", f"topic/{msg.topic}")})+ existing_ps.in_flight = {}for topic_filter in existing_ps.subscriptions:# A stored session keeps its topic filters, not the# subscription options they were made with: those live@@ -11332,11 +11361,7 @@ class _WSSession:await self._send_connack(session_present=True, assigned_client_id=assigned_client_id)- # Unacknowledged messages keep their packet identifiers and- # go out again once their retransmit interval has passed.- self._next_pid = existing_ps.next_packet_id- self._in_flight.update(existing_ps.in_flight)- existing_ps.in_flight = {}+ # They go out again once their retransmit interval has passed.await self._retransmit_due()queued = existing_ps.queued_messages[:]existing_ps.queued_messages.clear()@@ -11583,6 +11608,11 @@ class _WSSession:return Trueasync def cleanup(self) -> None:+ # A takeover cleans the old connection up, and its own transport loop does again on exit:+ # the second run must not overwrite the stored session with the evicted connection's state.+ if self._cleaned_up:+ return+ self._cleaned_up = Trueif self._retransmit_task is not None and not self._retransmit_task.done():self._retransmit_task.cancel()try:@@ -11673,12 +11703,12 @@ async def _feed_session(session: _WSSession, data: bytes, max_buffer: int) -> boreturn False-def _ws_handshake_refused(scope: dict) -> bool:- """Under AUTH=true, whether the upgrade's SigV4 signature, time or session token fails."""+def _ws_handshake_check(scope: dict) -> AuthError | ResolvedCredential | None:+ """Under AUTH=true, the upgrade's verified IAM credential or the ``AuthError`` refusing it; else None."""from ministack.app import AUTH- from ministack.core.iam_evaluator import AuthError, authenticate_handshake+ from ministack.core.iam_evaluator import authenticate_handshake- return bool(AUTH) and isinstance(authenticate_handshake(scope), AuthError)+ return authenticate_handshake(scope) if AUTH else Noneasync def _refuse_ws_handshake(scope: dict, send) -> None:@@ -11709,9 +11739,13 @@ async def handle_websocket(sub_headers[name.decode("latin-1").lower()] = value.decode("utf-8")except UnicodeDecodeError:sub_headers[name.decode("latin-1").lower()] = value.decode("latin-1")- if _ws_handshake_refused(scope):+ checked = _ws_handshake_check(scope)+ if isinstance(checked, AuthError):await _refuse_ws_handshake(scope, send)return+ if checked is not None:+ # The session belongs to the signing key's account, not the one guessed from the key id.+ account_id = checked.account_idrequested = sub_headers.get("sec-websocket-protocol", "")chosen = Nonefor proto in [p.strip() for p in requested.split(",") if p.strip()]:@@ -11728,7 +11762,9 @@ async def handle_websocket(ctx_token = _request_account_id.set(account_id)query = parse_qs(scope.get("query_string", b"").decode("latin-1"))- principal = _caller_principal(extract_access_key_id(sub_headers, query))+ # A verified signer names the session; an unverified credential only guesses one.+ principal = _caller_principal(checked.access_key_id if checked is not None+ else extract_access_key_id(sub_headers, query))session = _WSSession(send, account_id, region, principal)if checked is not None:session.iam_credential = (checked.access_key_id, checked.account_id)diff --git a/ministack/services/iot_jobs_data.py b/ministack/services/iot_jobs_data.pyindex 79984261..1d59d1c0 100644--- a/ministack/services/iot_jobs_data.py+++ b/ministack/services/iot_jobs_data.py@@ -159,6 +159,8 @@ def _start_next(thing: str, payload: dict, *, peek: bool) -> tuple:No jobs/notify(-next) publish: QUEUED -> IN_PROGRESS keeps the executionboth pending and at the front of the queue, and AWS stays silent(live-captured)."""+ if error := _iot_module._jobs_status_details_error(payload.get("statusDetails")):+ return errorexecution = _iot_module.jobs_start_next_execution(thing, status_details=payload.get("statusDetails"), peek=peek)@@ -219,12 +221,6 @@ async def _update_execution(thing: str, job_id: str, payload: dict) -> tuple:"InvalidRequestException",f"Invalid executionNumber: {execution_number!r}", 400,)- current = _iot_module.jobs_describe_execution(thing, job_id)- if current is not None and execution_number != current["executionNumber"]:- return error_response_json(- "ResourceNotFoundException",- f"Job {job_id} not found for {thing}", 404,- )prev_next = _iot_module.jobs_first_pending_job_id(thing)execution, error = _iot_module.jobs_update_execution(thing,@@ -233,6 +229,7 @@ async def _update_execution(thing: str, job_id: str, payload: dict) -> tuple:expected_version=payload.get("expectedVersion"),status_details=payload.get("statusDetails"),step_timeout_minutes=payload.get("stepTimeoutInMinutes"),+ execution_number=execution_number,)if error:return errordiff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 7b4735f7..dac00143 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -32,6 +32,7 @@ import copyimport datetime as _dtimport hashlibimport hmac+import ipaddressimport itertoolsimport jsonimport logging@@ -1066,6 +1067,10 @@ def bucket_policy_for_arn(resource_arn: str) -> tuple[str, str] | None:def object_tags_for_condition(bucket_name: str, key: str, query_params: dict) -> dict:"""The tags of the object version a read names, for ``s3:ExistingObjectTag`` in the identity check."""+ if bucket_name.endswith(_ACCESS_POINT_ALIAS_SUFFIX):+ resolved = resolve_access_point_alias(bucket_name)+ if resolved is not None and resolved[0] == get_account_id():+ bucket_name = resolved[2]["Bucket"]bucket = _buckets.get(bucket_name)if bucket is None:return {}@@ -1079,7 +1084,7 @@ def upload_encryption_header(upload_id: str) -> str | None:def _foreign_bucket_allows(owner_account: str, bucket_name: str, key: str,- method: str, query_params: dict, caller: str) -> bool:+ method: str, query_params: dict, caller: str, headers: dict | None = None) -> bool:"""Whether a caller who does not own the bucket may have this request.The owner's grants decide it: a Group grant on the bucket or the object@@ -1107,10 +1112,14 @@ def _foreign_bucket_allows(owner_account: str, bucket_name: str, key: str,policy = _bucket_policies.get_scoped(owner_account, None, bucket_name)if policy and not _public_access_blocked(owner_account, bucket_name, "RestrictPublicBuckets"):+ from ministack.core.iam_actions import _s3_action, s3_service_contextfrom ministack.core.iam_evaluator import EvalContext, evaluate_resource_policy- action = "s3:GetObject" if method in ("GET", "HEAD") else "s3:PutObject"+ path = f"/{bucket_name}/{key}" if key else f"/{bucket_name}"+ action = f"s3:{_s3_action(method, path, query_params) or ('GetObject' if method in ('GET', 'HEAD') else 'PutObject')}"resource = f"arn:aws:s3:::{bucket_name}"+ with request_scope(owner_account, get_region()):+ service_context = s3_service_context(action, query_params, path, headers or {})ctx = EvalContext(principal_arn=f"arn:aws:iam::{caller}:root" if caller else "*",principal_type="Root" if caller else "Anonymous",@@ -1118,6 +1127,7 @@ def _foreign_bucket_allows(owner_account: str, bucket_name: str, key: str,action=action,resource_arn=f"{resource}/{key}" if key else resource,region=get_region(),+ service_context={k.lower(): v for k, v in service_context.items()},)if evaluate_resource_policy(policy, ctx).decision == "Allow":return True@@ -1292,8 +1302,12 @@ def _apply_bucket_scope(method: str, bucket: str, key: str, headers: dict,if owner is None:return Nonefrom ministack.app import AUTH- if AUTH and not internal and not _request_access_key(method, key, headers, query_params, body):- if not _foreign_bucket_allows(owner, bucket, key, method, query_params, ""):+ anonymous = AUTH and not internal and not _request_access_key(method, key, headers, query_params, body)+ source_denied = _copy_source_denied(headers, "" if anonymous else get_account_id(), anonymous, internal)+ if source_denied is not None:+ return source_denied+ if anonymous:+ if not _foreign_bucket_allows(owner, bucket, key, method, query_params, "", headers):return _error("AccessDenied", "Access Denied", 403, f"/{bucket}/{key}" if key else f"/{bucket}")set_request_account_id(owner)return None@@ -1308,12 +1322,29 @@ def _apply_bucket_scope(method: str, bucket: str, key: str, headers: dict,# The caller is the owner; the credential just was not in a header.set_request_account_id(owner)return None- if not _foreign_bucket_allows(owner, bucket, key, method, query_params, access_key and caller):+ if not _foreign_bucket_allows(owner, bucket, key, method, query_params, access_key and caller, headers):return _error("AccessDenied", "Access Denied", 403, f"/{bucket}/{key}" if key else f"/{bucket}")set_request_account_id(owner)return None+def _copy_source_denied(headers: dict, caller: str, anonymous: bool, internal: bool):+ """AccessDenied when a copy reads a source object its caller may not read in another account's bucket."""+ source = headers.get("x-amz-copy-source", "")+ if internal or not source:+ return None+ src, _, query = source.partition("?")+ src_bucket, _, src_key = url_unquote(src).lstrip("/").partition("/")+ src_owner = _bucket_owner_account(src_bucket)+ if src_owner is None or (not anonymous and src_owner == caller):+ return None+ version = _parse_qs(query).get("versionId")+ if _foreign_bucket_allows(src_owner, src_bucket, src_key, "GET", {"versionId": version} if version else {},+ caller):+ return None+ return _error("AccessDenied", "Access Denied", 403, f"/{src_bucket}/{src_key}")++def _ensure_bucket(name: str):return _buckets.get(name)@@ -2893,9 +2924,80 @@ def _get_bucket_policy(name: str):return 200, {"Content-Type": "application/json"}, policy.encode("utf-8")+# Condition keys whose fixed value makes a statement non-public, per the S3 "meaning of public".+_NON_PUBLIC_CONDITION_KEYS = {+ "aws:principalorgid", "aws:principalaccount", "aws:principalarn", "aws:sourceip", "aws:sourcearn",+ "aws:sourcevpc", "aws:sourcevpce", "aws:sourceowner", "aws:sourceaccount", "aws:userid",+ "s3:dataaccesspointarn", "s3:dataaccesspointaccount",+}+# Operators that narrow access to the values they name; negated, Null and ForAllValues ones do not.+_NARROWING_OPERATORS = {+ "stringequals", "stringequalsignorecase", "stringlike", "arnequals", "arnlike", "ipaddress",+ "foranyvalue:stringequals", "foranyvalue:stringequalsignorecase", "foranyvalue:stringlike",+ "foranyvalue:arnequals", "foranyvalue:arnlike",+}+++def _fixed_condition_value(key: str, value: str) -> bool:+ if key == "s3:dataaccesspointarn":+ # A wildcard access point name with a fixed account still delegates to that account only.+ parts = value.split(":")+ return len(parts) >= 6 and parts[4].isdigit() and not any(c in ":".join(parts[:5]) for c in "*?")+ if any(c in value for c in "*?") or "${" in value:+ return False+ if key == "aws:sourceip":+ try:+ net = ipaddress.ip_network(value, strict=False)+ except ValueError:+ return False+ return net.is_private or net.prefixlen >= (8 if net.version == 4 else 32)+ return True+++def _statement_is_public(statement: dict) -> bool:+ """Whether an Allow statement grants access the S3 Block Public Access rules count as public."""+ if statement.get("Effect") != "Allow":+ return False+ if "NotPrincipal" in statement:+ return True+ principal = statement.get("Principal")+ if isinstance(principal, dict):+ aws = principal.get("AWS", [])+ aws = aws if isinstance(aws, list) else [aws]+ if not any("*" in str(p) for p in aws):+ return False+ elif principal != "*":+ return False+ conditions = statement.get("Condition") or {}+ if not isinstance(conditions, dict):+ return True+ for operator, keys in conditions.items():+ if str(operator).lower().removesuffix("ifexists") not in _NARROWING_OPERATORS or not isinstance(keys, dict):+ continue+ for key, values in keys.items():+ values = values if isinstance(values, list) else [values]+ if str(key).lower() in _NON_PUBLIC_CONDITION_KEYS and values and all(+ _fixed_condition_value(str(key).lower(), str(v)) for v in values):+ return False+ return True+++def _policy_is_public(policy_text: str) -> bool:+ try:+ statements = json.loads(policy_text).get("Statement", [])+ except (ValueError, AttributeError):+ return False+ statements = [statements] if isinstance(statements, dict) else statements+ return any(isinstance(s, dict) and _statement_is_public(s) for s in statements)++def _put_bucket_policy(name: str, body: bytes):if name not in _buckets:return _no_such_bucket(name)+ if _public_access_blocked(get_account_id(), name, "BlockPublicPolicy") and _policy_is_public(+ body.decode("utf-8", errors="replace")):+ return _error("AccessDenied",+ "public policies are prevented by the BlockPublicPolicy setting in S3 Block Public Access.", 403)_bucket_policies[name] = body.decode("utf-8")return 204, {}, b""diff --git a/ministack/services/s3tables.py b/ministack/services/s3tables.pyindex 4d0f6932..55b73088 100644--- a/ministack/services/s3tables.py+++ b/ministack/services/s3tables.py@@ -690,12 +690,12 @@ def _in_bucket(bucket_arn: str, bucket_filter) -> bool:def _iceberg_allows_cross_region(headers, query_params=None):- """Whether a call names no signing region; under AUTH a presigned call names it in its query, as checks read it."""- if query_params and "X-Amz-Credential" in query_params:- from ministack.app import AUTH+ """Whether a call names no signing region; under AUTH any call that names a key is held to its region, as checks are."""+ from ministack.app import AUTH+ from ministack.core.router import extract_access_key_id- if AUTH:- return False+ if AUTH and extract_access_key_id(headers, query_params or {}):+ return Falsereturn _SIGV4_CREDENTIAL_REGION_RE.search(headers.get("authorization", "")) is Nonediff --git a/tests/conftest.py b/tests/conftest.pyindex af1cc243..9f26bcce 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -187,6 +187,17 @@ def iam_user(auth_enabled):yield create+def second_access_key(user):+ """A second access key of an ``iam_user`` user, to sign raw requests with; deleted on exit."""+ iam = make_client("iam")+ key = iam.create_access_key(UserName=user.name)["AccessKey"]+ try:+ yield key["AccessKeyId"], key["SecretAccessKey"]+ finally:+ iam.delete_access_key(UserName=user.name, AccessKeyId=key["AccessKeyId"])++def inprocess_iam_user(identity_policy=None):"""An in-process IAM user with an access key in the default account: ``((key id, secret), arn)``."""from ministack.core.responses import get_account_id, request_scopediff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.pyindex 0010c8fd..53f97b1c 100644--- a/tests/test_apigatewayv1.py+++ b/tests/test_apigatewayv1.py@@ -13,7 +13,7 @@ import boto3import pytestimport yamlfrom botocore.exceptions import ClientError-from conftest import inprocess_iam_user, make_client, routed_request+from conftest import inprocess_iam_user, make_client, routed_request, second_access_keyfrom ministack.core.responses import set_request_regionfrom ministack.services import apigateway_v1@@ -52,6 +52,21 @@ def test_apigwv1_get_rest_apis(apigw_v1):apigw_v1.delete_rest_api(restApiId=id1)apigw_v1.delete_rest_api(restApiId=id2)+def test_apigwv1_rest_api_reports_status_and_root_resource(apigw_v1):+ """Every RestApi response carries apiStatus AVAILABLE and the id of its / resource, which Terraform waits on."""+ created = apigw_v1.create_rest_api(name="v1-status-test")+ api_id = created["id"]+ try:+ root_id = next(r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")+ updated = apigw_v1.update_rest_api(+ restApiId=api_id, patchOperations=[{"op": "replace", "path": "/description", "value": "d"}])+ listed = next(a for a in apigw_v1.get_rest_apis()["items"] if a["id"] == api_id)+ for api in (created, apigw_v1.get_rest_api(restApiId=api_id), listed, updated):+ assert (api["apiStatus"], api["rootResourceId"]) == ("AVAILABLE", root_id)+ finally:+ apigw_v1.delete_rest_api(restApiId=api_id)++def test_apigwv1_get_account_defaults_and_update_roundtrip(apigw_v1):"""GetAccount returns AWS-shaped defaults; UpdateAccount with /cloudwatchRoleArnpatch op round-trips. Single test to avoid cross-test state bleed on the@@ -1355,17 +1370,6 @@ def test_apigwv1_execute_aws_iam_requires_auth_header(apigw_v1, lam):lam.delete_function(FunctionName=fname)-def _second_access_key(user):- """A second access key of an ``iam_user`` user, to sign raw requests with; deleted on exit."""- iam = make_client("iam")- key = iam.create_access_key(UserName=user.name)["AccessKey"]- try:- yield key["AccessKeyId"], key["SecretAccessKey"]- finally:- iam.delete_access_key(UserName=user.name, AccessKeyId=key["AccessKeyId"])--def _signed_rest_get(url, key, secret, *, session=False, header=False, expires=300, skew=0):"""Status and x-amzn-ErrorType of a GET signed by botocore for execute-api, in its query string by default."""import datetime as dt@@ -1423,7 +1427,7 @@ def test_apigwv1_aws_iam_presigned_call_contract(auth_enabled, iam_user, apigw_vpolicy = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["execute-api:Invoke", "sts:GetSessionToken"], "Resource": "*"}]}args, strict, permissive = _REST_SIGNED_CASES[case]- with _second_access_key(iam_user(policy=policy)) as (key, secret):+ with second_access_key(iam_user(policy=policy)) as (key, secret):args = {"key": key, "secret": secret, **args}answer = _signed_rest_get(f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/p/",args.pop("key"), args.pop("secret"), **args)diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.pyindex 19eace35..15704269 100644--- a/tests/test_apigatewayv2.py+++ b/tests/test_apigatewayv2.py@@ -2,7 +2,6 @@import asyncioimport base64-import contextlibimport ioimport jsonimport os@@ -24,8 +23,8 @@ from conftest import (ENDPOINT,LoopProbe,concurrent_burst,- make_client,make_probe_lambda,+ second_access_key,)from ministack.core.responses import get_account_id, get_region, set_request_account_id, set_request_region@@ -3269,17 +3268,6 @@ _WS_IAM_POLICY = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["execute-api:Invoke", "sts:GetSessionToken"], "Resource": "*"}]}-def _second_access_key(user):- """A second access key of an ``iam_user`` user, to sign raw requests with; deleted on exit."""- iam = make_client("iam")- key = iam.create_access_key(UserName=user.name)["AccessKey"]- try:- yield key["AccessKeyId"], key["SecretAccessKey"]- finally:- iam.delete_access_key(UserName=user.name, AccessKeyId=key["AccessKeyId"])--def _signed_ws_connect(host, key, secret, *, session=False, token=None, token_after=False, header=False,expires=3600, skew=0, drop=""):"""Path and headers of a GET /prod handshake signed by botocore for execute-api."""@@ -3350,7 +3338,7 @@ def test_ws_connect_aws_iam_handshake_signature_contract(auth_enabled, iam_user,apigw.create_stage(ApiId=api_id, StageName="prod")args, message = _WS_CONNECT_CASES[case]host = f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"- with _second_access_key(iam_user(policy=_WS_IAM_POLICY)) as (key, secret):+ with second_access_key(iam_user(policy=_WS_IAM_POLICY)) as (key, secret):args = {"key": key, "secret": secret, **args}path, headers = _signed_ws_connect(host, args.pop("key"), args.pop("secret"), **args)status, body = _ws_handshake(api_id, path, headers)diff --git a/tests/test_appsync.py b/tests/test_appsync.pyindex 24868346..a8fcf376 100644--- a/tests/test_appsync.py+++ b/tests/test_appsync.py@@ -2789,3 +2789,38 @@ def test_appsync_cfn_schema_lands_in_the_schema_store():assert _appsync._schemas.get(api_id) is None_appsync._delete_graphql_api(api_id)++[email protected]_contract+def test_appsync_aws_iam_api_refuses_an_unverifiable_signature_contract(auth_enabled, appsync):+ """A SigV4 header the server cannot verify is no AWS_IAM credential."""+ api_id = appsync.create_graphql_api(name="iam-unverifiable", authenticationType="AWS_IAM")["graphqlApi"]["apiId"]+ try:+ appsync.start_schema_creation(apiId=api_id, definition=b"type Query { hello: String }")+ req = urllib.request.Request(f"{_ENDPOINT}/v1/apis/{api_id}/graphql", data=b'{"query": "{ hello }"}',+ method="POST", headers={"Content-Type": "application/json",+ "Authorization": "AWS4-HMAC-SHA256 garbage"})+ try:+ with urllib.request.urlopen(req, timeout=10) as resp:+ status = resp.status+ except urllib.error.HTTPError as exc:+ status = exc.code+ assert status in ((401, 403) if auth_enabled else (200,))+ finally:+ appsync.delete_graphql_api(apiId=api_id)++[email protected]("payload", [{"query": 123}, {"query": "{ hello }", "variables": "x"}], ids=["query", "variables"])+def test_appsync_graphql_refuses_malformed_request_members(appsync, payload):+ api_id = appsync.create_graphql_api(name="gql-members", authenticationType="API_KEY")["graphqlApi"]["apiId"]+ appsync.start_schema_creation(apiId=api_id, definition=b"type Query { hello: String }")+ key = appsync.create_api_key(apiId=api_id)["apiKey"]["id"]+ try:+ req = urllib.request.Request(f"{_ENDPOINT}/v1/apis/{api_id}/graphql", data=json.dumps(payload).encode(),+ method="POST", headers={"Content-Type": "application/json", "x-api-key": key})+ with pytest.raises(urllib.error.HTTPError) as exc:+ urllib.request.urlopen(req, timeout=10)+ assert exc.value.code == 400+ assert json.loads(exc.value.read())["errors"][0]["errorType"] == "MalformedHttpRequestException"+ finally:+ appsync.delete_graphql_api(apiId=api_id)diff --git a/tests/test_cloudwatch.py b/tests/test_cloudwatch.pyindex 1e5025bf..b44cfe99 100644--- a/tests/test_cloudwatch.py+++ b/tests/test_cloudwatch.py@@ -747,7 +747,13 @@ def test_cloudwatch_put_composite_alarm_validates_rule(cw):cw.put_composite_alarm(AlarmName=f"{p}bad", AlarmRule=rule)assert exc.value.response["Error"]["Code"] == "ValidationError"assert exc.value.response["Error"]["Message"] == message+ with pytest.raises(ClientError) as exc:+ cw.put_composite_alarm(AlarmName=f"{p}bad", AlarmRule="(" * 2000 + "TRUE" + ")" * 2000)+ assert exc.value.response["Error"]["Code"] == "ValidationError"assert cw.describe_alarms(AlarmNames=[f"{p}bad"], AlarmTypes=["CompositeAlarm"])["CompositeAlarms"] == []+ # A long flat chain within the 10240-character limit is not nesting.+ cw.put_composite_alarm(AlarmName=f"{p}chain", AlarmRule=" AND ".join(["TRUE"] * 1100))+ cw.delete_alarms(AlarmNames=[f"{p}chain"])finally:cw.delete_alarms(AlarmNames=[a])diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex cd44129c..da08056e 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -1519,9 +1519,8 @@ def test_cognito_get_id_checks_logins(auth_enabled, cognito_idp, cognito_identit]:result = ctx.call("get_id", IdentityPoolId=ctx.pool, Logins=logins)assert result == ("NotAuthorizedException", message) if auth_enabled else "IdentityId" in result- # With AUTH a login that has an identity gets that identity back; without it every GetId makes a new one.- found = ctx.call("get_id", IdentityPoolId=ctx.pool, Logins={provider: tokens["u1"]})["IdentityId"]- assert (found == ctx.u1) == auth_enabled+ # A login that has an identity gets that identity back.+ assert ctx.call("get_id", IdentityPoolId=ctx.pool, Logins={provider: tokens["u1"]})["IdentityId"] == ctx.u1@pytest.mark.auth_contract@@ -1534,12 +1533,11 @@ def test_cognito_identity_without_login_takes_one(auth_enabled, cognito_idp, coglogins = ctx.call("describe_identity", IdentityId=identity_id).get("Logins", [])found = ctx.call("get_id", IdentityPoolId=ctx.pool, Logins={provider: tokens[user]})["IdentityId"]without_logins = ctx.call("get_credentials_for_identity", IdentityId=identity_id)+ assert (logins, found) == ([provider], identity_id)if auth_enabled:- assert (logins, found) == ([provider], identity_id)assert without_logins == ("NotAuthorizedException", f"Access to Identity '{identity_id}' is forbidden.")else:- assert (logins, without_logins["IdentityId"]) == ([], identity_id)- assert found != identity_id+ assert without_logins["IdentityId"] == identity_id@pytest.mark.auth_contract@@ -1552,18 +1550,16 @@ def test_cognito_identity_without_login_merges_into_the_logins_identity(auth_enaidentity_id = ctx.call("get_id", IdentityPoolId=ctx.pool)["IdentityId"]result = ctx.call(action, IdentityId=identity_id, Logins={provider: tokens[user]})logins = ctx.call("describe_identity", IdentityId=identity_id)["Logins"]- if not auth_enabled:- assert (result["IdentityId"], logins) == (identity_id, [])- continue# The call answers for the identity that holds the login and disables the caller's.assert (result["IdentityId"], logins) == (holder, ["DISABLED", "us-east-1"])if action == "get_open_id_token":assert _decode_jwt_claims(result["Token"])["sub"] == holderassert ctx.call(action, IdentityId=identity_id, Logins={provider: tokens[user]})["IdentityId"] == holder- assert ctx.call(action, IdentityId=identity_id) == (- "NotAuthorizedException", f"Access to Identity '{identity_id}' is forbidden.")- assert ctx.call(action, IdentityId=identity_id, Logins={provider: tokens["u2"]}) == (- "NotAuthorizedException", mismatch)+ if auth_enabled:+ assert ctx.call(action, IdentityId=identity_id) == (+ "NotAuthorizedException", f"Access to Identity '{identity_id}' is forbidden.")+ assert ctx.call(action, IdentityId=identity_id, Logins={provider: tokens["u2"]}) == (+ "NotAuthorizedException", mismatch)listed = {hide: [i["IdentityId"] for i in ctx.call("list_identities", IdentityPoolId=ctx.pool, MaxResults=60, HideDisabled=hide)["Identities"]]for hide in (False, True)}@@ -1593,20 +1589,18 @@ def test_cognito_identity_merges_the_identities_holding_its_logins(auth_enabled,only_new_login = ctx.call("get_credentials_for_identity", IdentityId=u3, Logins={provider_b: tokens["b5"]})u5, b6 = get_id({provider: tokens["u5"]}), get_id({provider_b: tokens["b6"]})both_held = get_id({provider: tokens["u5"], provider_b: tokens["b6"]})- if not auth_enabled:- assert (logins_of(ctx.u1), logins_of(held_b)) == ([provider], [provider_b])- assert only_new_login["IdentityId"] == u3- assert both_held not in (u5, b6)- return# The caller keeps its identity, takes the other identity's logins and disables it.assert (logins_of(ctx.u1), logins_of(held_b)) == (sorted([provider, provider_b]), ["DISABLED", "us-east-1"])assert get_id({provider_b: tokens["b"]}) == ctx.u1assert ctx.call("get_credentials_for_identity", IdentityId=held_b,Logins={provider_b: tokens["b"]})["IdentityId"] == ctx.u1- # An identity with a login needs one of its own; a new login next to it is linked.- assert only_new_login == (- "NotAuthorizedException",- "Logins don't match. Please include at least one valid login for this identity or identity pool.")+ # Under AUTH an identity with a login needs one of its own; a new login next to it is linked.+ if auth_enabled:+ assert only_new_login == (+ "NotAuthorizedException",+ "Logins don't match. Please include at least one valid login for this identity or identity pool.")+ else:+ assert only_new_login["IdentityId"] == u3result = ctx.call("get_credentials_for_identity", IdentityId=u3,Logins={provider: tokens["u3"], provider_b: tokens["b5"]})assert (result["IdentityId"], logins_of(u3)) == (u3, sorted([provider, provider_b]))@@ -12038,3 +12032,32 @@ def test_cognito_inbound_federation_trigger_unconfigured_pool_keeps_idp_attributuser = cognito_idp.admin_get_user(UserPoolId=pid, Username="TestSAML_plain-name-id")attrs = {a["Name"]: a["Value"] for a in user["UserAttributes"]}assert attrs["email"] == "[email protected]"++[email protected]_contract+def test_cognito_unsupported_login_and_forged_refresh_token_contract(auth_enabled, cognito_idp, cognito_identity):+ """A linked identity answers to no unsupported provider, and a refresh token's signature is checked."""+ ctx = _identity_logins(cognito_idp, cognito_identity)+ result = ctx.call("get_credentials_for_identity", IdentityId=ctx.u1, Logins={"made.up": "x"})+ if auth_enabled:+ assert result == ("NotAuthorizedException", "Token is not from a supported provider of this identity pool.")+ else:+ assert result["IdentityId"] == ctx.u1++ pid = cognito_idp.create_user_pool(PoolName="ForgedRefresh")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(UserPoolId=pid, ClientName="app", ExplicitAuthFlows=[+ "ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"])["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="victim", MessageAction="SUPPRESS")+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="victim", Password="Passw0rd!", Permanent=True)+ refresh = cognito_idp.initiate_auth(ClientId=cid, AuthFlow="USER_PASSWORD_AUTH", AuthParameters={+ "USERNAME": "victim", "PASSWORD": "Passw0rd!"})["AuthenticationResult"]["RefreshToken"]+ header, payload, _signature = refresh.split(".")+ claims = json.loads(base64.urlsafe_b64decode(payload + "=="))+ forged_payload = base64.urlsafe_b64encode(json.dumps({**claims, "origin_jti": "forged"}).encode()).decode().rstrip("=")+ forged = f"{header}.{forged_payload}.AAAA"+ if auth_enabled:+ with pytest.raises(ClientError) as exc:+ cognito_idp.initiate_auth(ClientId=cid, AuthFlow="REFRESH_TOKEN_AUTH", AuthParameters={"REFRESH_TOKEN": forged})+ assert exc.value.response["Error"]["Message"] == "Invalid Refresh Token"+ assert cognito_idp.initiate_auth(ClientId=cid, AuthFlow="REFRESH_TOKEN_AUTH", AuthParameters={+ "REFRESH_TOKEN": refresh})["AuthenticationResult"]["AccessToken"]diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex b487490e..2550c438 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -2797,14 +2797,24 @@ class TestResourceArn:async def send(message):sent.append(message)- scope = {"type": "websocket", "path": "/prod", "query_string": query.encode(), "headers": [],+ scope = {"type": "websocket", "path": "/prod", "query_string": query.encode(),+ "headers": [(b"host", b"d9506af4.execute-api.localhost")],"extensions": {"websocket.http.response": {}}}asyncio.run(apigw_svc.handle_websocket(scope, receive, send, "d9506af4"))return sent[0].get("status"), json.loads(sent[1]["body"])["message"] if len(sent) > 1 else None+ def presigned_query():+ from botocore.auth import SigV4QueryAuth+ from botocore.awsrequest import AWSRequest+ from botocore.credentials import Credentials++ request = AWSRequest(method="GET", url="https://d9506af4.execute-api.localhost/prod")+ SigV4QueryAuth(Credentials(fake_key, "s"), "execute-api", "eu-central-1", 300).add_auth(request)+ return request.url.split("?", 1)[1]+try:unsigned = handshake("")- signed = handshake(f"X-Amz-Credential={fake_key}%2F20260101%2Feu-central-1%2Fexecute-api%2Faws4_request")+ signed = handshake(presigned_query())finally:iam_svc._access_keys.pop(fake_key, None)iam_svc._users.pop("ws-user", None)@@ -6231,3 +6241,72 @@ def test_write_get_object_response_needs_its_iam_action(monkeypatch):"POST", "/WriteGetObjectResponse", headers, b"", {}, "rid"))[0]assert seen["action"] == "s3-object-lambda:WriteGetObjectResponse"assert status == 400++[email protected]_contract+def test_unverifiable_credentials_are_refused_contract(auth_enabled, iam_user):+ """A credential this server cannot verify never acts as its key's user: another algorithm, SigV2, no Credential."""+ import urllib.error+ import urllib.request+ import uuid++ from conftest import ENDPOINT, second_access_key++ user = iam_user(policy={"Version": "2012-10-17", "Statement": [+ {"Effect": "Allow", "Action": "sqs:CreateQueue", "Resource": "*"}]})++ def create_queue(authorization, query=""):+ body = f"Action=CreateQueue&QueueName=unverifiable-{uuid.uuid4().hex[:8]}&Version=2012-11-05".encode()+ request = urllib.request.Request(f"{ENDPOINT}/{query}", data=body, method="POST", headers={+ "Content-Type": "application/x-www-form-urlencoded", "Authorization": authorization})+ try:+ with urllib.request.urlopen(request, timeout=10) as resp:+ return resp.status+ except urllib.error.HTTPError as exc:+ return exc.code++ with second_access_key(user) as (key, _secret):+ scope = f"{key}/20261019/us-east-1/sqs/aws4_request"+ for authorization, query in (+ (f"AWS4-HMAC-SHA512 Credential={scope}, SignedHeaders=host, Signature=00", ""),+ (f"AWS {key}:bogus", ""),+ ("AWS4-HMAC-SHA256 SignedHeaders=host, Signature=00", ""),+ ("AWS4-HMAC-SHA256 SignedHeaders=host, Signature=00", f"?X-Amz-Credential={scope.replace('/', '%2F')}"),+ ):+ status = create_queue(authorization, query)+ assert status >= 400 if auth_enabled else status == 200, (authorization, query)++[email protected]_contract+def test_s3_sigv2_signatures_are_verified_contract(auth_enabled, iam_user):+ """SigV2 header and query signatures are checked for an IAM user, and still work when they are right."""+ import urllib.error+ import urllib.request+ import uuid++ import boto3+ from botocore.config import Config+ from conftest import ENDPOINT, make_client, second_access_key++ bucket = f"sigv2-{uuid.uuid4().hex[:8]}"+ admin = make_client("s3")+ admin.create_bucket(Bucket=bucket)+ admin.put_object(Bucket=bucket, Key="k", Body=b"v")+ user = iam_user(policy={"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]})+ try:+ with second_access_key(user) as (key, secret):+ v2 = boto3.client("s3", endpoint_url=ENDPOINT, region_name="us-east-1", aws_access_key_id=key,+ aws_secret_access_key=secret, config=Config(signature_version="s3"))+ assert v2.get_object(Bucket=bucket, Key="k")["Body"].read() == b"v"+ url = v2.generate_presigned_url("get_object", Params={"Bucket": bucket, "Key": "k"})+ with urllib.request.urlopen(url, timeout=10) as resp:+ assert resp.status == 200+ try:+ with urllib.request.urlopen(url.replace("Signature=", "Signature=AA"), timeout=10) as resp:+ status = resp.status+ except urllib.error.HTTPError as exc:+ status = exc.code+ assert status == (403 if auth_enabled else 200)+ finally:+ admin.delete_object(Bucket=bucket, Key="k")+ admin.delete_bucket(Bucket=bucket)diff --git a/tests/test_iot_data.py b/tests/test_iot_data.pyindex cea2521d..3097f863 100644--- a/tests/test_iot_data.py+++ b/tests/test_iot_data.py@@ -12,7 +12,6 @@ bridge layer.from __future__ import annotationsimport base64-import contextlibimport io as _ioimport jsonimport os@@ -33,7 +32,7 @@ import boto3import pytestfrom botocore.config import Configfrom botocore.exceptions import ClientError-from conftest import iot_test_ca, make_client, patch_endpoint_dns, sqs_policy_allow_sns+from conftest import iot_test_ca, patch_endpoint_dns, second_access_key, sqs_policy_allow_snsENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")@@ -963,17 +962,6 @@ _IOT_WS_POLICY = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["iot:*", "sts:GetSessionToken"], "Resource": "*"}]}-def _second_access_key(user):- """A second access key of an ``iam_user`` user, to sign raw requests with; deleted on exit."""- iam = make_client("iam")- key = iam.create_access_key(UserName=user.name)["AccessKey"]- try:- yield key["AccessKeyId"], key["SecretAccessKey"]- finally:- iam.delete_access_key(UserName=user.name, AccessKeyId=key["AccessKeyId"])--def _iot_ws_host() -> str:parsed = urlparse(ENDPOINT)return f"prefix-ats.iot.us-east-1.{parsed.hostname or 'localhost'}:{parsed.port or 4566}"@@ -1055,7 +1043,7 @@ _IOT_WS_CASES = { # case: (signing arguments, refused under AUTH=true)def test_iot_ws_handshake_signature_contract(auth_enabled, iam_user, case):"""Under AUTH=true an MQTT-over-WebSocket upgrade signed with an IAM key is verified like a request."""args, refused = _IOT_WS_CASES[case]- with _second_access_key(iam_user(policy=_IOT_WS_POLICY)) as (key, secret):+ with second_access_key(iam_user(policy=_IOT_WS_POLICY)) as (key, secret):args = {"key": key, "secret": secret, **args}status, content_type, body = _iot_ws_upgrade(*_signed_mqtt_upgrade(args.pop("key"), args.pop("secret"),**args))@@ -1146,7 +1134,7 @@ def test_iot_ws_session_iam_policy_contract(auth_enabled, iam_user, case, signerelse:frames.append(_make_publish(f"{run}/{name}", b"{}", qos=1, packet_id=2, protocol_level=level,retain=kind == "retain"))- with _second_access_key(iam_user(policy={"Version": "2012-10-17", "Statement": statements})) as (key, secret):+ with second_access_key(iam_user(policy={"Version": "2012-10-17", "Statement": statements})) as (key, secret):if signer == "root":key, secret = "test", "test"query, _ = _signed_mqtt_upgrade(key, secret, session=signer == "session",@@ -1156,6 +1144,29 @@ def test_iot_ws_session_iam_policy_contract(auth_enabled, iam_user, case, signerassert sorted(names) == sorted(n.replace(" t/", f" {run}/t/") for n in expected)[email protected]_contract[email protected]("policy_account, connects", [("111111111111", True), ("000000000000", False)],+ ids=["own-account", "default-account"])+def test_iot_ws_session_runs_in_the_signers_account(auth_enabled, policy_account, connects):+ """An IAM user of another account is authorized on its own account's ARNs, not the default account's."""+ iam = boto3.client("iam", endpoint_url=ENDPOINT, region_name="us-east-1",+ aws_access_key_id="111111111111", aws_secret_access_key="test")+ name = _unique("ws-acct")+ iam.create_user(UserName=name)+ iam.put_user_policy(UserName=name, PolicyName="p", PolicyDocument=json.dumps({+ "Version": "2012-10-17",+ "Statement": [{"Effect": "Allow", "Action": "iot:Connect", "Resource": f"arn:aws:iot:*:{policy_account}:*"}]}))+ key = iam.create_access_key(UserName=name)["AccessKey"]+ try:+ query, _ = _signed_mqtt_upgrade(key["AccessKeyId"], key["SecretAccessKey"])+ names = asyncio.run(_mqtt_over_signed_ws(query, [_make_connect(name, protocol_level=MQTT_311)]))+ finally:+ iam.delete_access_key(UserName=name, AccessKeyId=key["AccessKeyId"])+ iam.delete_user_policy(UserName=name, PolicyName="p")+ iam.delete_user(UserName=name)+ assert names == (["CONNACK 0x00", "PINGRESP"] if connects or not auth_enabled else [])++# ---------------------------------------------------------------------------# Device Shadow (GetThingShadow / UpdateThingShadow / DeleteThingShadow)# ---------------------------------------------------------------------------@@ -3381,6 +3392,7 @@ _RESERVED_FILTERS = {"$aws/things/some-thing/shadow/update/+": 0x01,"$aws/things/+/jobs/#": 0x01,"$aws/events/#": 0x01,+ "$share/consumer/sports/#": 0x01,"$aws/certificates/create/+/accepted": 0x01,"$aws/provisioning-templates/+/provision/json/rejected": 0x01,"$aws/device_location/some-thing/get_position_estimate/accepted": 0x01,diff --git a/tests/test_iot_jobs_data.py b/tests/test_iot_jobs_data.pyindex dcd54916..d121e896 100644--- a/tests/test_iot_jobs_data.py+++ b/tests/test_iot_jobs_data.py@@ -4872,3 +4872,19 @@ def test_jobs_mqtt_start_next_twice_rehands_in_progress_silently(iot_client, iotassert d2["status"] == "IN_PROGRESS"assert d2["statusDetails"] == {"step": "a"}assert d2["versionNumber"] == d1["versionNumber"]++[email protected]("details", [{"k": 1}, {"k": {"nested": "x"}}, {"k": ""}, False], ids=["number", "map", "empty", "false"])+def test_iot_jobs_update_refuses_status_details_that_is_not_a_string_map(iot_client, details):+ """statusDetails is a DetailsMap of non-empty strings; anything else is refused before the execution changes."""+ thing, job_id = _unique("jobs-thing"), _unique("job")+ try:+ thing_arn = _create_thing(iot_client, thing)+ iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)+ status, body = _raw_jobs_data("POST", f"/things/{thing}/jobs/{job_id}",+ {"status": "IN_PROGRESS", "statusDetails": details})+ assert status == 400 and body["__type"].endswith("InvalidRequestException")+ execution = iot_client.describe_job_execution(jobId=job_id, thingName=thing)["execution"]+ assert (execution["status"], execution["versionNumber"]) == ("QUEUED", 1)+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])diff --git a/tests/test_s3.py b/tests/test_s3.pyindex 626cdc05..c24aa834 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -1439,6 +1439,35 @@ def test_s3_public_access_block(s3):assert exc.value.response["Error"]["Code"] == "NoSuchPublicAccessBlockConfiguration"+def test_s3_block_public_policy_refuses_a_public_bucket_policy(s3):+ bkt = f"intg-s3-bpp-{_uuid_mod.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=bkt)++ def policy(**extra):+ return json.dumps({"Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject",+ "Resource": f"arn:aws:s3:::{bkt}/*", **extra}]})++ try:+ s3.put_bucket_policy(Bucket=bkt, Policy=policy())+ s3.put_public_access_block(Bucket=bkt, PublicAccessBlockConfiguration={+ "BlockPublicAcls": False, "IgnorePublicAcls": False,+ "BlockPublicPolicy": True, "RestrictPublicBuckets": False})+ # The policy set before the setting stays.+ assert json.loads(s3.get_bucket_policy(Bucket=bkt)["Policy"]) == json.loads(policy())+ for public in (policy(), policy(Condition={"StringLike": {"aws:SourceVpc": "vpc-*"}})):+ with pytest.raises(ClientError) as exc:+ s3.put_bucket_policy(Bucket=bkt, Policy=public)+ assert exc.value.response["Error"]["Code"] == "AccessDenied"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403+ s3.put_bucket_policy(Bucket=bkt, Policy=policy(+ Condition={"StringEquals": {"aws:SourceVpc": "vpc-91237329"}}))+ finally:+ s3.delete_public_access_block(Bucket=bkt)+ s3.delete_bucket_policy(Bucket=bkt)+ s3.delete_bucket(Bucket=bkt)++def test_s3_block_public_acls_refuses_setting_a_public_acl(s3):"""BlockPublicAcls refuses every call that sets a public ACL; private grants and IgnorePublicAcls alone pass."""import requests@@ -9419,6 +9448,18 @@ def test_s3_canned_acl_condition_contract(auth_enabled, iam_user, auth_conditionlambda: client.put_object(Bucket=bucket, Key=f"acl-{acl}", Body=b"x", **extra))[email protected]_contract+def test_s3_grant_header_condition_contract(auth_enabled, iam_user, auth_condition_bucket):+ """A bucket policy on s3:x-amz-grant-read sees the grant header of a PutObject."""+ user = iam_user(policy=_ALLOW_ALL_S3)+ bucket = auth_condition_bucket(user.arn, "s3:PutObject", {"Null": {"s3:x-amz-grant-read": "false"}})+ client = user.client("s3")+ _assert_s3_condition(auth_enabled, True, lambda: client.put_object(Bucket=bucket, Key="plain", Body=b"x"))+ grant = 'id="c4c1ede66af53448b93c283ce9448c4ba468c9432aa01d700d3878632f77d2d0"'+ _assert_s3_condition(auth_enabled, False,+ lambda: client.put_object(Bucket=bucket, Key="granted", Body=b"x", GrantRead=grant))++@pytest.mark.auth_contractdef test_s3_existing_object_tag_condition_contract(auth_enabled, iam_user, s3, auth_condition_bucket):"""A bucket policy on s3:ExistingObjectTag sees the tags of the object a GetObject or HeadObject reads."""@@ -9928,3 +9969,57 @@ def test_s3_bucket_config_enum_and_day_validation(s3):s3.put_bucket_encryption(Bucket=bucket, ServerSideEncryptionConfiguration={"Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "aws:kms:dsse"}}]})s3.delete_bucket(Bucket=bucket)++[email protected]_contract+def test_s3_anonymous_copy_source_and_policy_action_contract(auth_enabled, s3):+ """A public PutObject policy lets anonymous callers write, not read another bucket through a copy or delete."""+ secret, upload = f"anon-src-{uuid.uuid4().hex[:8]}", f"anon-dst-{uuid.uuid4().hex[:8]}"+ for bucket in (secret, upload):+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=secret, Key="c", Body=b"secret")+ s3.put_object(Bucket=upload, Key="kept", Body=b"kept")+ s3.put_bucket_policy(Bucket=upload, Policy=json.dumps({"Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Principal": "*", "Action": "s3:PutObject", "Resource": f"arn:aws:s3:::{upload}/*"}]}))+ try:+ assert requests.put(f"{ENDPOINT}/{upload}/plain", data=b"x").status_code == 200+ copy = requests.put(f"{ENDPOINT}/{upload}/loot", headers={"x-amz-copy-source": f"/{secret}/c"})+ delete = requests.delete(f"{ENDPOINT}/{upload}/kept")+ if auth_enabled:+ assert (copy.status_code, delete.status_code) == (403, 403)+ else:+ assert (copy.status_code, delete.status_code) == (200, 204)+ finally:+ s3.delete_bucket_policy(Bucket=upload)+ for bucket in (secret, upload):+ for item in s3.list_objects_v2(Bucket=bucket).get("Contents", []):+ s3.delete_object(Bucket=bucket, Key=item["Key"])+ s3.delete_bucket(Bucket=bucket)++[email protected]_contract+def test_s3_copy_source_in_the_query_string_is_authorized_contract(auth_enabled, iam_user, s3):+ """x-amz-copy-source hoisted into the query string is checked like the header."""+ from botocore.auth import S3SigV4Auth+ from botocore.awsrequest import AWSRequest+ from botocore.credentials import Credentials+ from conftest import second_access_key++ secret, upload = f"hoist-src-{uuid.uuid4().hex[:8]}", f"hoist-dst-{uuid.uuid4().hex[:8]}"+ for bucket in (secret, upload):+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=secret, Key="c", Body=b"secret")+ user = iam_user(policy={"Version": "2012-10-17", "Statement": [+ {"Effect": "Allow", "Action": "s3:PutObject", "Resource": f"arn:aws:s3:::{upload}/*"}]})+ try:+ with second_access_key(user) as (key, secret_key):+ url = f"{ENDPOINT}/{upload}/b?x-amz-copy-source=%2F{secret}%2Fc"+ request = AWSRequest(method="PUT", url=url, data=b"")+ S3SigV4Auth(Credentials(key, secret_key), "s3", "us-east-1").add_auth(request)+ status = requests.put(url, data=b"", headers=dict(request.headers)).status_code+ assert status == (403 if auth_enabled else 200)+ finally:+ for bucket in (secret, upload):+ for item in s3.list_objects_v2(Bucket=bucket).get("Contents", []):+ s3.delete_object(Bucket=bucket, Key=item["Key"])+ s3.delete_bucket(Bucket=bucket)diff --git a/tests/test_s3tables.py b/tests/test_s3tables.pyindex ffe6a00c..12602388 100644--- a/tests/test_s3tables.py+++ b/tests/test_s3tables.py@@ -427,6 +427,22 @@ def test_s3tables_iceberg_catalog_spans_control_plane_regions():west.delete_table_bucket(tableBucketARN=bucket_arn)[email protected]("headers, query, cross_region", [+ ({"authorization": "AWS AKIAEXAMPLE:sig"}, {}, False),+ ({}, {"x-amz-credential": ["AKIAEXAMPLE/20260101/us-west-2/s3tables/aws4_request"]}, False),+ ({"authorization": "AWS4-HMAC-SHA256 Credential=AKIAEXAMPLE/20260101/us-west-2/s3tables/aws4_request, "+ "SignedHeaders=host, Signature=abc"}, {}, False),+ ({}, {}, True),+], ids=["sigv2", "lowercase-query", "sigv4", "unsigned"])+def test_s3tables_iceberg_auth_holds_a_named_key_to_its_region(monkeypatch, headers, query, cross_region):+ """Under AUTH a call that names any key serves its own region, the one its checks resolve."""+ import ministack.app as app+ from ministack.services import s3tables++ monkeypatch.setattr(app, "AUTH", True)+ assert s3tables._iceberg_allows_cross_region(headers, query) is cross_region++def test_s3tables_iceberg_catalog_prefers_signed_region_for_duplicate_names():east = _make_s3tables_client(region_name="us-east-1")west = _make_s3tables_client(region_name="us-west-2")diff --git a/tests/test_ses.py b/tests/test_ses.pyindex d8621cda..b9ef82f5 100644--- a/tests/test_ses.py+++ b/tests/test_ses.py@@ -1970,3 +1970,33 @@ def test_ses_send_email_rejects_non_ascii_address(ses):ses.send_email(Source="[email protected]", Destination={"ToAddresses": ["[email protected]"]},Message={"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}})++[email protected]_contract+def test_ses_v2_target_header_route_is_authorized_contract(auth_enabled, iam_user):+ """SES v2 on a path without /v2/email, selected by the target header, is authorized like the prefixed call."""+ import urllib.error+ import urllib.request++ from botocore.auth import SigV4Auth+ from botocore.awsrequest import AWSRequest+ from botocore.credentials import Credentials+ from conftest import ENDPOINT, make_client, second_access_key++ name = f"tpl-{uuid4().hex[:8]}"+ sesv2 = make_client("sesv2")+ sesv2.create_email_template(TemplateName=name, TemplateContent={"Subject": "s", "Text": "t"})+ with second_access_key(iam_user()) as (key, secret):+ request = AWSRequest(method="DELETE", url=f"{ENDPOINT}/templates/{name}", headers={"x-amz-target": "sesv2"})+ SigV4Auth(Credentials(key, secret), "ses", "us-east-1").add_auth(request)+ try:+ with urllib.request.urlopen(urllib.request.Request(+ request.url, method="DELETE", headers=dict(request.headers)), timeout=10) as resp:+ status = resp.status+ except urllib.error.HTTPError as exc:+ status = exc.code+ if auth_enabled:+ assert status == 403+ sesv2.delete_email_template(TemplateName=name)+ else:+ assert status == 200