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.29 (#2239)
Nahuel Nucera3338e91c9ef8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 768224d9..df4c7c49 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,28 +7,27 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]-### Fixed-- **Cognito / API Gateway REST — OAuth scope refusals** — the client credentials token endpoint now rejects undefined custom scopes with HTTP 400 `invalid_scope`, and defined scopes the app client does not allow with HTTP 400 `invalid_grant`, instead of issuing a token after dropping them. Whitespace-only scope requests are rejected as malformed, and clients with no allowed scopes no longer inherit the user sign-in scope. A REST Cognito authorizer whose method scopes do not match the token now answers HTTP 401 `Unauthorized` through the `UNAUTHORIZED` gateway response instead of 403. Scope refusals and REST authorization follow official AWS documentation; empty-value and malformed-scope handling follow OAuth 2.0. These changes have not been measured against a real AWS account.-- **S3 — signed browser POST policies** — SigV4 and legacy SigV2 form uploads now verify their policy signature and registered credentials, expiration, exact and prefix conditions, field coverage and file-size bounds before writing. Under `AUTH=true` the form signer also needs the object write permissions. Registered IAM keys retain the bucket owner's account scope. Anonymous form behavior is unchanged.-- **CloudWatch Logs — ordered, bounded event reads** — keep stream histories chronological for API, Lambda, CodeBuild and DynamoDB import logs, including late batches and restored snapshots. `FilterLogEvents` seeks to time bounds and merges stream cursors until its limit is reached instead of collecting, filtering and sorting every event; newer events in an earlier-scanned stream cannot displace older matches. Equal timestamps retain stream-selection and arrival order, `GetLogEvents` reads late arrivals chronologically with tokens anchored to returned events, so pages neither repeat nor skip events on the unread side, and Live Tail still receives the exact newly ingested batch.--- **Lambda — conditional function and alias updates** — `UpdateFunctionCode`, `UpdateFunctionConfiguration`, and `UpdateAlias` reject a stale `RevisionId` with `PreconditionFailedException` (412) before changing state or invalidating workers. Competing updates to the same revision are serialized per function or alias, while unrelated resources remain independent.-- **SQS — empty policy updates** — `SetQueueAttributes` removes `Policy`, `RedrivePolicy`, and `RedriveAllowPolicy` when explicitly set to an empty string, so Terraform policy deletion succeeds and subsequent attribute reads omit the removed policy. Invalid nonempty redrive policies and numeric attributes are still rejected before any attributes change.-- **AppSync Events event payloads**: deliver each WebSocket data frame with a string `event` field, matching observed AWS behavior. HTTP and WebSocket publish batches still produce one frame per event.-- **CloudFront — function status follows publish and association** — `DescribeFunction` and `ListFunctions` reported the `DEVELOPMENT` stage as `UNPUBLISHED` even after `PublishFunction`, so Terraform's `aws_cloudfront_function.status`, which reads that stage, never left `UNPUBLISHED`; once the current development version is published it now reports `UNASSOCIATED`, or `ASSOCIATED` while a distribution's cache behavior references the function, and an `UpdateFunction` makes it `UNPUBLISHED` again until the next publish. Contributed by @fabio-andre-rodrigues.-- **Step Functions — JSONata Fail and Wait fields are evaluated** — a JSONata Fail state raised its `Error` and `Cause` expressions as literal text, a JSONata Wait failed on a `Seconds` expression, ignored a `Timestamp` expression and dropped its `Output` and `Assign`, and JSONPath `ErrorPath`/`CausePath` were ignored; they are now evaluated, with AWS's `States.QueryEvaluationError` or `States.Runtime` for a result of the wrong type, a `Seconds` that is not a non-negative integer and an unparsable `Timestamp`.-- **S3 — presigned URLs keep AWS's time limits under `AUTH=true`** — an `X-Amz-Expires` over 604800 seconds or not a number, or a malformed `X-Amz-Date`, answers 400 `AuthorizationQueryParametersError`, and a URL dated more than 15 minutes ahead answers 403 `AccessDenied` `Request is not yet valid`, where they were served. Contributed by @iot-rocket.-- **Auth — credential failures in the service's protocol** — under `AUTH=true` an unknown, inactive or expired access key answered `UnrecognizedClientException` 403 from every service; it now gets the code, status and `Content-Type` AWS sends for the service's protocol, for example `InvalidClientTokenId` 403 from IAM and SQS, `UnrecognizedClientException` 400 from DynamoDB, `InvalidAccessKeyId` 403 from S3 and `AuthFailure` 401 from EC2. Contributed by @iot-rocket.-### Fixed-- **Step Functions — `ListExecutions` order and pagination** — executions came back oldest first, so `maxResults=1` returned the oldest, and `nextToken` was an offset; they now come back most recent first (running executions by `startDate`, the rest by `stopDate`), the token resumes after the last execution returned so one started between pages is not repeated, an unreadable token answers `InvalidToken` and `maxResults=0` uses the default, as on AWS.### Added-- **Managed Service for Apache Flink — control plane** — `kinesisanalyticsv2` applications for the `FLINK-*` runtimes: create, describe, update and delete, start and stop with the model's status transitions, snapshots, CloudWatch logging options and tags, per account and region. Updates bump `ApplicationVersionId` and the `ConditionalToken`, and a stale one returns `ConcurrentModificationException`. CloudFormation creates, updates and deletes `AWS::KinesisAnalyticsV2::Application`, `AWS::KinesisAnalyticsV2::ApplicationCloudWatchLoggingOption` and `AWS::Logs::LogStream`, so a CDK Flink stack deploys. Contributed by @Jolley71717.- **Managed Service for Apache Flink — job execution** — with Docker available, starting a `FLINK-1_19` or `FLINK-1_20` application runs its jar from MiniStack S3 in the official Apache Flink image (1.19.1 or 1.20.5, Java 11) with a JobManager and a TaskManager, its runtime properties at `/etc/flink/application_properties.json`, its configured parallelism and checkpointing, and its AWS calls pointed at MiniStack in the application's account. Snapshots are Flink savepoints, restores resume the job's state, and a job that fails to start returns the application to `READY`. Jars in `/opt/ministack/flink-lib` (for example a mounted `aws-kinesisanalytics-runtime`) are added to every cluster. Without Docker the control plane behaves as before. Contributed by @Jolley71717.- **S3 Access Points** — S3 Control `CreateAccessPoint`, `GetAccessPoint`, `ListAccessPoints`, `DeleteAccessPoint` and `Put`/`Get`/`DeleteAccessPointPolicy`. The bucket must be in the request's region, names are unique per account and region, and errors follow AWS (`AccessPointAlreadyOwnedByYou`, `NoSuchAccessPoint`). Requests through an access point ARN (`<name>-<account>.<host>`) or its `-s3alias` alias reach the bucket, including as a `CopyObject` source; signing for another region gets the bucket-region redirect with the access point's region. `DeleteBucket` refuses a bucket with access points. CloudFormation provisions `AWS::S3::AccessPoint`, and under `AUTH=true` each operation needs its `s3:` action. Contributed by @fabio-andre-rodrigues.- **S3 Object Lambda** — S3 Control `Create`/`Get`/`List`/`DeleteAccessPointForObjectLambda`, `Get`/`PutAccessPointConfigurationForObjectLambda` and the policy operations, with the supporting access point and Lambda in the same account and region. `GetObject` through an Object Lambda ARN or `--ol-s3` alias invokes the Lambda with the documented `getObjectContext` (a presigned `inputS3Url` through the supporting access point, `outputRoute`, `outputToken`) and returns what it writes with `WriteGetObjectResponse`. `HeadObject`, `ListObjects` and `ListObjectsV2` transformations return the Lambda's JSON result; operations without a transformation pass through; `Range` and `partNumber` need `AllowedFeatures`; Lambda failures map to `LambdaRuntimeError`, `LambdaResponseNotReceived`, `LambdaTimeout` and `LambdaNotFound`. CloudFormation provisions `AWS::S3ObjectLambda::AccessPoint` and `AccessPointPolicy`. AWS no longer onboards new Object Lambda customers, so the data plane follows the S3 user guide. Contributed by @fabio-andre-rodrigues.- **Lambda — `AWS_DISABLE_HOST_PREFIX_INJECTION=true` by default** — Lambda environments set it unless the function does, so boto3 in a handler reaches `WriteGetObjectResponse` without the `<route>.<host>` prefix, which doesn't resolve locally. SDKs that ignore the variable need their host-prefix injection turned off in client config. Contributed by @fabio-andre-rodrigues.+### Fixed+- **Cognito / API Gateway — OAuth scope refusals** — a client credentials grant that named a scope the client lacks, or one that doesn't exist, dropped it and issued a token; `/oauth2/token` now refuses the whole request with 400 `invalid_grant` or `invalid_scope`, and a REST API method whose authorization scopes match none in the access token answers 401 `Unauthorized` (the `UNAUTHORIZED` gateway response) instead of 403. Contributed by @gakuto-cw21.+- **S3 — browser POST policies are enforced** — a form upload was written whatever its policy said; an expired policy, a field that fails a condition or a field the policy doesn't cover now answers 403 `AccessDenied` (`Invalid according to Policy: …`), and under `AUTH=true` the SigV4 or SigV2 signature and the signer's `s3:PutObject` permission are checked. Contributed by @kinoh.+- **CloudWatch Logs — event order across streams and pages** — `FilterLogEvents` stopped at `limit` before sorting across streams, so a newer event could displace an older match; events now merge across streams by timestamp, then ingestion time, and `searchedLogStreams` is empty, as on AWS. `GetLogEvents` excludes events at `endTime`, and its tokens no longer repeat or skip events when late events arrive. Contributed by @kinoh.+- **Lambda — `RevisionId` on updates** — `UpdateFunctionCode`, `UpdateFunctionConfiguration` and `UpdateAlias` ignored `RevisionId`; a stale one now answers 412 `PreconditionFailedException` before anything changes. Contributed by @kinoh.+- **SQS — an empty policy removes it** — `SetQueueAttributes` with an empty `Policy` or `RedriveAllowPolicy` stored the empty string, and an empty `RedrivePolicy` was refused; each now removes the attribute, as Terraform's policy resources expect. Contributed by @kinoh.+- **AppSync Events — `event` is a string** — subscribers' `data` messages carried `event` as a one-element array; it is now the JSON-encoded string, as AWS sends it. Contributed by @edbramwell.+- **S3 — Object Lock is per version** — retention and legal holds were stored per key, so a lock on one version blocked permanent deletes of the key's other versions; they now belong to the version they were set on, `GetObjectRetention`, `PutObjectRetention` and the legal-hold calls take `versionId`, and a `DeleteObject` or `DeleteObjects` without a `VersionId` on a locked key adds a delete marker instead of answering 403. Reported by @bettiah.+- **S3 — Object Lock headers need an Object Lock bucket** — `PutObject` and browser POST uploads with `x-amz-object-lock-*` headers on a bucket created without Object Lock applied the lock; they now answer 400 `InvalidRequest` `Bucket is missing ObjectLockConfiguration`. Reported by @bettiah.+- **KMS — `ScheduleKeyDeletion` window** — a `PendingWindowInDays` outside 7–30 was accepted; it now answers `ValidationException` `PendingWindowInDays must be between 7 and 30`. Reported by @bettiah.+- **KMS — RSASSA-PSS salt** — signatures used a maximum-length salt; they now use a salt as long as the digest, as AWS does, and `Verify` expects the same. Reported by @bettiah.+- **KMS — RSA encryption algorithms** — `Encrypt` and `Decrypt` used OAEP SHA-256 whatever `EncryptionAlgorithm` named; they now use `RSAES_OAEP_SHA_1` or `RSAES_OAEP_SHA_256` as named, so a mismatched `Decrypt` answers `InvalidCiphertextException`, and an algorithm the key doesn't support answers `InvalidKeyUsageException`. Reported by @bettiah.+- **KMS — `Sign` and `Verify` input checks** — a digest of the wrong length or an algorithm the key spec doesn't support crashed with a 500; they now answer 400 `ValidationException` (`Digest is invalid length for algorithm …`) and `InvalidKeyUsageException`. Reported by @bettiah.+## [1.5.28] — 2026-10-16### Addeddiff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.pyindex 9b22097b..4535106f 100644--- a/ministack/services/cloudwatch_logs.py+++ b/ministack/services/cloudwatch_logs.py@@ -586,12 +586,7 @@ def _event_timestamp(event):def _append_log_events(stream, events):- """Keep chronological history and stable ties for every log producer.-- Chronological batches extend the existing array without copying history.- A late batch replaces it with a stable merge, leaving captured readers'- arrays intact. Readers capture their array and end bound under the lock.- """+ """Append events keeping the stream chronological; a late batch replaces the list with a stable merge."""if not events:returnordered = sorted(events, key=_event_timestamp)@@ -1222,14 +1217,7 @@ def _resolve_log_group_name(data):def _event_cursor(history, size, position, forward):- """Name a GetLogEvents boundary by the returned event beside it.-- The cursor is "<timestamp>:<k>", the k-th position within that timestamp's- run. Late events stay on their own side of the anchor, and equal-time- arrivals sort after their ties, so the boundary never shifts. A backward- boundary at the tail anchors on the last event, so later events stay- after it. "-" marks the head of the stream, or a boundary in an empty one.- """+ """GetLogEvents boundary as "<timestamp>:<k>" (k-th event of that timestamp), or "-" at the head."""anchor = position - 1 if forward or position == size else positionif not 0 <= anchor < size:return "-"@@ -1272,7 +1260,7 @@ def _get_log_events(data):history = _log_groups[group]["streams"][stream]["events"]size = len(history)lower = bisect_left(history, start_time, hi=size, key=_event_timestamp) if start_time is not None else 0- upper = bisect_right(history, end_time, lo=lower, hi=size, key=_event_timestamp) if end_time is not None else size+ upper = bisect_left(history, end_time, lo=lower, hi=size, key=_event_timestamp) if end_time is not None else sizeforward = start_from_headposition = lower if forward else upper@@ -1363,7 +1351,6 @@ def _filter_log_events(data):)events = []- searched = []ranges = []streams = _log_groups[group]["streams"]target_streams = stream_names if stream_names else list(streams.keys())@@ -1373,7 +1360,6 @@ def _filter_log_events(data):stream = streams.get(sn)if stream is None:continue- searched.append({"logStreamName": sn, "searchedCompletely": True})history = stream["events"]start = bisect_left(history, start_time, key=_event_timestamp) if start_time is not None else 0end = bisect_right(history, end_time, key=_event_timestamp) if end_time is not None else len(history)@@ -1381,7 +1367,7 @@ def _filter_log_events(data):# merge is stable across input streams and only pulls the next candidate.scanned = 0- for event, sn in heapq.merge(*ranges, key=lambda entry: entry[0]["timestamp"]):+ for event, sn in heapq.merge(*ranges, key=lambda entry: (entry[0]["timestamp"], entry[0].get("ingestionTime", 0))):if len(events) >= limit:breakscanned += 1@@ -1391,7 +1377,7 @@ def _filter_log_events(data):breaklogger.debug("FilterLogEvents streams=%d scanned=%d returned=%d limit=%s",len(ranges), scanned, len(events), limit)- return json_response({"events": events, "searchedLogStreams": searched})+ return json_response({"events": events, "searchedLogStreams": []})# ---------------------------------------------------------------------------diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 4490bdb3..88e0886a 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -792,8 +792,7 @@ def _granted_scopes(client: dict | None, requested: str | None, grant: str = "au"""The scopes a token-endpoint grant carries: the requested ones the client allows, or all it allows."""listed = (client or {}).get("AllowedOAuthScopes") or []if not listed and not requested:- # Only user sign-ins inherit the user-pool API scope. M2M grants- # cannot gain that scope when the client has no custom scopes.+ # Only user sign-ins inherit the user-pool API scope.return "" if grant == "client_credentials" else None# client_credentials grants only resource-server scopesallowed = sorted(s for s in listed if "/" in s or grant != "client_credentials")@@ -809,27 +808,21 @@ def _id_token_granted(scope: str | None) -> bool:def _client_credentials_scope_error(pool: dict, client: dict, requested: str | None):- """Reject the whole M2M grant when a custom scope is undefined or not allowed.-- AWS's token endpoint documents invalid_scope for an unknown resource server- or scope, and invalid_grant for a defined scope the app client does not allow.- """+ """invalid_scope for an undefined scope, invalid_grant for one the client doesn't allow; the whole grant fails."""allowed = client.get("AllowedOAuthScopes") or []- # RFC 6749 treats an empty value as omitted, but a nonempty value must- # contain a scope token. Whitespace alone must not pass a vacuous check.- if requested and not requested.split():- return _oauth2_error("invalid_scope", "The requested scope is malformed.")wanted = requested.split() if requested else [s for s in allowed if "/" in s]defined = {f"{identifier}/{scope['ScopeName']}"for identifier, server in (pool.get("_resource_servers") or {}).items()for scope in server.get("Scopes", [])}- if any(scope not in defined for scope in wanted):- return _oauth2_error("invalid_scope", "The requested scope does not exist.")- if any(scope not in allowed for scope in wanted):- return _oauth2_error("invalid_grant", "The requested scope is not allowed for this client.")- return None+ if (requested and not wanted) or any(scope not in defined for scope in wanted):+ error = "invalid_scope"+ elif any(scope not in allowed for scope in wanted):+ error = "invalid_grant"+ else:+ return None+ return 400, {"Content-Type": "application/json"}, json.dumps({"error": error}).encode()def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "access",diff --git a/ministack/services/kms.py b/ministack/services/kms.pyindex 71bca6ba..87aeab0e 100644--- a/ministack/services/kms.py+++ b/ministack/services/kms.py@@ -660,6 +660,9 @@ def _sign(data):else:message = message_b64+ err = _algorithm_error(rec, algorithm, "SigningAlgorithms")+ if err:+ return errif algorithm in ("ED25519_SHA_512", "ED25519_PH_SHA_512"):if rec["KeySpec"] != "ECC_NIST_EDWARDS25519":return error_response_json(@@ -696,6 +699,9 @@ def _sign(data):})pad, hash_algo = _signing_params(algorithm)+ err = _digest_length_error(algorithm, message_type, message, hash_algo)+ if err:+ return errif hash_algo is None:return error_response_json("UnsupportedOperationException",@@ -754,6 +760,9 @@ def _verify(data):message = base64.b64decode(message_b64) if isinstance(message_b64, str) else message_b64signature = base64.b64decode(signature_b64) if isinstance(signature_b64, str) else signature_b64+ err = _algorithm_error(rec, algorithm, "SigningAlgorithms")+ if err:+ return errpublic_key = rec["_private_key"].public_key()if algorithm in ("ED25519_SHA_512", "ED25519_PH_SHA_512"):if rec["KeySpec"] != "ECC_NIST_EDWARDS25519":@@ -788,7 +797,10 @@ def _verify(data):"SigningAlgorithm": algorithm,})- pad, hash_algo = _signing_params(algorithm, for_verify=True)+ pad, hash_algo = _signing_params(algorithm)+ err = _digest_length_error(algorithm, message_type, message, hash_algo)+ if err:+ return errif hash_algo is None:return error_response_json("UnsupportedOperationException",@@ -824,7 +836,29 @@ def _verify(data):})-def _signing_params(algorithm, for_verify=False):+def _algorithm_error(rec, algorithm, field):+ """InvalidKeyUsageException for an algorithm the key spec doesn't support."""+ if algorithm in rec.get(field, []):+ return None+ return error_response_json(+ "InvalidKeyUsageException",+ f"Algorithm {algorithm} is incompatible with key spec {rec.get('KeySpec', '')}.",+ 400,+ )+++def _digest_length_error(algorithm, message_type, message, hash_algo):+ if message_type == "DIGEST" and hash_algo is not None and len(message) != hash_algo.digest_size:+ return error_response_json("ValidationException", f"Digest is invalid length for algorithm {algorithm}.", 400)+ return None+++def _oaep_padding(algorithm):+ digest = hashes.SHA1() if algorithm == "RSAES_OAEP_SHA_1" else hashes.SHA256()+ return padding.OAEP(mgf=padding.MGF1(algorithm=digest), algorithm=digest, label=None)+++def _signing_params(algorithm):"""Return (padding, hash_algorithm) for a signing algorithm.For RSA algorithms, padding is a padding object.@@ -834,8 +868,8 @@ def _signing_params(algorithm, for_verify=False):if not HAS_CRYPTO:return None, None- # PSS salt_length must be MAX_LENGTH for signing, AUTO for verification- pss_salt = padding.PSS.AUTO if for_verify else padding.PSS.MAX_LENGTH+ # AWS KMS signs RSASSA_PSS with a salt as long as the digest (key spec reference).+ pss_salt = padding.PSS.DIGEST_LENGTHalgo_map = {"RSASSA_PKCS1_V1_5_SHA_256": (padding.PKCS1v15(), hashes.SHA256()),@@ -1070,17 +1104,14 @@ def _encrypt(data):400,)err = _require_crypto("Encrypt")+ if err:+ return err+ algorithm = data.get("EncryptionAlgorithm", "SYMMETRIC_DEFAULT")+ err = _algorithm_error(rec, algorithm, "EncryptionAlgorithms")if err:return errpublic_key = rec["_private_key"].public_key()- ciphertext = public_key.encrypt(- plaintext,- padding.OAEP(- mgf=padding.MGF1(algorithm=hashes.SHA256()),- algorithm=hashes.SHA256(),- label=None,- ),- )+ ciphertext = public_key.encrypt(plaintext, _oaep_padding(algorithm))else:return error_response_json("UnsupportedOperationException",@@ -1158,17 +1189,14 @@ def _decrypt(data):400,)err = _require_crypto("Decrypt")+ if err:+ return err+ algorithm = data.get("EncryptionAlgorithm", "SYMMETRIC_DEFAULT")+ err = _algorithm_error(rec, algorithm, "EncryptionAlgorithms")if err:return errtry:- plaintext = rec["_private_key"].decrypt(- ciphertext,- padding.OAEP(- mgf=padding.MGF1(algorithm=hashes.SHA256()),- algorithm=hashes.SHA256(),- label=None,- ),- )+ plaintext = rec["_private_key"].decrypt(ciphertext, _oaep_padding(algorithm))except ValueError:# AWS KMS doesn't surface the underlying crypto library's error# text; the documented InvalidCiphertextException message format@@ -1914,10 +1942,12 @@ def _key_metadata_in_region(rec, region):def _schedule_key_deletion(data):+ days = data.get("PendingWindowInDays", 30)+ if isinstance(days, int) and not 7 <= days <= 30:+ return error_response_json("ValidationException", "PendingWindowInDays must be between 7 and 30", 400)rec = _resolve_key(data.get("KeyId", ""))if not rec:return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)- days = data.get("PendingWindowInDays", 30)state = "PendingDeletion"if rec.get("MultiRegion"):others = [r for r in (rec.get("_mrk_regions") or []) if r != get_region()]diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 9e53e958..2766eb1d 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -2769,9 +2769,7 @@ def _delete_function(name: str, query_params: dict, path_qualifier: str | None =return 204, {}, b""-# Code and configuration share a revision; each alias has its own. Only-# registry lookup is global. Weak entries disappear once all active callers-# release their strong references, without persisting locks in function state.+# One lock per function (code and configuration share a revision) or alias._revision_locks = weakref.WeakValueDictionary()_revision_locks_guard = threading.Lock()@@ -2788,9 +2786,6 @@ def _serialized_revision_update(*, alias=False):if lock is None:lock = threading.RLock()_revision_locks[key] = lock- # Keep this reference while waiting as well as while executing:- # a waiter must never acquire a replacement lock for the same key.- # Reentrant acquisition cannot deadlock a same-thread nested call.with lock:return operation(*args, **kwargs)return guarded@@ -2802,7 +2797,8 @@ def _check_revision(current: dict, data: dict):logger.debug("Rejected Lambda update with a stale RevisionId")return error_response_json("PreconditionFailedException",- "The RevisionId provided does not match the latest RevisionId.",+ "The RevisionId provided does not match the latest RevisionId for the Lambda function or alias. "+ "Call the GetFunction or the GetAlias API to retrieve the latest RevisionId for your resource.",412,)return Nonediff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 788b35c8..a8b4281e 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -2002,11 +2002,11 @@ def _object_response_headers(obj: dict, bucket_name: str = "", key: str = "", inexpiry = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(restore["expires_at"]))h["x-amz-restore"] = f'ongoing-request="false", expiry-date="{expiry}"'if bucket_name and key:- retention = _object_retention.get((bucket_name, key))+ retention = _object_retention.get((bucket_name, key, obj.get("version_id")))if retention:h["x-amz-object-lock-mode"] = retention["Mode"]h["x-amz-object-lock-retain-until-date"] = retention["RetainUntilDate"]- hold = _object_legal_hold.get((bucket_name, key))+ hold = _object_legal_hold.get((bucket_name, key, obj.get("version_id")))if hold:h["x-amz-object-lock-legal-hold"] = hold# AWS only returns x-amz-checksum-* headers when the request opted in via@@ -2325,9 +2325,9 @@ def _dispatch(method: str, bucket: str, key: str, headers: dict, body: bytes, quif "tagging" in query_params:return _get_object_tagging(bucket, key, query_params)if "retention" in query_params:- return _get_object_retention(bucket, key)+ return _get_object_retention(bucket, key, query_params)if "legal-hold" in query_params:- return _get_object_legal_hold(bucket, key)+ return _get_object_legal_hold(bucket, key, query_params)if "acl" in query_params:return _get_object_acl(bucket, key, query_params)if "attributes" in query_params:@@ -2344,9 +2344,9 @@ def _dispatch(method: str, bucket: str, key: str, headers: dict, body: bytes, quif "tagging" in query_params:return _put_object_tagging(bucket, key, body, query_params)if "retention" in query_params:- return _put_object_retention(bucket, key, body, headers)+ return _put_object_retention(bucket, key, body, headers, query_params)if "legal-hold" in query_params:- return _put_object_legal_hold(bucket, key, body)+ return _put_object_legal_hold(bucket, key, body, query_params)if "acl" in query_params:return _put_object_acl(bucket, key, body, headers, query_params)if "x-amz-copy-source" in headers:@@ -4292,15 +4292,15 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):if canned_acl and canned_acl not in _CANNED_OBJECT_ACLS:return _error("InvalidArgument", f"Invalid x-amz-acl value: {canned_acl}", 400)+ lock_err = _object_lock_header_error(bucket_name, headers)+ if lock_err:+ return lock_erretag = f'"{md5_hash(body)}"'obj = _build_object_record(body, headers, etag=etag, checksums=checksums)obj["preserved_headers"].update(sse_headers)prior_obj = bucket["objects"].get(key)bucket["objects"][key] = obj- # --- Object Lock headers on PutObject ---- _apply_object_lock_from_headers(bucket_name, key, headers)-# --- x-amz-tagging header on PutObject ---# Parse + validate up front so the count error returns before persist/event,# but defer the dict write until version_id is assigned (tags are per-version).@@ -4315,6 +4315,7 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):resp_headers.update(sse_headers)_maybe_replicate(bucket_name, key, obj, body, pending_tags)version_id = _record_object_version(bucket_name, key, prior_obj, obj, body)+ _apply_object_lock_from_headers(bucket_name, key, headers, obj.get("version_id"))if version_id:resp_headers["x-amz-version-id"] = version_id# After the version is cut, so the record names it.@@ -4426,20 +4427,19 @@ def _enforce_post_policy_size(policy_b64: str, size: int):return Nonedef _enforce_signed_post_policy(fields: dict, bucket_name: str, region: str, size: int, sigv4: bool):- """Verify a signed form and its expanded fields before any object mutation.-- POST signs the Base64 policy itself, rather than a canonical HTTP request:- SigV4 with the scoped signing key, legacy SigV2 with HMAC-SHA1 of the secret.- Anonymous forms retain their existing handling.- """+ """Check a signed form's policy before any write; the signature and signer only under AUTH=true."""+ from ministack.app import AUTHdef invalid():logger.debug("S3 POST rejected: invalid policy document")return _error("InvalidPolicyDocument", "The content of the form does not meet the conditions ""specified in the policy document.", 400)- def denied(reason="policy condition not satisfied"):+ def denied(reason):logger.debug("S3 POST rejected: %s", reason)- return _error("AccessDenied", "Access Denied", 403)+ return _error("AccessDenied", f"Invalid according to Policy: {reason}", 403)++ def condition_failed(operator, name, value):+ return denied(f"Policy Condition failed: {json.dumps([operator, name, value])}")def invalid_argument(reason):logger.debug("S3 POST rejected: %s", reason)@@ -4466,35 +4466,35 @@ def _enforce_signed_post_policy(fields: dict, bucket_name: str, region: str, sizelse:access_key, signed_region = fields["awsaccesskeyid"], region- # Use the signer's tenant only for credential and IAM resolution. The- # bucket-owner scope chosen by _apply_bucket_scope must survive the upload.- try:- account = find_iam_access_key_account(access_key) or access_key- except AmbiguousAccessKeyError:- return _error("InvalidAccessKeyId", "The AWS Access Key Id you provided does not exist in our records.", 403)- with request_scope(get_account_id(), region):- set_request_account_id(account)- credential = resolve_credential(access_key, get_account_id(), fields.get("x-amz-security-token", ""))- if isinstance(credential, CredentialResolutionError):- if credential.code == "ExpiredTokenException":- return _error("ExpiredToken", "The provided token has expired.", 400)- if credential.code == "InvalidToken":- return _error("InvalidToken", credential.message, 400)- return _error("InvalidAccessKeyId", "The AWS Access Key Id you provided does not exist in our records.", 403)- # The signature covers the Base64 policy as sent, so it is checked before decoding.encoded = fields["policy"]- if sigv4:- computed = calculate_signature(credential.secret_access_key, date_stamp, signed_region, "s3", encoded)- signature = fields["x-amz-signature"]- signed = re.fullmatch(r"[0-9a-f]{64}", signature) and signatures_match(computed, signature)- else:- digest = hmac.new(credential.secret_access_key.encode(), encoded.encode(), hashlib.sha1).digest()- signature = fields["signature"]- signed = signature.isascii() and signatures_match(base64.b64encode(digest).decode(), signature)- if not signed:- logger.debug("S3 POST rejected: signature mismatch")- return _error("SignatureDoesNotMatch", "The request signature we calculated does not match the signature "- "you provided. Check your key and signing method.", 403)+ if AUTH:+ # Use the signer's tenant only for credential and IAM resolution. The+ # bucket-owner scope chosen by _apply_bucket_scope must survive the upload.+ try:+ account = find_iam_access_key_account(access_key) or access_key+ except AmbiguousAccessKeyError:+ return _error("InvalidAccessKeyId", "The AWS Access Key Id you provided does not exist in our records.", 403)+ with request_scope(get_account_id(), region):+ set_request_account_id(account)+ credential = resolve_credential(access_key, get_account_id(), fields.get("x-amz-security-token", ""))+ if isinstance(credential, CredentialResolutionError):+ if credential.code == "ExpiredTokenException":+ return _error("ExpiredToken", "The provided token has expired.", 400)+ if credential.code == "InvalidToken":+ return _error("InvalidToken", credential.message, 400)+ return _error("InvalidAccessKeyId", "The AWS Access Key Id you provided does not exist in our records.", 403)+ if sigv4:+ computed = calculate_signature(credential.secret_access_key, date_stamp, signed_region, "s3", encoded)+ signature = fields["x-amz-signature"]+ signed = re.fullmatch(r"[0-9a-f]{64}", signature) and signatures_match(computed, signature)+ else:+ digest = hmac.new(credential.secret_access_key.encode(), encoded.encode(), hashlib.sha1).digest()+ signature = fields["signature"]+ signed = signature.isascii() and signatures_match(base64.b64encode(digest).decode(), signature)+ if not signed:+ logger.debug("S3 POST rejected: signature mismatch")+ return _error("SignatureDoesNotMatch", "The request signature we calculated does not match the signature "+ "you provided. Check your key and signing method.", 403)try:policy = json.loads(base64.b64decode(encoded, validate=True).decode("utf-8"))@@ -4510,15 +4510,15 @@ def _enforce_signed_post_policy(fields: dict, bucket_name: str, region: str, sizexcept (ValueError, TypeError, RecursionError):return invalid()if _dt.datetime.now(_dt.timezone.utc) >= expires:- return denied("policy expired")+ return denied("Policy expired.")values = dict(fields, bucket=bucket_name)if "bucket" in fields and fields["bucket"] != bucket_name:- return denied()+ return condition_failed("eq", "$bucket", bucket_name)covered = set()for condition in conditions:if isinstance(condition, dict) and condition:- matches = [("eq", name, value) for name, value in condition.items()]+ matches = [("eq", f"${name}", value) for name, value in condition.items()]elif isinstance(condition, list) and len(condition) == 3:operator, name, value = conditionif operator == "content-length-range":@@ -4526,7 +4526,7 @@ def _enforce_signed_post_policy(fields: dict, bucket_name: str, region: str, siztry:name, value = int(name), int(value)except (TypeError, ValueError):- return denied()+ return condition_failed(operator, name, value)if name < 0 or value < name:return invalid()if size < name:@@ -4536,27 +4536,26 @@ def _enforce_signed_post_policy(fields: dict, bucket_name: str, region: str, sizcontinueif operator not in ("eq", "starts-with") or not isinstance(name, str) or not name.startswith("$"):return invalid()- matches = [(operator, name[1:], value)]+ matches = [(operator, name, value)]else:return invalid()- for operator, name, value in matches:- if not isinstance(name, str) or not name or not isinstance(value, str):+ for operator, field, value in matches:+ if not isinstance(field, str) or len(field) < 2 or not isinstance(value, str):return invalid()- name = name.lower()+ name = field[1:].lower()if name not in values:- return denied()+ return condition_failed(operator, field, value)actual = values[name]candidates = actual.split(",") if name == "content-type" and operator == "starts-with" else [actual]if not all(candidate == value if operator == "eq" else candidate.startswith(value) for candidate in candidates):- return denied()+ return condition_failed(operator, field, value)covered.add(name)exempt = {"policy", "x-amz-signature", "awsaccesskeyid", "signature", "file"}- if any(name not in covered and name not in exempt and not name.startswith("x-ignore-") for name in values):- return denied()+ extra = [name for name in values if name not in covered and name not in exempt and not name.startswith("x-ignore-")]+ if extra:+ return denied(f"Extra input fields: {', '.join(extra)}")- # Multipart credentials are absent from the router's Authorization header.- # Enforce the actual signer against the expanded object key under AUTH.- from ministack.app import AUTH+ # The form's signer, not the request's Authorization header, needs the write permissions.if AUTH:from ministack.core.iam_evaluator import enforce@@ -4576,7 +4575,7 @@ def _enforce_signed_post_policy(fields: dict, bucket_name: str, region: str, sizfor action in sorted(actions):if enforce(access_key, action, "s3", signed_region,resource_arn=f"arn:aws:s3:::{bucket_name}/{fields['key']}", service_context=context) is not None:- return denied("signer lacks object write permission")+ return _error("AccessDenied", "Access Denied", 403)return None@@ -4701,12 +4700,14 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):if sse_err:return sse_err+ lock_err = _object_lock_header_error(bucket_name, synth)+ if lock_err:+ return lock_erretag = f'"{md5_hash(file_value)}"'obj = _build_object_record(file_value, synth, etag=etag)obj["preserved_headers"].update(sse_headers)prior_obj = bucket["objects"].get(key)bucket["objects"][key] = obj- _apply_object_lock_from_headers(bucket_name, key, synth)# Defer tag write until version_id is assigned (tags are per-version).pending_tags = None@@ -4718,6 +4719,7 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):_maybe_replicate(bucket_name, key, obj, file_value, pending_tags)version_id = _record_object_version(bucket_name, key, prior_obj, obj, file_value)+ _apply_object_lock_from_headers(bucket_name, key, synth, obj.get("version_id"))_fire_s3_event_async(bucket_name, key, "s3:ObjectCreated:Post", size=obj["size"], etag=etag, version_id=version_id)if pending_tags is not None:@@ -4769,7 +4771,17 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):return status, base_resp, b""-def _apply_object_lock_from_headers(bucket_name: str, key: str, headers: dict):+_OBJECT_LOCK_HEADERS = ("x-amz-object-lock-mode", "x-amz-object-lock-retain-until-date",+ "x-amz-object-lock-legal-hold", "x-amz-object-lock-legal-hold-status")+++def _object_lock_header_error(bucket_name: str, headers: dict) -> tuple | None:+ if any(headers.get(h) for h in _OBJECT_LOCK_HEADERS) and not _bucket_object_lock.get(bucket_name):+ return _error("InvalidRequest", "Bucket is missing ObjectLockConfiguration", 400)+ return None+++def _apply_object_lock_from_headers(bucket_name: str, key: str, headers: dict, version_id):lock_mode = headers.get("x-amz-object-lock-mode", "")lock_until = headers.get("x-amz-object-lock-retain-until-date", "")lock_legal = headers.get("x-amz-object-lock-legal-hold", "") or headers.get(@@ -4777,7 +4789,7 @@ def _apply_object_lock_from_headers(bucket_name: str, key: str, headers: dict):)if lock_mode and lock_until:- _object_retention[(bucket_name, key)] = {+ _object_retention[(bucket_name, key, version_id)] = {"Mode": lock_mode,"RetainUntilDate": lock_until,}@@ -4795,13 +4807,13 @@ def _apply_object_lock_from_headers(bucket_name: str, key: str, headers: dict):until = now.replace(year=now.year + years)else:return- _object_retention[(bucket_name, key)] = {+ _object_retention[(bucket_name, key, version_id)] = {"Mode": dr["Mode"],"RetainUntilDate": until.strftime("%Y-%m-%dT%H:%M:%S.000Z"),}if lock_legal in ("ON", "OFF"):- _object_legal_hold[(bucket_name, key)] = lock_legal+ _object_legal_hold[(bucket_name, key, version_id)] = lock_legaldef _object_tagging_count_header(bucket_name: str, key: str, version_id) -> dict:@@ -5175,8 +5187,8 @@ def _purge_current_object(bucket_name: str, key: str, bucket: dict):bucket["objects"].pop(key, None)_object_tags.pop((bucket_name, key, None), None)_object_annotations.pop((bucket_name, key, None), None)- _object_retention.pop((bucket_name, key), None)- _object_legal_hold.pop((bucket_name, key), None)+ _object_retention.pop((bucket_name, key, None), None)+ _object_legal_hold.pop((bucket_name, key, None), None)_object_acl.pop((bucket_name, key, None), None)_delete_persisted_object(bucket_name, key)@@ -5569,6 +5581,8 @@ def _delete_object_version(bucket: dict, bucket_name: str, key: str, version_id:_object_tags.pop((bucket_name, key, version_id), None)_object_acl.pop((bucket_name, key, version_id), None)_object_annotations.pop((bucket_name, key, None if version_id == "null" else version_id), None)+ _object_retention.pop((bucket_name, key, version_id), None)+ _object_legal_hold.pop((bucket_name, key, version_id), None)if not versions:# History is now empty — drop the index entry and the current object.@@ -5640,16 +5654,14 @@ def _delete_object(bucket_name: str, key: str, headers: dict | None = None, querf"/{bucket_name}/{key}",)- if key in bucket["objects"]:- lock_err = _check_object_lock(bucket_name, key, headers)- if lock_err:- return lock_err-# An explicit VersionId permanently removes exactly that version (or that# specific delete marker) — it never creates a new marker. Only a delete# WITHOUT a VersionId falls through to the delete-marker path below.version_id = _qp(query_params, "versionId", "")if version_id:+ lock_err = _check_object_lock(bucket_name, key, headers, None if version_id == "null" else version_id)+ if lock_err:+ return lock_err_found, was_delete_marker = _delete_object_version(bucket, bucket_name, key, version_id)# S3 returns 204 whether or not the version existed, echoing the# addressed VersionId (and delete-marker flag when one was removed).@@ -5681,8 +5693,8 @@ def _delete_object(bucket_name: str, key: str, headers: dict | None = None, querbucket["objects"].pop(key, None)_object_tags.pop((bucket_name, key, None), None)_object_annotations.pop((bucket_name, key, None), None)- _object_retention.pop((bucket_name, key), None)- _object_legal_hold.pop((bucket_name, key), None)+ _object_retention.pop((bucket_name, key, None), None)+ _object_legal_hold.pop((bucket_name, key, None), None)_object_acl.pop((bucket_name, key, None), None)_delete_persisted_object(bucket_name, key)@@ -5691,8 +5703,9 @@ def _delete_object(bucket_name: str, key: str, headers: dict | None = None, querreturn 204, {}, b""-def _check_object_lock(bucket_name: str, key: str, headers: dict) -> tuple | None:- hold = _object_legal_hold.get((bucket_name, key))+def _check_object_lock(bucket_name: str, key: str, headers: dict, version_id) -> tuple | None:+ """Refusal for a permanent delete of a version under retention or legal hold."""+ hold = _object_legal_hold.get((bucket_name, key, version_id))if hold == "ON":return _error("AccessDenied",@@ -5700,7 +5713,7 @@ def _check_object_lock(bucket_name: str, key: str, headers: dict) -> tuple | Non403,)- retention = _object_retention.get((bucket_name, key))+ retention = _object_retention.get((bucket_name, key, version_id))if retention:retain_until = retention.get("RetainUntilDate", "")if retain_until and retain_until > now_iso():@@ -5971,19 +5984,6 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):}pending_dest_annotations[name] = carried- # --- Preserve lock / retention ---- src_retention = _object_retention.get((src_bucket_name, src_key))- if src_retention:- _object_retention[(bucket_name, dest_key)] = dict(src_retention)- else:- _object_retention.pop((bucket_name, dest_key), None)-- src_hold = _object_legal_hold.get((src_bucket_name, src_key))- if src_hold:- _object_legal_hold[(bucket_name, dest_key)] = src_hold- else:- _object_legal_hold.pop((bucket_name, dest_key), None)-resp_headers = {"Content-Type": "application/xml"}resp_headers.update(dest_sse)if copy_src_vid:@@ -6005,6 +6005,10 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):)dest_version_id = dest_obj.get("version_id")+ src_lock_key = (src_bucket_name, src_key, src_obj.get("version_id"))+ for store in (_object_retention, _object_legal_hold):+ if src_lock_key in store and _bucket_object_lock.get(bucket_name):+ store[(bucket_name, dest_key, dest_version_id)] = copy.deepcopy(store[src_lock_key])if pending_dest_annotations:_object_annotations[(bucket_name, dest_key, dest_version_id)] = pending_dest_annotationsif dest_obj.get("_replica"):@@ -6381,14 +6385,14 @@ def _annotation_checksum_headers(entry: dict) -> dict:return out-def _annotation_lock_error(bucket_name: str, key: str, headers: dict) -> tuple | None:+def _annotation_lock_error(bucket_name: str, key: str, headers: dict, version_id) -> tuple | None:"""Object Lock refusal for an annotation write (observed on AWS)."""from ministack.app import AUTHif not AUTH:return None- if _object_legal_hold.get((bucket_name, key)) == "ON":+ if _object_legal_hold.get((bucket_name, key, version_id)) == "ON":return _error("AccessDenied", "Access Denied because object protected by object lock legal hold.", 403)- retention = _object_retention.get((bucket_name, key))+ retention = _object_retention.get((bucket_name, key, version_id))if not retention:return Noneretain_until = retention.get("RetainUntilDate", "")@@ -6410,7 +6414,7 @@ def _put_object_annotation(bucket_name: str, key: str, body: bytes, headers: dicif error:return errorbucket, version_key, record = target- lock_error = _annotation_lock_error(bucket_name, key, headers)+ lock_error = _annotation_lock_error(bucket_name, key, headers, version_key)if lock_error:return lock_errorprecondition = _annotation_if_match(headers, record)@@ -6579,7 +6583,7 @@ def _delete_object_annotation(bucket_name: str, key: str, headers: dict, query_pif error:return errorbucket, version_key, record = target- lock_error = _annotation_lock_error(bucket_name, key, headers)+ lock_error = _annotation_lock_error(bucket_name, key, headers, version_key)if lock_error:return lock_errorprecondition = _annotation_if_match(headers, record)@@ -6698,23 +6702,30 @@ def _put_object_lock_configuration(bucket_name: str, body: bytes):return 200, {"Content-Type": "application/xml"}, b""-def _get_object_retention(bucket_name: str, key: str):+def _object_lock_target(bucket_name: str, key: str, bucket: dict, query_params: dict | None):+ """``(lock key, error)`` for the version a retention or legal-hold call addresses."""+ if _qp(query_params or {}, "versionId", ""):+ missing = _no_such_version(bucket_name, key, query_params)+ if missing:+ return None, missing+ elif key not in bucket["objects"]:+ return None, _error("NoSuchKey", "The specified key does not exist.", 404, f"/{bucket_name}/{key}")+ return (bucket_name, key, _resolve_subresource_version(query_params or {}, bucket, key)), None+++def _get_object_retention(bucket_name: str, key: str, query_params: dict | None = None):bucket = _ensure_bucket(bucket_name)if bucket is None:return _no_such_bucket(bucket_name)- if key not in bucket["objects"]:- return _error(- "NoSuchKey",- "The specified key does not exist.",- 404,- f"/{bucket_name}/{key}",- )+ lock_key, missing = _object_lock_target(bucket_name, key, bucket, query_params)+ if missing:+ return missinglock = _bucket_object_lock.get(bucket_name)if not lock:return _error("InvalidRequest", "Bucket is missing Object Lock Configuration", 400)- retention = _object_retention.get((bucket_name, key))+ retention = _object_retention.get(lock_key)if not retention:return _error("NoSuchObjectLockConfiguration",@@ -6728,17 +6739,13 @@ def _get_object_retention(bucket_name: str, key: str):return 200, {"Content-Type": "application/xml"}, _xml_body(root)-def _put_object_retention(bucket_name: str, key: str, body: bytes, headers: dict):+def _put_object_retention(bucket_name: str, key: str, body: bytes, headers: dict, query_params: dict | None = None):bucket = _ensure_bucket(bucket_name)if bucket is None:return _no_such_bucket(bucket_name)- if key not in bucket["objects"]:- return _error(- "NoSuchKey",- "The specified key does not exist.",- 404,- f"/{bucket_name}/{key}",- )+ lock_key, missing = _object_lock_target(bucket_name, key, bucket, query_params)+ if missing:+ return missinglock = _bucket_object_lock.get(bucket_name)if not lock:@@ -6759,7 +6766,7 @@ def _put_object_retention(bucket_name: str, key: str, body: bytes, headers: dictretain_until = date_el.text- existing = _object_retention.get((bucket_name, key))+ existing = _object_retention.get(lock_key)if existing:is_reducing = existing.get("RetainUntilDate", "") > retain_until or (mode_el.text == "GOVERNANCE" and existing.get("Mode") == "COMPLIANCE"@@ -6780,30 +6787,26 @@ def _put_object_retention(bucket_name: str, key: str, body: bytes, headers: dict403,)- _object_retention[(bucket_name, key)] = {+ _object_retention[lock_key] = {"Mode": mode_el.text,"RetainUntilDate": retain_until,}return 200, {"Content-Type": "application/xml"}, b""-def _get_object_legal_hold(bucket_name: str, key: str):+def _get_object_legal_hold(bucket_name: str, key: str, query_params: dict | None = None):bucket = _ensure_bucket(bucket_name)if bucket is None:return _no_such_bucket(bucket_name)- if key not in bucket["objects"]:- return _error(- "NoSuchKey",- "The specified key does not exist.",- 404,- f"/{bucket_name}/{key}",- )+ lock_key, missing = _object_lock_target(bucket_name, key, bucket, query_params)+ if missing:+ return missinglock = _bucket_object_lock.get(bucket_name)if not lock:return _error("InvalidRequest", "Bucket is missing Object Lock Configuration", 400)- status = _object_legal_hold.get((bucket_name, key))+ status = _object_legal_hold.get(lock_key)if status is None:return _error("NoSuchObjectLockConfiguration",@@ -6816,17 +6819,13 @@ def _get_object_legal_hold(bucket_name: str, key: str):return 200, {"Content-Type": "application/xml"}, _xml_body(root)-def _put_object_legal_hold(bucket_name: str, key: str, body: bytes):+def _put_object_legal_hold(bucket_name: str, key: str, body: bytes, query_params: dict | None = None):bucket = _ensure_bucket(bucket_name)if bucket is None:return _no_such_bucket(bucket_name)- if key not in bucket["objects"]:- return _error(- "NoSuchKey",- "The specified key does not exist.",- 404,- f"/{bucket_name}/{key}",- )+ lock_key, missing = _object_lock_target(bucket_name, key, bucket, query_params)+ if missing:+ return missinglock = _bucket_object_lock.get(bucket_name)if not lock:@@ -6841,7 +6840,7 @@ def _put_object_legal_hold(bucket_name: str, key: str, body: bytes):if status_el is None or status_el.text not in ("ON", "OFF"):return _error("MalformedXML", "The XML you provided was not well-formed", 400)- _object_legal_hold[(bucket_name, key)] = status_el.text+ _object_legal_hold[lock_key] = status_el.textreturn 200, {"Content-Type": "application/xml"}, b""@@ -7409,8 +7408,8 @@ def _delete_objects(bucket_name: str, body: bytes, headers: dict = None):vid_el = _find_xml_tag(obj_el, "VersionId")version_id = vid_el.text if (vid_el is not None and vid_el.text) else ""- if k in bucket["objects"]:- lock_err = _check_object_lock(bucket_name, k, headers)+ if version_id:+ lock_err = _check_object_lock(bucket_name, k, headers, None if version_id == "null" else version_id)if lock_err:errors.append({@@ -7504,8 +7503,8 @@ def _delete_objects(bucket_name: str, body: bytes, headers: dict = None):bucket["objects"].pop(k, None)_object_tags.pop((bucket_name, k, None), None)_object_annotations.pop((bucket_name, k, None), None)- _object_retention.pop((bucket_name, k), None)- _object_legal_hold.pop((bucket_name, k), None)+ _object_retention.pop((bucket_name, k, None), None)+ _object_legal_hold.pop((bucket_name, k, None), None)_object_acl.pop((bucket_name, k, None), None)_delete_persisted_object(bucket_name, k)deleted.append({"key": k, "version_id": "", "was_marker": False})diff --git a/ministack/services/sqs.py b/ministack/services/sqs.pyindex 9527647f..169e25a0 100644--- a/ministack/services/sqs.py+++ b/ministack/services/sqs.py@@ -945,8 +945,7 @@ def _act_set_queue_attributes(data: dict, qurl: str) -> dict:_validate_numeric_attrs(incoming)for k, v in incoming.items():if k in {"Policy", "RedrivePolicy", "RedriveAllowPolicy"} and v == "":- # Terraform deletes standalone policy resources with an empty- # attribute value. Reads must then omit the removed attribute.+ # An empty value removes the policy (Terraform's policy-resource delete).q["attributes"].pop(k, None)logger.debug("Removed queue attribute %s from %s", k, url)else:diff --git a/tests/test_cloudwatch_logs.py b/tests/test_cloudwatch_logs.pyindex 76ab656a..01d7abba 100644--- a/tests/test_cloudwatch_logs.py+++ b/tests/test_cloudwatch_logs.py@@ -2,6 +2,7 @@ import asyncioimport jsonimport osimport time+import uuidimport uuid as _uuid_modimport boto3@@ -2523,3 +2524,365 @@ def test_tag_arn_validation_preserves_malformed_json_error(logs_auth, monkeypatcassert call(action, root=True, raw_body=b"{") == (400, {"__type": "SerializationException", "message": "Invalid JSON"},)+++def log_group():+ group = f"/test/filter-pattern/{uuid.uuid4().hex}"+ assert _logs_svc._create_log_group({"logGroupName": group})[0] == 200+ yield group+ assert _logs_svc._delete_log_group({"logGroupName": group})[0] == 200+++def put_messages(group, stream, messages):+ assert _logs_svc._create_log_stream({+ "logGroupName": group, "logStreamName": stream,+ })[0] == 200+ response = _logs_svc._put_log_events({+ "logGroupName": group,+ "logStreamName": stream,+ "logEvents": [{"timestamp": timestamp, "message": message}+ for timestamp, message in messages],+ })+ assert response[0] == 200+++def test_filter_applies_limit_after_global_stream_order(log_group):+ now = int(time.time() * 1000)+ # The stream scanned first has newer events than the second stream.+ put_messages(log_group, "newer", [(now + 30, "match newer")])+ put_messages(log_group, "older", [+ (now, "unrelated"), (now + 10, "match first"), (now + 20, "match second"),+ ])+ response = _logs_svc._filter_log_events({+ "logGroupName": log_group, "filterPattern": "match", "limit": 1,+ })+ assert response[0] == 200+ assert [e["message"] for e in json.loads(response[2])["events"]] == ["match first"]+++def test_filter_does_not_stop_later_stream_after_partial_global_limit(log_group):+ now = int(time.time() * 1000)+ put_messages(log_group, "newer", [(now + 30, "match newer")])+ put_messages(log_group, "older", [(now + 10, "match first"), (now + 20, "match second")])+ response = _logs_svc._filter_log_events({+ "logGroupName": log_group, "filterPattern": "match", "limit": 2,+ })+ assert response[0] == 200+ assert [e["message"] for e in json.loads(response[2])["events"]] == [+ "match first", "match second",+ ]+++def filter_events(group, **parameters):+ response = _logs_svc._filter_log_events({"logGroupName": group, **parameters})+ assert response[0] == 200+ return json.loads(response[2])["events"]+++def count_filter_calls(monkeypatch):+ compile_pattern = _logs_svc._compile_filter_pattern+ checked = []++ def compile_counted(pattern):+ matcher = compile_pattern(pattern)++ def matches(message):+ checked.append(message)+ return matcher(message)++ return matches++ monkeypatch.setattr(_logs_svc, "_compile_filter_pattern", compile_counted)+ return checked+++def test_limit_stops_filtering_after_oldest_matches(log_group, monkeypatch):+ now = int(time.time() * 1000)+ put_messages(log_group, "a", [(now + i, f"match {i}") for i in range(2, 202, 2)])+ put_messages(log_group, "b", [(now + i, f"match {i}") for i in range(1, 202, 2)])+ # A later request can carry events older than those already stored.+ assert _logs_svc._put_log_events({+ "logGroupName": log_group, "logStreamName": "a",+ "logEvents": [{"timestamp": now, "message": "skip"}],+ })[0] == 200+ checked = count_filter_calls(monkeypatch)+ events = filter_events(log_group, filterPattern="match", limit=2)+ assert [event["message"] for event in events] == ["match 1", "match 2"]+ assert checked == ["skip", "match 1", "match 2"]+++def test_time_window_seeks_without_scanning_history(log_group):+ now = int(time.time() * 1000)+ put_messages(log_group, "history", [(now + i, f"event {i}") for i in range(8192)])+ timestamp_reads = []++ class CountedEvent(dict):+ def __getitem__(self, key):+ if key == "timestamp":+ timestamp_reads.append(None)+ return super().__getitem__(key)++ stream = _logs_svc._log_groups[log_group]["streams"]["history"]+ stream["events"] = [CountedEvent(event) for event in stream["events"]]+ events = filter_events(log_group, startTime=now + 8000, endTime=now + 8001, limit=10)+ assert [event["message"] for event in events] == ["event 8000", "event 8001"]+ # Allow headroom for binary searches and merge setup, but no linear scan.+ assert len(timestamp_reads) < 100+++def test_late_batch_keeps_reads_ordered_and_live_delivery_exact(log_group, monkeypatch):+ now = int(time.time() * 1000)+ put_messages(log_group, "s", [(now + 30, "newer")])+ deliveries = []+ monkeypatch.setattr(_logs_svc, "_fanout_to_live_tail_sessions",+ lambda group, stream, events: deliveries.extend(events))+ assert _logs_svc._put_log_events({+ "logGroupName": log_group, "logStreamName": "s",+ "logEvents": [+ {"timestamp": now + 10, "message": "older"},+ {"timestamp": now + 20, "message": "middle"},+ ],+ })[0] == 200+ response = _logs_svc._get_log_events({+ "logGroupName": log_group, "logStreamName": "s", "startFromHead": True,+ })+ assert response[0] == 200+ assert [event["message"] for event in json.loads(response[2])["events"]] == [+ "older", "middle", "newer",+ ]+ assert [event["message"] for event in deliveries] == ["older", "middle"]+ stored = filter_events(log_group)+ assert [event["eventId"] for event in stored[:2]] == [event["eventId"] for event in deliveries]++[email protected]("stream_order", [["a", "b"], ["b", "a"]])+def test_equal_timestamps_order_by_ingestion_time(log_group, stream_order):+ """AWS sorts by timestamp, then ingestion time, whatever the stream order."""+ now = int(time.time() * 1000)+ for stream, ingested in (("a", now + 2), ("b", now + 1)):+ assert _logs_svc._create_log_stream({"logGroupName": log_group, "logStreamName": stream})[0] == 200+ _logs_svc._append_log_events(_logs_svc._log_groups[log_group]["streams"][stream], [+ {"timestamp": now, "message": f"{stream} event", "ingestionTime": ingested, "eventId": stream}])+ events = filter_events(log_group, logStreamNames=stream_order, limit=2)+ assert [event["message"] for event in events] == ["b event", "a event"]+++def test_legacy_persistence_restores_order_before_limited_reads(log_group, monkeypatch, tmp_path):+ from ministack.core import persistence++ now = int(time.time() * 1000)+ put_messages(log_group, "s", [(now + i, f"event {i}") for i in range(20)])+ state = _logs_svc.get_state()+ state["log_groups"][log_group]["streams"]["s"]["events"].reverse()+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))+ persistence.save_state("cloudwatch_logs", state)+ assert _logs_svc._delete_log_group({"logGroupName": log_group})[0] == 200+ _logs_svc.load_persisted_state(persistence.load_state("cloudwatch_logs"))+ checked = count_filter_calls(monkeypatch)+ events = filter_events(log_group, limit=1)+ assert [event["message"] for event in events] == ["event 0"]+ assert checked == ["event 0"]++[email protected]("producer", ["codebuild", "dynamodb"])+def test_native_writers_keep_order_after_future_dated_api_event(log_group, monkeypatch, producer):+ now = int(time.time() * 1000)+ if producer == "codebuild":+ from ministack.services import codebuild++ stream_name = "native"+ emit = codebuild._log_sink({"logs": {"groupName": log_group, "streamName": stream_name}})+ monkeypatch.setattr(codebuild.time, "time", lambda: now / 1000)+ else:+ from ministack.services import dynamodb++ monkeypatch.setattr(dynamodb, "_IMPORT_LOG_GROUP", log_group)+ monkeypatch.setattr(dynamodb.time, "time", lambda: now / 1000)+ import_id = uuid.uuid4().hex+ stream_name = f"{import_id}/error"++ def emit(message):+ dynamodb._log_import_error(f"arn:aws:dynamodb:us-east-1:000000000000:table/t/import/{import_id}",+ "bucket", "key", 0, message)++ emit("initial")+ assert _logs_svc._put_log_events({+ "logGroupName": log_group, "logStreamName": stream_name,+ "logEvents": [{"timestamp": now + 3000, "message": "future API event"}],+ })[0] == 200+ emit("later native event")+ events = filter_events(log_group, limit=2)+ assert len(events) == 2+ assert [event["timestamp"] for event in events] == [now, now]+ assert "initial" in events[0]["message"]+ assert "later native event" in events[1]["message"]+++def test_reader_remains_consistent_during_late_arrival(log_group, monkeypatch):+ now = int(time.time() * 1000)+ put_messages(log_group, "s", [(now + 10, "ten"), (now + 20, "twenty")])+ inserted = False++ def matcher(message):+ nonlocal inserted+ if not inserted:+ inserted = True+ assert _logs_svc._put_log_events({+ "logGroupName": log_group, "logStreamName": "s",+ "logEvents": [{"timestamp": now, "message": "zero"}],+ })[0] == 200+ return True++ monkeypatch.setattr(_logs_svc, "_compile_filter_pattern", lambda pattern: matcher)+ assert [event["message"] for event in filter_events(log_group, limit=2)] == ["ten", "twenty"]+ assert [event["message"] for event in filter_events(log_group, limit=2)] == ["zero", "ten"]+++def test_mixed_batches_and_ranges_match_stable_reference(log_group):+ import random++ randomizer = random.Random(731)+ now = int(time.time() * 1000)+ arrivals = {name: [] for name in ("a", "b", "c")}+ for name in arrivals:+ assert _logs_svc._create_log_stream({"logGroupName": log_group, "logStreamName": name})[0] == 200+ for batch in range(30):+ name = randomizer.choice(list(arrivals))+ records = [{"timestamp": now + randomizer.randrange(12),+ "message": f"{'keep' if index % 2 else 'drop'} {batch}-{index}"}+ for index in range(4)]+ arrivals[name].extend(records)+ assert _logs_svc._put_log_events({+ "logGroupName": log_group, "logStreamName": name, "logEvents": records,+ })[0] == 200+ for selection in (["a", "b", "c"], ["c", "a"], ["missing", "b"]):+ streams = _logs_svc._log_groups[log_group]["streams"]+ reference = sorted((dict(event, logStreamName=name)+ for name in selection if name in streams for event in streams[name]["events"]),+ key=lambda event: (event["timestamp"], event["ingestionTime"]))+ for lower, upper in ((0, 11), (3, 7), (5, 5), (9, 2)):+ expected = [event for event in reference if now + lower <= event["timestamp"] <= now + upper+ and "keep" in event["message"]]+ for limit in (1, 7, 10000):+ actual = filter_events(log_group, logStreamNames=selection, filterPattern="keep",+ startTime=now + lower, endTime=now + upper, limit=limit)+ assert [(event["timestamp"], event["message"], event["logStreamName"]) for event in actual] == [+ (event["timestamp"], event["message"], event["logStreamName"])+ for event in expected[:limit]+ ]+++def test_concurrent_late_batches_preserve_every_event(log_group):+ from concurrent.futures import ThreadPoolExecutor+ from threading import Barrier++ from ministack.core.responses import get_account_id, get_region, request_scope++ now = int(time.time() * 1000)+ put_messages(log_group, "shared", [])+ account, region = get_account_id(), get_region()+ barrier = Barrier(4)++ def write(worker):+ with request_scope(account, region):+ barrier.wait(timeout=5)+ for batch in reversed(range(8)):+ timestamp = now + batch * 4 + worker+ assert _logs_svc._put_log_events({+ "logGroupName": log_group, "logStreamName": "shared",+ "logEvents": [{"timestamp": timestamp, "message": f"event {timestamp}"}],+ })[0] == 200++ with ThreadPoolExecutor(max_workers=4) as executor:+ futures = [executor.submit(write, worker) for worker in range(4)]+ for future in futures:+ future.result(timeout=10)+ events = filter_events(log_group, limit=100)+ assert [event["timestamp"] for event in events] == list(range(now, now + 32))+ stream = _logs_svc._log_groups[log_group]["streams"]["shared"]+ assert stream["firstEventTimestamp"] == now+ assert stream["lastEventTimestamp"] == now + 31+++def get_page(group, stream, **parameters):+ response = _logs_svc._get_log_events({"logGroupName": group, "logStreamName": stream, **parameters})+ assert response[0] == 200+ body = json.loads(response[2])+ return [event["message"] for event in body["events"]], body+++def test_forward_token_survives_late_arrivals(log_group):+ now = int(time.time() * 1000)+ put_messages(log_group, "s", [(now + 10, "e10"), (now + 20, "e20"), (now + 30, "e30")])+ messages, body = get_page(log_group, "s", startFromHead=True, limit=2)+ assert messages == ["e10", "e20"]+ # One event lands behind the cursor, one between the cursor and stored history.+ assert _logs_svc._put_log_events({+ "logGroupName": log_group, "logStreamName": "s",+ "logEvents": [{"timestamp": now + 15, "message": "e15"},+ {"timestamp": now + 25, "message": "e25"}],+ })[0] == 200+ messages, _ = get_page(log_group, "s", nextToken=body["nextForwardToken"], limit=2)+ assert messages == ["e25", "e30"]+++def test_backward_token_survives_late_arrivals(log_group):+ now = int(time.time() * 1000)+ put_messages(log_group, "s", [(now + 10, "e10"), (now + 20, "e20"), (now + 30, "e30")])+ messages, body = get_page(log_group, "s", limit=2)+ assert messages == ["e20", "e30"]+ # e15 is older than everything read so far; e25 is behind the backward cursor.+ assert _logs_svc._put_log_events({+ "logGroupName": log_group, "logStreamName": "s",+ "logEvents": [{"timestamp": now + 15, "message": "e15"},+ {"timestamp": now + 25, "message": "e25"}],+ })[0] == 200+ messages, _ = get_page(log_group, "s", nextToken=body["nextBackwardToken"], limit=2)+ assert messages == ["e10", "e15"]+++def test_backward_token_from_tail_excludes_later_events(log_group):+ now = int(time.time() * 1000)+ put_messages(log_group, "s", [(now + 10, "e10"), (now + 20, "e20")])+ _, body = get_page(log_group, "s", startFromHead=True)+ messages, body = get_page(log_group, "s", nextToken=body["nextForwardToken"])+ assert messages == []+ # e30 arrives after the reader reached the tail.+ assert _logs_svc._put_log_events({+ "logGroupName": log_group, "logStreamName": "s",+ "logEvents": [{"timestamp": now + 30, "message": "e30"}],+ })[0] == 200+ messages, _ = get_page(log_group, "s", nextToken=body["nextBackwardToken"])+ assert messages == ["e10", "e20"]+++def test_forward_token_splits_equal_timestamps_exactly_once(log_group):+ now = int(time.time() * 1000)+ put_messages(log_group, "s", [(now, "a"), (now, "b"), (now, "c")])+ seen = []+ messages, body = get_page(log_group, "s", startFromHead=True, limit=1)+ seen += messages+ # An equal-time arrival sorts after existing ties, so it is still ahead of the cursor.+ assert _logs_svc._put_log_events({+ "logGroupName": log_group, "logStreamName": "s",+ "logEvents": [{"timestamp": now, "message": "d"}],+ })[0] == 200+ for _ in range(5):+ messages, body = get_page(log_group, "s", nextToken=body["nextForwardToken"], limit=1)+ if not messages:+ break+ seen += messages+ assert seen == ["a", "b", "c", "d"]+++def test_get_log_events_end_time_is_exclusive_and_filter_reports_no_searched_streams(log_group):+ now = int(time.time() * 1000)+ put_messages(log_group, "s", [(now, "first"), (now + 1, "second")])+ page = _logs_svc._get_log_events({"logGroupName": log_group, "logStreamName": "s", "startFromHead": True,+ "startTime": now, "endTime": now + 1})+ assert [e["message"] for e in json.loads(page[2])["events"]] == ["first"]+ response = json.loads(_logs_svc._filter_log_events({"logGroupName": log_group})[2])+ assert response["searchedLogStreams"] == []+diff --git a/tests/test_cloudwatch_logs_order.py b/tests/test_cloudwatch_logs_order.pydeleted file mode 100644index 8cc18d76..00000000--- a/tests/test_cloudwatch_logs_order.py+++ /dev/null@@ -1,363 +0,0 @@-"""In-process regressions for FilterLogEvents ordering across streams."""--import json-import time-import uuid--import pytest--from ministack.services import cloudwatch_logs as logs---def log_group():- group = f"/test/filter-pattern/{uuid.uuid4().hex}"- assert logs._create_log_group({"logGroupName": group})[0] == 200- yield group- assert logs._delete_log_group({"logGroupName": group})[0] == 200---def put_messages(group, stream, messages):- assert logs._create_log_stream({- "logGroupName": group, "logStreamName": stream,- })[0] == 200- response = logs._put_log_events({- "logGroupName": group,- "logStreamName": stream,- "logEvents": [{"timestamp": timestamp, "message": message}- for timestamp, message in messages],- })- assert response[0] == 200---def test_filter_applies_limit_after_global_stream_order(log_group):- now = int(time.time() * 1000)- # The stream scanned first has newer events than the second stream.- put_messages(log_group, "newer", [(now + 30, "match newer")])- put_messages(log_group, "older", [- (now, "unrelated"), (now + 10, "match first"), (now + 20, "match second"),- ])- response = logs._filter_log_events({- "logGroupName": log_group, "filterPattern": "match", "limit": 1,- })- assert response[0] == 200- assert [e["message"] for e in json.loads(response[2])["events"]] == ["match first"]---def test_filter_does_not_stop_later_stream_after_partial_global_limit(log_group):- now = int(time.time() * 1000)- put_messages(log_group, "newer", [(now + 30, "match newer")])- put_messages(log_group, "older", [(now + 10, "match first"), (now + 20, "match second")])- response = logs._filter_log_events({- "logGroupName": log_group, "filterPattern": "match", "limit": 2,- })- assert response[0] == 200- assert [e["message"] for e in json.loads(response[2])["events"]] == [- "match first", "match second",- ]---def filter_events(group, **parameters):- response = logs._filter_log_events({"logGroupName": group, **parameters})- assert response[0] == 200- return json.loads(response[2])["events"]---def count_filter_calls(monkeypatch):- compile_pattern = logs._compile_filter_pattern- checked = []-- def compile_counted(pattern):- matcher = compile_pattern(pattern)-- def matches(message):- checked.append(message)- return matcher(message)-- return matches-- monkeypatch.setattr(logs, "_compile_filter_pattern", compile_counted)- return checked---def test_limit_stops_filtering_after_oldest_matches(log_group, monkeypatch):- now = int(time.time() * 1000)- put_messages(log_group, "a", [(now + i, f"match {i}") for i in range(2, 202, 2)])- put_messages(log_group, "b", [(now + i, f"match {i}") for i in range(1, 202, 2)])- # A later request can carry events older than those already stored.- assert logs._put_log_events({- "logGroupName": log_group, "logStreamName": "a",- "logEvents": [{"timestamp": now, "message": "skip"}],- })[0] == 200- checked = count_filter_calls(monkeypatch)- events = filter_events(log_group, filterPattern="match", limit=2)- assert [event["message"] for event in events] == ["match 1", "match 2"]- assert checked == ["skip", "match 1", "match 2"]---def test_time_window_seeks_without_scanning_history(log_group):- now = int(time.time() * 1000)- put_messages(log_group, "history", [(now + i, f"event {i}") for i in range(8192)])- timestamp_reads = []-- class CountedEvent(dict):- def __getitem__(self, key):- if key == "timestamp":- timestamp_reads.append(None)- return super().__getitem__(key)-- stream = logs._log_groups[log_group]["streams"]["history"]- stream["events"] = [CountedEvent(event) for event in stream["events"]]- events = filter_events(log_group, startTime=now + 8000, endTime=now + 8001, limit=10)- assert [event["message"] for event in events] == ["event 8000", "event 8001"]- # Allow headroom for binary searches and merge setup, but no linear scan.- assert len(timestamp_reads) < 100---def test_late_batch_keeps_reads_ordered_and_live_delivery_exact(log_group, monkeypatch):- now = int(time.time() * 1000)- put_messages(log_group, "s", [(now + 30, "newer")])- deliveries = []- monkeypatch.setattr(logs, "_fanout_to_live_tail_sessions",- lambda group, stream, events: deliveries.extend(events))- assert logs._put_log_events({- "logGroupName": log_group, "logStreamName": "s",- "logEvents": [- {"timestamp": now + 10, "message": "older"},- {"timestamp": now + 20, "message": "middle"},- ],- })[0] == 200- response = logs._get_log_events({- "logGroupName": log_group, "logStreamName": "s", "startFromHead": True,- })- assert response[0] == 200- assert [event["message"] for event in json.loads(response[2])["events"]] == [- "older", "middle", "newer",- ]- assert [event["message"] for event in deliveries] == ["older", "middle"]- stored = filter_events(log_group)- assert [event["eventId"] for event in stored[:2]] == [event["eventId"] for event in deliveries]--[email protected]("stream_order", [["a", "b"], ["b", "a"]])-def test_equal_timestamps_keep_selected_stream_and_arrival_order(log_group, stream_order):- now = int(time.time() * 1000)- for stream in ("a", "b"):- put_messages(log_group, stream, [(now, f"{stream} first")])- assert logs._put_log_events({- "logGroupName": log_group, "logStreamName": stream,- "logEvents": [{"timestamp": now, "message": f"{stream} second"}],- })[0] == 200- events = filter_events(log_group, logStreamNames=stream_order, limit=3)- first, second = stream_order- assert [event["message"] for event in events] == [- f"{first} first", f"{first} second", f"{second} first",- ]---def test_legacy_persistence_restores_order_before_limited_reads(log_group, monkeypatch, tmp_path):- from ministack.core import persistence-- now = int(time.time() * 1000)- put_messages(log_group, "s", [(now + i, f"event {i}") for i in range(20)])- state = logs.get_state()- state["log_groups"][log_group]["streams"]["s"]["events"].reverse()- monkeypatch.setattr(persistence, "PERSIST_STATE", True)- monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))- persistence.save_state("cloudwatch_logs", state)- assert logs._delete_log_group({"logGroupName": log_group})[0] == 200- logs.load_persisted_state(persistence.load_state("cloudwatch_logs"))- checked = count_filter_calls(monkeypatch)- events = filter_events(log_group, limit=1)- assert [event["message"] for event in events] == ["event 0"]- assert checked == ["event 0"]--[email protected]("producer", ["codebuild", "dynamodb"])-def test_native_writers_keep_order_after_future_dated_api_event(log_group, monkeypatch, producer):- now = int(time.time() * 1000)- if producer == "codebuild":- from ministack.services import codebuild-- stream_name = "native"- emit = codebuild._log_sink({"logs": {"groupName": log_group, "streamName": stream_name}})- monkeypatch.setattr(codebuild.time, "time", lambda: now / 1000)- else:- from ministack.services import dynamodb-- monkeypatch.setattr(dynamodb, "_IMPORT_LOG_GROUP", log_group)- monkeypatch.setattr(dynamodb.time, "time", lambda: now / 1000)- import_id = uuid.uuid4().hex- stream_name = f"{import_id}/error"-- def emit(message):- dynamodb._log_import_error(f"arn:aws:dynamodb:us-east-1:000000000000:table/t/import/{import_id}",- "bucket", "key", 0, message)-- emit("initial")- assert logs._put_log_events({- "logGroupName": log_group, "logStreamName": stream_name,- "logEvents": [{"timestamp": now + 3000, "message": "future API event"}],- })[0] == 200- emit("later native event")- events = filter_events(log_group, limit=2)- assert len(events) == 2- assert [event["timestamp"] for event in events] == [now, now]- assert "initial" in events[0]["message"]- assert "later native event" in events[1]["message"]---def test_reader_remains_consistent_during_late_arrival(log_group, monkeypatch):- now = int(time.time() * 1000)- put_messages(log_group, "s", [(now + 10, "ten"), (now + 20, "twenty")])- inserted = False-- def matcher(message):- nonlocal inserted- if not inserted:- inserted = True- assert logs._put_log_events({- "logGroupName": log_group, "logStreamName": "s",- "logEvents": [{"timestamp": now, "message": "zero"}],- })[0] == 200- return True-- monkeypatch.setattr(logs, "_compile_filter_pattern", lambda pattern: matcher)- assert [event["message"] for event in filter_events(log_group, limit=2)] == ["ten", "twenty"]- assert [event["message"] for event in filter_events(log_group, limit=2)] == ["zero", "ten"]---def test_mixed_batches_and_ranges_match_stable_reference(log_group):- import random-- randomizer = random.Random(731)- now = int(time.time() * 1000)- arrivals = {name: [] for name in ("a", "b", "c")}- for name in arrivals:- assert logs._create_log_stream({"logGroupName": log_group, "logStreamName": name})[0] == 200- for batch in range(30):- name = randomizer.choice(list(arrivals))- records = [{"timestamp": now + randomizer.randrange(12),- "message": f"{'keep' if index % 2 else 'drop'} {batch}-{index}"}- for index in range(4)]- arrivals[name].extend(records)- assert logs._put_log_events({- "logGroupName": log_group, "logStreamName": name, "logEvents": records,- })[0] == 200- for selection in (["a", "b", "c"], ["c", "a"], ["missing", "b"]):- reference = sorted((dict(event, logStreamName=name)- for name in selection for event in arrivals.get(name, [])),- key=lambda event: event["timestamp"])- for lower, upper in ((0, 11), (3, 7), (5, 5), (9, 2)):- expected = [event for event in reference if now + lower <= event["timestamp"] <= now + upper- and "keep" in event["message"]]- for limit in (1, 7, 10000):- actual = filter_events(log_group, logStreamNames=selection, filterPattern="keep",- startTime=now + lower, endTime=now + upper, limit=limit)- assert [(event["timestamp"], event["message"], event["logStreamName"]) for event in actual] == [- (event["timestamp"], event["message"], event["logStreamName"])- for event in expected[:limit]- ]---def test_concurrent_late_batches_preserve_every_event(log_group):- from concurrent.futures import ThreadPoolExecutor- from threading import Barrier-- from ministack.core.responses import get_account_id, get_region, request_scope-- now = int(time.time() * 1000)- put_messages(log_group, "shared", [])- account, region = get_account_id(), get_region()- barrier = Barrier(4)-- def write(worker):- with request_scope(account, region):- barrier.wait(timeout=5)- for batch in reversed(range(8)):- timestamp = now + batch * 4 + worker- assert logs._put_log_events({- "logGroupName": log_group, "logStreamName": "shared",- "logEvents": [{"timestamp": timestamp, "message": f"event {timestamp}"}],- })[0] == 200-- with ThreadPoolExecutor(max_workers=4) as executor:- futures = [executor.submit(write, worker) for worker in range(4)]- for future in futures:- future.result(timeout=10)- events = filter_events(log_group, limit=100)- assert [event["timestamp"] for event in events] == list(range(now, now + 32))- stream = logs._log_groups[log_group]["streams"]["shared"]- assert stream["firstEventTimestamp"] == now- assert stream["lastEventTimestamp"] == now + 31---def get_page(group, stream, **parameters):- response = logs._get_log_events({"logGroupName": group, "logStreamName": stream, **parameters})- assert response[0] == 200- body = json.loads(response[2])- return [event["message"] for event in body["events"]], body---def test_forward_token_survives_late_arrivals(log_group):- now = int(time.time() * 1000)- put_messages(log_group, "s", [(now + 10, "e10"), (now + 20, "e20"), (now + 30, "e30")])- messages, body = get_page(log_group, "s", startFromHead=True, limit=2)- assert messages == ["e10", "e20"]- # One event lands behind the cursor, one between the cursor and stored history.- assert logs._put_log_events({- "logGroupName": log_group, "logStreamName": "s",- "logEvents": [{"timestamp": now + 15, "message": "e15"},- {"timestamp": now + 25, "message": "e25"}],- })[0] == 200- messages, _ = get_page(log_group, "s", nextToken=body["nextForwardToken"], limit=2)- assert messages == ["e25", "e30"]---def test_backward_token_survives_late_arrivals(log_group):- now = int(time.time() * 1000)- put_messages(log_group, "s", [(now + 10, "e10"), (now + 20, "e20"), (now + 30, "e30")])- messages, body = get_page(log_group, "s", limit=2)- assert messages == ["e20", "e30"]- # e15 is older than everything read so far; e25 is behind the backward cursor.- assert logs._put_log_events({- "logGroupName": log_group, "logStreamName": "s",- "logEvents": [{"timestamp": now + 15, "message": "e15"},- {"timestamp": now + 25, "message": "e25"}],- })[0] == 200- messages, _ = get_page(log_group, "s", nextToken=body["nextBackwardToken"], limit=2)- assert messages == ["e10", "e15"]---def test_backward_token_from_tail_excludes_later_events(log_group):- now = int(time.time() * 1000)- put_messages(log_group, "s", [(now + 10, "e10"), (now + 20, "e20")])- _, body = get_page(log_group, "s", startFromHead=True)- messages, body = get_page(log_group, "s", nextToken=body["nextForwardToken"])- assert messages == []- # e30 arrives after the reader reached the tail.- assert logs._put_log_events({- "logGroupName": log_group, "logStreamName": "s",- "logEvents": [{"timestamp": now + 30, "message": "e30"}],- })[0] == 200- messages, _ = get_page(log_group, "s", nextToken=body["nextBackwardToken"])- assert messages == ["e10", "e20"]---def test_forward_token_splits_equal_timestamps_exactly_once(log_group):- now = int(time.time() * 1000)- put_messages(log_group, "s", [(now, "a"), (now, "b"), (now, "c")])- seen = []- messages, body = get_page(log_group, "s", startFromHead=True, limit=1)- seen += messages- # An equal-time arrival sorts after existing ties, so it is still ahead of the cursor.- assert logs._put_log_events({- "logGroupName": log_group, "logStreamName": "s",- "logEvents": [{"timestamp": now, "message": "d"}],- })[0] == 200- for _ in range(5):- messages, body = get_page(log_group, "s", nextToken=body["nextForwardToken"], limit=1)- if not messages:- break- seen += messages- assert seen == ["a", "b", "c", "d"]diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 8070f35e..ada92b58 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -4878,8 +4878,7 @@ def test_oauth2_token_client_credentials_rejects_invalid_scopes(requested, errorstatus, _, body = _post_form(f'{ENDPOINT}/oauth2/token', form, headers=headers)response = json.loads(body)assert status == 400, body- assert response['error'] == error- assert 'access_token' not in response+ assert response == {'error': error}finally:cognito_idp.delete_user_pool(UserPoolId=pool_id)diff --git a/tests/test_kms.py b/tests/test_kms.pyindex 69d27d7b..cccecdf6 100644--- a/tests/test_kms.py+++ b/tests/test_kms.py@@ -2870,3 +2870,61 @@ def test_kms_create_grant_rejects_primary_pending_replica_deletion():assert east.list_grants(KeyId=key_id)["Grants"] == []finally:west.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)++[email protected]("days,accepted", [(6, False), (7, True), (30, True), (31, False)])+def test_kms_schedule_key_deletion_window_is_7_to_30_days(kms_client, days, accepted):+ key_id = kms_client.create_key()["KeyMetadata"]["KeyId"]+ if accepted:+ assert kms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=days)["KeyState"] == "PendingDeletion"+ else:+ with pytest.raises(ClientError) as exc:+ kms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=days)+ assert exc.value.response["Error"] == {"Code": "ValidationException",+ "Message": "PendingWindowInDays must be between 7 and 30"}+ assert kms_client.describe_key(KeyId=key_id)["KeyMetadata"]["KeyState"] == "Enabled"+++def test_kms_rsassa_pss_uses_a_digest_length_salt(kms_client):+ import hashlib++ from cryptography.hazmat.primitives import hashes, serialization+ from cryptography.hazmat.primitives.asymmetric import padding, utils++ key_id = kms_client.create_key(KeySpec="RSA_2048", KeyUsage="SIGN_VERIFY")["KeyMetadata"]["KeyId"]+ digest = hashlib.sha256(b"payload").digest()+ signature = kms_client.sign(KeyId=key_id, Message=digest, MessageType="DIGEST",+ SigningAlgorithm="RSASSA_PSS_SHA_256")["Signature"]+ public_key = serialization.load_der_public_key(kms_client.get_public_key(KeyId=key_id)["PublicKey"])+ public_key.verify(signature, digest, padding.PSS(mgf=padding.MGF1(hashes.SHA256()),+ salt_length=padding.PSS.DIGEST_LENGTH),+ utils.Prehashed(hashes.SHA256()))+++def test_kms_rsa_encryption_honours_the_named_algorithm(kms_client):+ from cryptography.hazmat.primitives import hashes, serialization+ from cryptography.hazmat.primitives.asymmetric import padding++ key_id = kms_client.create_key(KeySpec="RSA_2048", KeyUsage="ENCRYPT_DECRYPT")["KeyMetadata"]["KeyId"]+ public_key = serialization.load_der_public_key(kms_client.get_public_key(KeyId=key_id)["PublicKey"])+ sha256 = padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None)+ blob = public_key.encrypt(b"secret", sha256)+ with pytest.raises(ClientError) as exc:+ kms_client.decrypt(KeyId=key_id, CiphertextBlob=blob, EncryptionAlgorithm="RSAES_OAEP_SHA_1")+ assert exc.value.response["Error"]["Code"] == "InvalidCiphertextException"+ assert kms_client.decrypt(KeyId=key_id, CiphertextBlob=blob,+ EncryptionAlgorithm="RSAES_OAEP_SHA_256")["Plaintext"] == b"secret"+ sha1_blob = kms_client.encrypt(KeyId=key_id, Plaintext=b"secret", EncryptionAlgorithm="RSAES_OAEP_SHA_1")["CiphertextBlob"]+ assert kms_client.decrypt(KeyId=key_id, CiphertextBlob=sha1_blob,+ EncryptionAlgorithm="RSAES_OAEP_SHA_1")["Plaintext"] == b"secret"+++def test_kms_sign_refuses_a_wrong_digest_length_or_algorithm(kms_client):+ ec_key = kms_client.create_key(KeySpec="ECC_NIST_P256", KeyUsage="SIGN_VERIFY")["KeyMetadata"]["KeyId"]+ with pytest.raises(ClientError) as exc:+ kms_client.sign(KeyId=ec_key, Message=b"x" * 20, MessageType="DIGEST", SigningAlgorithm="ECDSA_SHA_256")+ err = exc.value.response+ assert (err["Error"]["Code"], err["ResponseMetadata"]["HTTPStatusCode"]) == ("ValidationException", 400)+ with pytest.raises(ClientError) as exc:+ kms_client.sign(KeyId=ec_key, Message=b"x" * 32, MessageType="DIGEST", SigningAlgorithm="RSASSA_PSS_SHA_256")+ assert exc.value.response["Error"]["Code"] == "InvalidKeyUsageException"diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex a541f787..fa1c4293 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -1,6 +1,7 @@import asyncioimport base64import contextlib+import copyimport ioimport jsonimport os@@ -13,6 +14,7 @@ import urllib.error as _urlerrimport urllib.request as _urlreqimport uuid as _uuid_modimport zipfile+from concurrent.futures import ThreadPoolExecutorfrom http.server import BaseHTTPRequestHandler, HTTPServerfrom unittest.mock import Mock, patchfrom urllib.parse import quote, urlparse@@ -32,6 +34,9 @@ from conftest import (routed_request,)+from ministack.core.responses import AccountRegionScopedDict, request_scope+from ministack.services import lambda_svc as _lambda_mod+_endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")_EXECUTE_PORT = urlparse(_endpoint).port or 4566@@ -14992,3 +14997,175 @@ def test_lambda_env_disables_host_prefix_injection_by_default(lam):finally:lam.delete_function(FunctionName=name)lam.delete_function(FunctionName=own)+++def functions(monkeypatch):+ store = AccountRegionScopedDict()+ for name in ("revision-test", "unrelated"):+ store[name] = {+ "config": {"RevisionId": "function-before", "Architectures": ["x86_64"],+ "Description": "original", "Version": "$LATEST"},+ "code_zip": b"original-code", "versions": {}, "next_version": 1,+ "aliases": {alias: {"RevisionId": "alias-before", "FunctionVersion": "1",+ "Description": "original"} for alias in ("live", "other")},+ }+ monkeypatch.setattr(_lambda_mod, "_functions", store)+ for helper in ("invalidate_worker", "_pool_kill_function", "_sweep_extract_cache",+ "_schedule_state_transition", "_snapstart_provision_version_async"):+ monkeypatch.setattr(_lambda_mod, helper, Mock())+ return store+++def _update(operation, revision="function-before", value="changed", name="revision-test"):+ data = {"RevisionId": revision} if revision is not None else {}+ if operation == "code":+ return _lambda_mod._update_code(name, {**data, "ZipFile": base64.b64encode(value.encode()).decode()})+ if operation == "config":+ return _lambda_mod._update_config(name, {**data, "Description": value})+ return _lambda_mod._update_alias(name, "live", {**data, "Description": value, "FunctionVersion": "2"})++[email protected]("operation", ["code", "config", "alias"])+def test_stale_revision_rejects_before_mutation_or_side_effects(functions, monkeypatch, operation):+ fetch = Mock(side_effect=AssertionError("stale request fetched code"))+ monkeypatch.setattr(_lambda_mod, "_fetch_code_from_s3", fetch)+ before = copy.deepcopy(functions._data)+ if operation == "code":+ result = _lambda_mod._update_code("revision-test", {+ "RevisionId": "stale", "S3Bucket": "unused", "S3Key": "unused",+ "Architectures": ["arm64"], "Publish": True,+ "S3ObjectStorageMode": "CustomerManaged", "SourceKMSKeyArn": "changed",+ })+ elif operation == "config":+ result = _lambda_mod._update_config("revision-test", {+ "RevisionId": "stale", "Description": "changed", "MemorySize": 512,+ "Environment": {"Variables": {"CHANGED": "true"}},+ })+ else:+ result = _lambda_mod._update_alias("revision-test", "live", {+ "RevisionId": "stale", "FunctionVersion": "2", "Description": "changed",+ "RoutingConfig": {"AdditionalVersionWeights": {"3": 0.1}},+ })+ status, _, body = result+ assert status == 412+ assert json.loads(body)["__type"] == "PreconditionFailedException"+ assert functions._data == before+ fetch.assert_not_called()+ for helper in (_lambda_mod.invalidate_worker, _lambda_mod._pool_kill_function, _lambda_mod._sweep_extract_cache,+ _lambda_mod._schedule_state_transition, _lambda_mod._snapstart_provision_version_async):+ helper.assert_not_called()++[email protected]("operation", ["code", "config", "alias"])+def test_matching_and_omitted_revisions_allow_updates(functions, operation):+ revision = "alias-before" if operation == "alias" else "function-before"+ status, _, body = _update(operation, revision)+ assert status == 200+ updated = json.loads(body)+ assert updated["RevisionId"] != revision+ assert _update(operation, revision)[0] == 412+ assert _update(operation, updated["RevisionId"])[0] == 200+ assert _update(operation, None)[0] == 200++[email protected]("style", ["keyword", "mixed", "data-keyword"])+def test_revision_updates_preserve_keyword_call_support(functions, style):+ assert _lambda_mod._update_code(name="revision-test", data={"RevisionId": "function-before"})[0] == 200+ revision = functions["revision-test"]["config"]["RevisionId"]+ assert _lambda_mod._update_config(name="revision-test", data={"RevisionId": revision})[0] == 200+ data = {"RevisionId": "alias-before"}+ if style == "keyword":+ result = _lambda_mod._update_alias(func_name="revision-test", alias_name="live", data=data)+ elif style == "mixed":+ result = _lambda_mod._update_alias("revision-test", alias_name="live", data=data)+ else:+ result = _lambda_mod._update_alias("revision-test", "live", data=data)+ assert result[0] == 200++[email protected]("first,second", [("code", "code"), ("code", "config"),+ ("config", "code"), ("config", "config"),+ ("alias", "alias")])+def test_competing_updates_with_same_revision_have_one_winner(functions, monkeypatch, first, second):+ entered, release, second_started, second_done = (threading.Event() for _ in range(4))+ helper = "new_uuid" if first == "alias" else "_now_iso"+ original = getattr(_lambda_mod, helper)+ first_thread = []++ def pause_first():+ if threading.get_ident() == first_thread[0] and not entered.is_set():+ entered.set()+ assert release.wait(5), "first update was not released"+ return original()++ monkeypatch.setattr(_lambda_mod, helper, pause_first)+ revision = "alias-before" if first == "alias" else "function-before"++ def run_first():+ first_thread.append(threading.get_ident())+ return _update(first, revision, "winner")++ def run_second():+ second_started.set()+ try:+ return _update(second, revision, "loser")+ finally:+ second_done.set()++ with ThreadPoolExecutor(max_workers=2) as pool:+ winner = pool.submit(run_first)+ try:+ assert entered.wait(5), "first update never reached mutation"+ loser = pool.submit(run_second)+ assert second_started.wait(5)+ # Let an unguarded contender finish while the first revision is+ # still current; a correctly serialized contender must wait.+ second_done.wait(0.3)+ finally:+ release.set()+ assert winner.result(timeout=5)[0] == 200+ assert loser.result(timeout=5)[0] == 412+ record = functions["revision-test"]+ if first == "alias":+ assert record["aliases"]["live"]["Description"] == "winner"+ elif first == "code":+ assert record["code_zip"] == b"winner"+ assert record["config"]["Description"] == "original"+ else:+ assert record["config"]["Description"] == "winner"+ assert record["code_zip"] == b"original-code"+++def test_slow_code_update_does_not_block_independent_resources(functions, monkeypatch):+ entered, release = threading.Event(), threading.Event()+ prototype = copy.deepcopy(functions["revision-test"])++ def fetch(*args, **kwargs):+ entered.set()+ assert release.wait(5)+ return b"new-code"++ monkeypatch.setattr(_lambda_mod, "_fetch_code_from_s3", fetch)+ with ThreadPoolExecutor(max_workers=2) as pool:+ slow = pool.submit(_lambda_mod._update_code, "revision-test", {+ "RevisionId": "function-before", "S3Bucket": "unused", "S3Key": "unused"})+ try:+ assert entered.wait(5)+ assert pool.submit(_update, "config", name="unrelated").result(timeout=2)[0] == 200+ assert pool.submit(_update, "alias", "alias-before").result(timeout=2)[0] == 200+ for account, region in (("222222222222", "us-east-1"), ("000000000000", "eu-west-1")):+ def other_tenant():+ with request_scope(account, region):+ functions["revision-test"] = copy.deepcopy(prototype)+ return _update("config")+ assert pool.submit(other_tenant).result(timeout=2)[0] == 200+ finally:+ release.set()+ assert slow.result(timeout=5)[0] == 200++[email protected]("operation", ["code", "config", "alias"])+def test_missing_resource_keeps_not_found_response(functions, operation):+ assert _update(operation, "stale", name="missing")[0] == 404+ assert _lambda_mod._update_alias("revision-test", "missing", {"RevisionId": "stale"})[0] == 404diff --git a/tests/test_lambda_revision.py b/tests/test_lambda_revision.pydeleted file mode 100644index 15090ced..00000000--- a/tests/test_lambda_revision.py+++ /dev/null@@ -1,186 +0,0 @@-# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT-"""Conditional Lambda updates reject stale revisions before any side effects."""--import base64-import copy-import json-import threading-from concurrent.futures import ThreadPoolExecutor-from unittest.mock import Mock--import pytest--from ministack.core.responses import AccountRegionScopedDict, request_scope-from ministack.services import lambda_svc as svc---def functions(monkeypatch):- store = AccountRegionScopedDict()- for name in ("revision-test", "unrelated"):- store[name] = {- "config": {"RevisionId": "function-before", "Architectures": ["x86_64"],- "Description": "original", "Version": "$LATEST"},- "code_zip": b"original-code", "versions": {}, "next_version": 1,- "aliases": {alias: {"RevisionId": "alias-before", "FunctionVersion": "1",- "Description": "original"} for alias in ("live", "other")},- }- monkeypatch.setattr(svc, "_functions", store)- for helper in ("invalidate_worker", "_pool_kill_function", "_sweep_extract_cache",- "_schedule_state_transition", "_snapstart_provision_version_async"):- monkeypatch.setattr(svc, helper, Mock())- return store---def _update(operation, revision="function-before", value="changed", name="revision-test"):- data = {"RevisionId": revision} if revision is not None else {}- if operation == "code":- return svc._update_code(name, {**data, "ZipFile": base64.b64encode(value.encode()).decode()})- if operation == "config":- return svc._update_config(name, {**data, "Description": value})- return svc._update_alias(name, "live", {**data, "Description": value, "FunctionVersion": "2"})--[email protected]("operation", ["code", "config", "alias"])-def test_stale_revision_rejects_before_mutation_or_side_effects(functions, monkeypatch, operation):- fetch = Mock(side_effect=AssertionError("stale request fetched code"))- monkeypatch.setattr(svc, "_fetch_code_from_s3", fetch)- before = copy.deepcopy(functions._data)- if operation == "code":- result = svc._update_code("revision-test", {- "RevisionId": "stale", "S3Bucket": "unused", "S3Key": "unused",- "Architectures": ["arm64"], "Publish": True,- "S3ObjectStorageMode": "CustomerManaged", "SourceKMSKeyArn": "changed",- })- elif operation == "config":- result = svc._update_config("revision-test", {- "RevisionId": "stale", "Description": "changed", "MemorySize": 512,- "Environment": {"Variables": {"CHANGED": "true"}},- })- else:- result = svc._update_alias("revision-test", "live", {- "RevisionId": "stale", "FunctionVersion": "2", "Description": "changed",- "RoutingConfig": {"AdditionalVersionWeights": {"3": 0.1}},- })- status, _, body = result- assert status == 412- assert json.loads(body)["__type"] == "PreconditionFailedException"- assert functions._data == before- fetch.assert_not_called()- for helper in (svc.invalidate_worker, svc._pool_kill_function, svc._sweep_extract_cache,- svc._schedule_state_transition, svc._snapstart_provision_version_async):- helper.assert_not_called()--[email protected]("operation", ["code", "config", "alias"])-def test_matching_and_omitted_revisions_allow_updates(functions, operation):- revision = "alias-before" if operation == "alias" else "function-before"- status, _, body = _update(operation, revision)- assert status == 200- updated = json.loads(body)- assert updated["RevisionId"] != revision- assert _update(operation, revision)[0] == 412- assert _update(operation, updated["RevisionId"])[0] == 200- assert _update(operation, None)[0] == 200--[email protected]("style", ["keyword", "mixed", "data-keyword"])-def test_revision_updates_preserve_keyword_call_support(functions, style):- assert svc._update_code(name="revision-test", data={"RevisionId": "function-before"})[0] == 200- revision = functions["revision-test"]["config"]["RevisionId"]- assert svc._update_config(name="revision-test", data={"RevisionId": revision})[0] == 200- data = {"RevisionId": "alias-before"}- if style == "keyword":- result = svc._update_alias(func_name="revision-test", alias_name="live", data=data)- elif style == "mixed":- result = svc._update_alias("revision-test", alias_name="live", data=data)- else:- result = svc._update_alias("revision-test", "live", data=data)- assert result[0] == 200--[email protected]("first,second", [("code", "code"), ("code", "config"),- ("config", "code"), ("config", "config"),- ("alias", "alias")])-def test_competing_updates_with_same_revision_have_one_winner(functions, monkeypatch, first, second):- entered, release, second_started, second_done = (threading.Event() for _ in range(4))- helper = "new_uuid" if first == "alias" else "_now_iso"- original = getattr(svc, helper)- first_thread = []-- def pause_first():- if threading.get_ident() == first_thread[0] and not entered.is_set():- entered.set()- assert release.wait(5), "first update was not released"- return original()-- monkeypatch.setattr(svc, helper, pause_first)- revision = "alias-before" if first == "alias" else "function-before"-- def run_first():- first_thread.append(threading.get_ident())- return _update(first, revision, "winner")-- def run_second():- second_started.set()- try:- return _update(second, revision, "loser")- finally:- second_done.set()-- with ThreadPoolExecutor(max_workers=2) as pool:- winner = pool.submit(run_first)- try:- assert entered.wait(5), "first update never reached mutation"- loser = pool.submit(run_second)- assert second_started.wait(5)- # Let an unguarded contender finish while the first revision is- # still current; a correctly serialized contender must wait.- second_done.wait(0.3)- finally:- release.set()- assert winner.result(timeout=5)[0] == 200- assert loser.result(timeout=5)[0] == 412- record = functions["revision-test"]- if first == "alias":- assert record["aliases"]["live"]["Description"] == "winner"- elif first == "code":- assert record["code_zip"] == b"winner"- assert record["config"]["Description"] == "original"- else:- assert record["config"]["Description"] == "winner"- assert record["code_zip"] == b"original-code"---def test_slow_code_update_does_not_block_independent_resources(functions, monkeypatch):- entered, release = threading.Event(), threading.Event()- prototype = copy.deepcopy(functions["revision-test"])-- def fetch(*args, **kwargs):- entered.set()- assert release.wait(5)- return b"new-code"-- monkeypatch.setattr(svc, "_fetch_code_from_s3", fetch)- with ThreadPoolExecutor(max_workers=2) as pool:- slow = pool.submit(svc._update_code, "revision-test", {- "RevisionId": "function-before", "S3Bucket": "unused", "S3Key": "unused"})- try:- assert entered.wait(5)- assert pool.submit(_update, "config", name="unrelated").result(timeout=2)[0] == 200- assert pool.submit(_update, "alias", "alias-before").result(timeout=2)[0] == 200- for account, region in (("222222222222", "us-east-1"), ("000000000000", "eu-west-1")):- def other_tenant():- with request_scope(account, region):- functions["revision-test"] = copy.deepcopy(prototype)- return _update("config")- assert pool.submit(other_tenant).result(timeout=2)[0] == 200- finally:- release.set()- assert slow.result(timeout=5)[0] == 200--[email protected]("operation", ["code", "config", "alias"])-def test_missing_resource_keeps_not_found_response(functions, operation):- assert _update(operation, "stale", name="missing")[0] == 404- assert svc._update_alias("revision-test", "missing", {"RevisionId": "stale"})[0] == 404diff --git a/tests/test_s3.py b/tests/test_s3.pyindex f2102111..cb166590 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -1,3 +1,4 @@+import asyncioimport base64import contextlibimport hashlib@@ -10,12 +11,20 @@ import uuidimport uuid as _uuid_modfrom datetime import datetimefrom urllib.parse import urlparse+from xml.etree import ElementTree+import boto3import pytest+import requestsfrom botocore.config import Configfrom botocore.exceptions import ClientErrorfrom conftest import inprocess_iam_user, make_client, patch_endpoint_dns, routed_request, sqs_policy_allow_s3+from ministack.core.responses import AccountScopedDict, request_scope+from ministack.services import iam as _iam_mod+from ministack.services import s3 as _s3_mod+from ministack.services import sts as _sts_mod+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")# Last-Modified on S3 HTTP responses must be RFC 7231 HTTP-date (AWS / Smithy).@@ -1482,45 +1491,32 @@ def test_s3_object_legal_hold(s3):assert resp["LegalHold"]["Status"] == "OFF"def test_s3_object_lock_prevents_delete(s3):+ """A delete naming a locked version is refused; a plain delete adds a delete marker (Object Lock docs)."""+ from datetime import datetime, timedelta, timezone+bkt = "intg-s3-lock-del"s3.create_bucket(Bucket=bkt, ObjectLockEnabledForBucket=True)- s3.put_object(Bucket=bkt, Key="locked.txt", Body=b"immutable")-- s3.put_object_legal_hold(- Bucket=bkt,- Key="locked.txt",- LegalHold={"Status": "ON"},- )+ version = s3.put_object(Bucket=bkt, Key="locked.txt", Body=b"immutable")["VersionId"]+ s3.put_object_legal_hold(Bucket=bkt, Key="locked.txt", LegalHold={"Status": "ON"})with pytest.raises(ClientError) as exc:- s3.delete_object(Bucket=bkt, Key="locked.txt")+ s3.delete_object(Bucket=bkt, Key="locked.txt", VersionId=version)assert exc.value.response["Error"]["Code"] == "AccessDenied"- # Remove legal hold, add governance retention- s3.put_object_legal_hold(- Bucket=bkt,- Key="locked.txt",- LegalHold={"Status": "OFF"},- )- from datetime import datetime, timedelta, timezone+ marker = s3.delete_object(Bucket=bkt, Key="locked.txt")+ assert marker["DeleteMarker"] is True+ assert s3.get_object(Bucket=bkt, Key="locked.txt", VersionId=version)["Body"].read() == b"immutable"+ assert s3.get_object_legal_hold(Bucket=bkt, Key="locked.txt", VersionId=version)["LegalHold"]["Status"] == "ON"+ s3.put_object_legal_hold(Bucket=bkt, Key="locked.txt", VersionId=version, LegalHold={"Status": "OFF"})retain_until = datetime.now(timezone.utc) + timedelta(days=1)- s3.put_object_retention(- Bucket=bkt,- Key="locked.txt",- Retention={"Mode": "GOVERNANCE", "RetainUntilDate": retain_until},- )+ s3.put_object_retention(Bucket=bkt, Key="locked.txt", VersionId=version,+ Retention={"Mode": "GOVERNANCE", "RetainUntilDate": retain_until})with pytest.raises(ClientError) as exc:- s3.delete_object(Bucket=bkt, Key="locked.txt")+ s3.delete_object(Bucket=bkt, Key="locked.txt", VersionId=version)assert exc.value.response["Error"]["Code"] == "AccessDenied"-- # Bypass governance retention- s3.delete_object(- Bucket=bkt,- Key="locked.txt",- BypassGovernanceRetention=True,- )+ s3.delete_object(Bucket=bkt, Key="locked.txt", VersionId=version, BypassGovernanceRetention=True)with pytest.raises(ClientError):- s3.head_object(Bucket=bkt, Key="locked.txt")+ s3.get_object(Bucket=bkt, Key="locked.txt", VersionId=version)def test_s3_bucket_replication(s3):src = "intg-s3-repl-src"@@ -1638,17 +1634,20 @@ def test_s3_default_retention_applied(s3):def test_s3_batch_delete_enforces_lock(s3):bkt = "intg-s3-batch-lock"s3.create_bucket(Bucket=bkt, ObjectLockEnabledForBucket=True)- s3.put_object(Bucket=bkt, Key="a.txt", Body=b"a")- s3.put_object(Bucket=bkt, Key="b.txt", Body=b"b")+ a_version = s3.put_object(Bucket=bkt, Key="a.txt", Body=b"a")["VersionId"]+ b_version = s3.put_object(Bucket=bkt, Key="b.txt", Body=b"b")["VersionId"]s3.put_object_legal_hold(Bucket=bkt, Key="a.txt", LegalHold={"Status": "ON"})resp = s3.delete_objects(Bucket=bkt,- Delete={"Objects": [{"Key": "a.txt"}, {"Key": "b.txt"}]},+ Delete={"Objects": [{"Key": "a.txt", "VersionId": a_version}, {"Key": "b.txt", "VersionId": b_version}]},)deleted_keys = [d["Key"] for d in resp.get("Deleted", [])]error_keys = [e["Key"] for e in resp.get("Errors", [])]assert "b.txt" in deleted_keysassert "a.txt" in error_keys+ # Without a VersionId the locked key just gets a delete marker.+ resp = s3.delete_objects(Bucket=bkt, Delete={"Objects": [{"Key": "a.txt"}]})+ assert resp["Deleted"][0]["DeleteMarker"] is Truedef test_s3_copy_preserves_tags_and_lock(s3):src = "intg-s3-copy-tag-src"@@ -9184,3 +9183,323 @@ def test_s3_post_permission_contract(assert response.status_code == 204, response.textwith s3.get_object(Bucket=destination, Key="copied")["Body"] as body:assert body.read() == b"post-auth-contract"+++def post_form(monkeypatch):+ import ministack.app as app_mod++ monkeypatch.setattr(app_mod, "AUTH", False)+ monkeypatch.setattr(_s3_mod, "_buckets", AccountScopedDict())+ monkeypatch.setattr(_s3_mod, "S3_PERSIST", False)+ with request_scope("000000000000", "us-east-1"):+ bucket = "post-policy-" + uuid.uuid4().hex[:12]+ key, _arn = inprocess_iam_user({"Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]})+ _s3_mod._create_bucket(bucket, b"", {})++ class Form:+ def generate(self, *, fields=None, conditions=None, key_name="uploads/data.txt", expires=300,+ secret=None, token=None, access_key=None, signature_version="s3v4"):+ client = boto3.client(+ "s3", endpoint_url="http://localhost", region_name="us-east-1",+ aws_access_key_id=access_key or key[0], aws_secret_access_key=secret or key[1],+ aws_session_token=token, config=Config(signature_version=signature_version),+ )+ return client.generate_presigned_post(+ Bucket=bucket, Key=key_name, Fields=fields or {},+ Conditions=conditions or [], ExpiresIn=expires,+ )["fields"]++ def submit(self, fields, *, data=b"contents", filename="data.txt", routed=False):+ req = requests.Request(+ "POST", "http://localhost/" + bucket,+ data=fields, files={"file": (filename, data)},+ ).prepare()+ headers = {name.lower(): value for name, value in req.headers.items()}+ if routed:+ return routed_request(None, "s3", "POST", "/" + bucket,+ body=req.body, headers=headers)+ return asyncio.run(_s3_mod.handle_request("POST", "/" + bucket, headers, req.body, {}))++ def assert_rejected(self, fields, code, **kwargs):+ response = self.submit(fields, **kwargs)+ assert response[0] in (400, 403)+ assert ElementTree.fromstring(response[2]).findtext("Code") == code+ assert _s3_mod._buckets[bucket]["objects"] == {}++ form = Form()+ form.bucket, form.key = bucket, key+ yield form+ _iam_mod._access_keys.pop(key[0], None)+ name = _arn.rsplit("/", 1)[-1]+ _iam_mod._users.pop(name, None)+ _iam_mod._user_inline_policies.pop(name, None)++[email protected]("signature_version", ["s3v4", "s3"])+def test_signed_post_stores_bytes_and_metadata(post_form, signature_version):+ fields = post_form.generate(fields={"x-amz-meta-author": "alice", "success_action_status": "201"},+ conditions=[{"x-amz-meta-author": "alice"}, {"success_action_status": "201"}],+ signature_version=signature_version)+ assert post_form.submit(fields)[0] == 201+ obj = _s3_mod._buckets[post_form.bucket]["objects"]["uploads/data.txt"]+ assert obj["body"] == b"contents"+ assert obj["metadata"] == {"x-amz-meta-author": "alice"}++[email protected]("name,value", [("key", "uploads/other.txt"), ("Content-Type", "text/plain"),+ ("x-amz-meta-author", "bob"), ("success_action_status", "204")])+def test_post_exact_conditions_reject_mismatched_fields(post_form, name, value):+ fields = {"Content-Type": "application/json", "x-amz-meta-author": "alice", "success_action_status": "201"}+ form = post_form.generate(fields=fields, conditions=[{k: v} for k, v in fields.items()])+ form[name] = value+ post_form.assert_rejected(form, "AccessDenied")+++def post_auth(monkeypatch):+ import ministack.app as app_mod++ monkeypatch.setattr(app_mod, "AUTH", True)++[email protected]("signature_version", ["s3v4", "s3"])[email protected]("auth_enabled", [False, True])+def test_post_signature_verified_under_auth_only(post_form, monkeypatch, auth_enabled, signature_version):+ import ministack.app as app_mod++ monkeypatch.setattr(app_mod, "AUTH", auth_enabled)+ form = post_form.generate(secret=uuid.uuid4().hex, signature_version=signature_version)+ if auth_enabled:+ post_form.assert_rejected(form, "SignatureDoesNotMatch", routed=True)+ else:+ assert post_form.submit(form, routed=True)[0] == 204++[email protected]("missing", ["x-amz-signature", "x-amz-date", "x-amz-credential", "policy"])+def test_incomplete_sigv4_form_rejected(post_form, missing):+ form = post_form.generate()+ del form[missing]+ post_form.assert_rejected(form, "InvalidArgument")+++def test_expired_post_policy_rejected(post_form):+ post_form.assert_rejected(post_form.generate(expires=-60), "AccessDenied")++[email protected]("content_type,accepted", [("image/png,image/jpeg", True), ("image/png,text/plain", False)])+def test_post_content_type_prefix_applies_to_each_list_item(post_form, content_type, accepted):+ form = post_form.generate(fields={"Content-Type": content_type},+ conditions=[["starts-with", "$Content-Type", "image/"]])+ if accepted:+ assert post_form.submit(form)[0] == 204+ else:+ post_form.assert_rejected(form, "AccessDenied")+++def test_post_variables_expanded_before_matching(post_form):+ form = post_form.generate(key_name="uploads/${filename}", fields={"x-amz-meta-name": "${filename}"},+ conditions=[["eq", "$x-amz-meta-name", "data.txt"]])+ assert post_form.submit(form)[0] == 204+ obj = _s3_mod._buckets[post_form.bucket]["objects"]["uploads/data.txt"]+ assert obj["metadata"]["x-amz-meta-name"] == "data.txt"+++def test_post_variables_expanded_once(post_form):+ form = post_form.generate(key_name="uploads/${filename}")+ assert post_form.submit(form, filename="${filename}.txt")[0] == 204+ assert list(_s3_mod._buckets[post_form.bucket]["objects"]) == ["uploads/${filename}.txt"]++[email protected]("extra", ["x-amz-meta-extra", "acl"])+def test_post_uncovered_form_fields_rejected(post_form, extra):+ form = post_form.generate(fields={extra: "private"})+ post_form.assert_rejected(form, "AccessDenied")+++def test_post_missing_condition_field_rejected(post_form):+ form = post_form.generate(conditions=[["starts-with", "$x-amz-meta-required", ""]])+ post_form.assert_rejected(form, "AccessDenied")+++def test_post_ignore_fields_exempt_from_conditions(post_form):+ assert post_form.submit(post_form.generate(fields={"x-ignore-client": "local"}))[0] == 204++[email protected]("data,code", [(b"a", "EntityTooSmall"), (b"1234", "EntityTooLarge"), (b"12", None), (b"123", None)])+def test_post_size_range_inclusive(post_form, data, code):+ form = post_form.generate(conditions=[["content-length-range", 2, 3]])+ if code:+ post_form.assert_rejected(form, code, data=data)+ else:+ assert post_form.submit(form, data=data)[0] == 204++[email protected]("low,code", [("2", None), ("x", "AccessDenied")])+def test_post_size_range_string_bounds(post_form, low, code):+ form = post_form.generate(conditions=[["content-length-range", low, "3"]])+ if code:+ post_form.assert_rejected(form, code, data=b"12")+ else:+ assert post_form.submit(form, data=b"12")[0] == 204+++def test_post_modified_policy_fails_signature(post_form, post_auth):+ form = post_form.generate()+ form["policy"] = form["policy"][:-2]+ post_form.assert_rejected(form, "SignatureDoesNotMatch")+++def test_post_invalid_condition_rejected(post_form):+ post_form.assert_rejected(post_form.generate(conditions=[["unknown", "$key", ""]]), "InvalidPolicyDocument")+++def test_post_policy_refusals_use_aws_messages(post_form):+ def message(form):+ return ElementTree.fromstring(post_form.submit(form)[2]).findtext("Message")+ form = post_form.generate(fields={"x-amz-meta-author": "alice"}, conditions=[{"x-amz-meta-author": "alice"}])+ form["x-amz-meta-author"] = "bob"+ assert message(form) == 'Invalid according to Policy: Policy Condition failed: ["eq", "$x-amz-meta-author", "alice"]'+ assert message(post_form.generate(expires=-60)) == "Invalid according to Policy: Policy expired."+ assert message(post_form.generate(fields={"x-amz-meta-extra": "x"})) == (+ "Invalid according to Policy: Extra input fields: x-amz-meta-extra")+++def test_post_bucket_condition_uses_destination(post_form):+ post_form.assert_rejected(post_form.generate(conditions=[{"bucket": "different-bucket"}]), "AccessDenied")+++def test_post_inactive_registered_key_rejected(post_form, post_auth):+ form = post_form.generate()+ _iam_mod._access_keys[post_form.key[0]]["Status"] = "Inactive"+ post_form.assert_rejected(form, "InvalidAccessKeyId")+++def test_post_unexpected_session_token_rejected(post_form, post_auth):+ post_form.assert_rejected(post_form.generate(token=uuid.uuid4().hex), "InvalidToken")+++def test_post_registered_key_resolves_nondefault_account(post_form):+ with request_scope("123456789012", "us-east-1"):+ key, arn = inprocess_iam_user()+ try:+ bucket = "tenant-post-" + uuid.uuid4().hex[:12]+ _s3_mod._create_bucket(bucket, b"", {})+ client = boto3.client("s3", endpoint_url="http://localhost", region_name="us-east-1",+ aws_access_key_id=key[0], aws_secret_access_key=key[1],+ config=Config(signature_version="s3v4"))+ form = client.generate_presigned_post(Bucket=bucket, Key="uploads/data.txt")["fields"]+ # submit() captures the fixture bucket, so route this request explicitly.+ req = requests.Request("POST", "http://localhost/" + bucket, data=form,+ files={"file": ("data.txt", b"tenant")}).prepare()+ result = asyncio.run(_s3_mod.handle_request("POST", "/" + bucket,+ {k.lower(): v for k, v in req.headers.items()}, req.body, {}))+ assert result[0] == 204+ assert _s3_mod._buckets[bucket]["objects"]["uploads/data.txt"]["body"] == b"tenant"+ finally:+ _iam_mod._access_keys.pop(key[0], None)+ _iam_mod._users.pop(arn.rsplit("/", 1)[-1], None)++[email protected]("signature", ["", "not-hex", "é" * 64])+def test_post_malformed_signature_is_a_client_error(post_form, post_auth, signature):+ form = post_form.generate()+ form["x-amz-signature"] = signature+ post_form.assert_rejected(form, "InvalidArgument" if not signature else "SignatureDoesNotMatch")++[email protected]("token_state", ["valid", "missing", "incorrect", "expired"])+def test_post_uses_sts_issued_credentials(post_form, post_auth, token_state):+ response = routed_request(post_form.key, "sts", "POST", "/",+ body=b"Action=GetSessionToken&DurationSeconds=900",+ headers={"content-type": "application/x-www-form-urlencoded"})+ assert response[0] == 200+ root = ElementTree.fromstring(response[2])+ credentials = {name: root.findtext(".//{*}" + name) for name in ("AccessKeyId", "SecretAccessKey", "SessionToken")}+ access_key = credentials["AccessKeyId"]+ try:+ token = credentials["SessionToken"]+ if token_state == "missing":+ token = None+ elif token_state == "incorrect":+ token = uuid.uuid4().hex+ elif token_state == "expired":+ _sts_mod._sessions[access_key]["Expiration"] = time.time() - 60+ form = post_form.generate(access_key=access_key, secret=credentials["SecretAccessKey"], token=token)+ if token_state == "valid":+ assert post_form.submit(form)[0] == 204+ else:+ post_form.assert_rejected(form, "ExpiredToken" if token_state == "expired" else "InvalidToken")+ finally:+ _sts_mod._sessions.pop(access_key, None)+++def test_post_configured_root_credentials(post_form, monkeypatch):+ key, secret = "local-root-" + uuid.uuid4().hex, uuid.uuid4().hex+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", key)+ monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", secret)+ assert post_form.submit(post_form.generate(access_key=key, secret=secret))[0] == 204+++def test_rejected_post_preserves_existing_object_and_disk(post_form, post_auth, monkeypatch, tmp_path):+ monkeypatch.setattr(_s3_mod, "DATA_DIR", str(tmp_path))+ monkeypatch.setattr(_s3_mod, "S3_PERSIST", True)+ events = []+ monkeypatch.setattr(_s3_mod, "_fire_s3_event_async", lambda *a, **kw: events.append(kw))+ assert post_form.submit(post_form.generate(), data=b"original")[0] == 204+ files = {str(path): path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()}+ assert files+ invalid = post_form.generate(secret=uuid.uuid4().hex)+ assert post_form.submit(invalid, data=b"replacement")[0] == 403+ assert {str(path): path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()} == files+ assert len(events) == 1+ obj = _s3_mod._buckets[post_form.bucket]["objects"]["uploads/data.txt"]+ assert _s3_mod._read_body(post_form.bucket, "uploads/data.txt", obj) == b"original"+ _s3_mod._buckets.clear()+ _s3_mod._load_persisted_data()+ obj = _s3_mod._buckets[post_form.bucket]["objects"]["uploads/data.txt"]+ assert _s3_mod._read_body(post_form.bucket, "uploads/data.txt", obj) == b"original"+++def test_post_after_persisted_reload(post_form, monkeypatch, tmp_path):+ monkeypatch.setattr(_s3_mod, "DATA_DIR", str(tmp_path))+ monkeypatch.setattr(_s3_mod, "S3_PERSIST", True)+ assert post_form.submit(post_form.generate(), data=b"first")[0] == 204+ _s3_mod._buckets.clear()+ _s3_mod._load_persisted_data()+ assert post_form.submit(post_form.generate(), data=b"second")[0] == 204+++def test_s3_object_lock_headers_need_an_object_lock_bucket(s3):+ from datetime import datetime, timedelta, timezone++ bkt = f"intg-s3-nolock-{_uuid_mod.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=bkt)+ s3.put_bucket_versioning(Bucket=bkt, VersioningConfiguration={"Status": "Enabled"})+ try:+ with pytest.raises(ClientError) as exc:+ s3.put_object(Bucket=bkt, Key="k", Body=b"x", ObjectLockMode="COMPLIANCE",+ ObjectLockRetainUntilDate=datetime.now(timezone.utc) + timedelta(days=1))+ err = exc.value.response+ assert (err["Error"]["Code"], err["Error"]["Message"], err["ResponseMetadata"]["HTTPStatusCode"]) == (+ "InvalidRequest", "Bucket is missing ObjectLockConfiguration", 400)+ assert s3.list_objects_v2(Bucket=bkt).get("KeyCount") == 0+ finally:+ s3.delete_bucket(Bucket=bkt)+++def test_s3_object_lock_applies_to_its_version_only(s3):+ from datetime import datetime, timedelta, timezone++ bkt = f"intg-s3-lock-ver-{_uuid_mod.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=bkt, ObjectLockEnabledForBucket=True)+ locked = s3.put_object(Bucket=bkt, Key="k", Body=b"v1", ObjectLockMode="COMPLIANCE",+ ObjectLockRetainUntilDate=datetime.now(timezone.utc) + timedelta(days=1))["VersionId"]+ free = s3.put_object(Bucket=bkt, Key="k", Body=b"v2")["VersionId"]+ assert "ObjectLockMode" not in s3.head_object(Bucket=bkt, Key="k")+ assert s3.head_object(Bucket=bkt, Key="k", VersionId=locked)["ObjectLockMode"] == "COMPLIANCE"+ s3.delete_object(Bucket=bkt, Key="k", VersionId=free)+ with pytest.raises(ClientError) as exc:+ s3.delete_object(Bucket=bkt, Key="k", VersionId=locked)+ assert exc.value.response["Error"]["Code"] == "AccessDenied"+diff --git a/tests/test_s3_post_policy.py b/tests/test_s3_post_policy.pydeleted file mode 100644index 347ec03e..00000000--- a/tests/test_s3_post_policy.py+++ /dev/null@@ -1,281 +0,0 @@-"""Local S3 POST contract tests using boto3 forms and registered IAM credentials.--Expected conditions come from the S3 POST policy documentation, not a live AWS run.-"""-import asyncio-import time-import uuid-from xml.etree import ElementTree--import boto3-import pytest-import requests-from botocore.config import Config-from conftest import inprocess_iam_user, routed_request--from ministack.core.responses import AccountScopedDict, request_scope-from ministack.services import iam, s3, sts---def post_form(monkeypatch):- import ministack.app as app_mod-- monkeypatch.setattr(app_mod, "AUTH", False)- monkeypatch.setattr(s3, "_buckets", AccountScopedDict())- monkeypatch.setattr(s3, "S3_PERSIST", False)- with request_scope("000000000000", "us-east-1"):- bucket = "post-policy-" + uuid.uuid4().hex[:12]- key, _arn = inprocess_iam_user()- s3._create_bucket(bucket, b"", {})-- class Form:- def generate(self, *, fields=None, conditions=None, key_name="uploads/data.txt", expires=300,- secret=None, token=None, access_key=None, signature_version="s3v4"):- client = boto3.client(- "s3", endpoint_url="http://localhost", region_name="us-east-1",- aws_access_key_id=access_key or key[0], aws_secret_access_key=secret or key[1],- aws_session_token=token, config=Config(signature_version=signature_version),- )- return client.generate_presigned_post(- Bucket=bucket, Key=key_name, Fields=fields or {},- Conditions=conditions or [], ExpiresIn=expires,- )["fields"]-- def submit(self, fields, *, data=b"contents", filename="data.txt", routed=False):- req = requests.Request(- "POST", "http://localhost/" + bucket,- data=fields, files={"file": (filename, data)},- ).prepare()- headers = {name.lower(): value for name, value in req.headers.items()}- if routed:- return routed_request(None, "s3", "POST", "/" + bucket,- body=req.body, headers=headers)- return asyncio.run(s3.handle_request("POST", "/" + bucket, headers, req.body, {}))-- def assert_rejected(self, fields, code, **kwargs):- response = self.submit(fields, **kwargs)- assert response[0] in (400, 403)- assert ElementTree.fromstring(response[2]).findtext("Code") == code- assert s3._buckets[bucket]["objects"] == {}-- form = Form()- form.bucket, form.key = bucket, key- yield form- iam._access_keys.pop(key[0], None)- name = _arn.rsplit("/", 1)[-1]- iam._users.pop(name, None)- iam._user_inline_policies.pop(name, None)--[email protected]("signature_version", ["s3v4", "s3"])-def test_signed_post_stores_bytes_and_metadata(post_form, signature_version):- fields = post_form.generate(fields={"x-amz-meta-author": "alice", "success_action_status": "201"},- conditions=[{"x-amz-meta-author": "alice"}, {"success_action_status": "201"}],- signature_version=signature_version)- assert post_form.submit(fields)[0] == 201- obj = s3._buckets[post_form.bucket]["objects"]["uploads/data.txt"]- assert obj["body"] == b"contents"- assert obj["metadata"] == {"x-amz-meta-author": "alice"}--[email protected]("name,value", [("key", "uploads/other.txt"), ("Content-Type", "text/plain"),- ("x-amz-meta-author", "bob"), ("success_action_status", "204")])-def test_post_exact_conditions_reject_mismatched_fields(post_form, name, value):- fields = {"Content-Type": "application/json", "x-amz-meta-author": "alice", "success_action_status": "201"}- form = post_form.generate(fields=fields, conditions=[{k: v} for k, v in fields.items()])- form[name] = value- post_form.assert_rejected(form, "AccessDenied")--[email protected]("signature_version", ["s3v4", "s3"])[email protected]("auth_enabled", [False, True])-def test_post_signature_verified_in_both_auth_modes(post_form, monkeypatch, auth_enabled, signature_version):- import ministack.app as app_mod-- monkeypatch.setattr(app_mod, "AUTH", auth_enabled)- form = post_form.generate(secret=uuid.uuid4().hex, signature_version=signature_version)- post_form.assert_rejected(form, "SignatureDoesNotMatch", routed=True)--[email protected]("missing", ["x-amz-signature", "x-amz-date", "x-amz-credential", "policy"])-def test_incomplete_sigv4_form_rejected(post_form, missing):- form = post_form.generate()- del form[missing]- post_form.assert_rejected(form, "InvalidArgument")---def test_expired_post_policy_rejected(post_form):- post_form.assert_rejected(post_form.generate(expires=-60), "AccessDenied")--[email protected]("content_type,accepted", [("image/png,image/jpeg", True), ("image/png,text/plain", False)])-def test_post_content_type_prefix_applies_to_each_list_item(post_form, content_type, accepted):- form = post_form.generate(fields={"Content-Type": content_type},- conditions=[["starts-with", "$Content-Type", "image/"]])- if accepted:- assert post_form.submit(form)[0] == 204- else:- post_form.assert_rejected(form, "AccessDenied")---def test_post_variables_expanded_before_matching(post_form):- form = post_form.generate(key_name="uploads/${filename}", fields={"x-amz-meta-name": "${filename}"},- conditions=[["eq", "$x-amz-meta-name", "data.txt"]])- assert post_form.submit(form)[0] == 204- obj = s3._buckets[post_form.bucket]["objects"]["uploads/data.txt"]- assert obj["metadata"]["x-amz-meta-name"] == "data.txt"---def test_post_variables_expanded_once(post_form):- form = post_form.generate(key_name="uploads/${filename}")- assert post_form.submit(form, filename="${filename}.txt")[0] == 204- assert list(s3._buckets[post_form.bucket]["objects"]) == ["uploads/${filename}.txt"]--[email protected]("extra", ["x-amz-meta-extra", "acl"])-def test_post_uncovered_form_fields_rejected(post_form, extra):- form = post_form.generate(fields={extra: "private"})- post_form.assert_rejected(form, "AccessDenied")---def test_post_missing_condition_field_rejected(post_form):- form = post_form.generate(conditions=[["starts-with", "$x-amz-meta-required", ""]])- post_form.assert_rejected(form, "AccessDenied")---def test_post_ignore_fields_exempt_from_conditions(post_form):- assert post_form.submit(post_form.generate(fields={"x-ignore-client": "local"}))[0] == 204--[email protected]("data,code", [(b"a", "EntityTooSmall"), (b"1234", "EntityTooLarge"), (b"12", None), (b"123", None)])-def test_post_size_range_inclusive(post_form, data, code):- form = post_form.generate(conditions=[["content-length-range", 2, 3]])- if code:- post_form.assert_rejected(form, code, data=data)- else:- assert post_form.submit(form, data=data)[0] == 204--[email protected]("low,code", [("2", None), ("x", "AccessDenied")])-def test_post_size_range_string_bounds(post_form, low, code):- form = post_form.generate(conditions=[["content-length-range", low, "3"]])- if code:- post_form.assert_rejected(form, code, data=b"12")- else:- assert post_form.submit(form, data=b"12")[0] == 204---def test_post_modified_policy_fails_signature(post_form):- form = post_form.generate()- form["policy"] = form["policy"][:-2]- post_form.assert_rejected(form, "SignatureDoesNotMatch")---def test_post_invalid_condition_rejected(post_form):- post_form.assert_rejected(post_form.generate(conditions=[["unknown", "$key", ""]]), "InvalidPolicyDocument")---def test_post_bucket_condition_uses_destination(post_form):- post_form.assert_rejected(post_form.generate(conditions=[{"bucket": "different-bucket"}]), "AccessDenied")---def test_post_inactive_registered_key_rejected(post_form):- form = post_form.generate()- iam._access_keys[post_form.key[0]]["Status"] = "Inactive"- post_form.assert_rejected(form, "InvalidAccessKeyId")---def test_post_unexpected_session_token_rejected(post_form):- post_form.assert_rejected(post_form.generate(token=uuid.uuid4().hex), "InvalidToken")---def test_post_registered_key_resolves_nondefault_account(post_form):- with request_scope("123456789012", "us-east-1"):- key, arn = inprocess_iam_user()- try:- bucket = "tenant-post-" + uuid.uuid4().hex[:12]- s3._create_bucket(bucket, b"", {})- client = boto3.client("s3", endpoint_url="http://localhost", region_name="us-east-1",- aws_access_key_id=key[0], aws_secret_access_key=key[1],- config=Config(signature_version="s3v4"))- form = client.generate_presigned_post(Bucket=bucket, Key="uploads/data.txt")["fields"]- # submit() captures the fixture bucket, so route this request explicitly.- req = requests.Request("POST", "http://localhost/" + bucket, data=form,- files={"file": ("data.txt", b"tenant")}).prepare()- result = asyncio.run(s3.handle_request("POST", "/" + bucket,- {k.lower(): v for k, v in req.headers.items()}, req.body, {}))- assert result[0] == 204- assert s3._buckets[bucket]["objects"]["uploads/data.txt"]["body"] == b"tenant"- finally:- iam._access_keys.pop(key[0], None)- iam._users.pop(arn.rsplit("/", 1)[-1], None)--[email protected]("signature", ["", "not-hex", "é" * 64])-def test_post_malformed_signature_is_a_client_error(post_form, signature):- form = post_form.generate()- form["x-amz-signature"] = signature- post_form.assert_rejected(form, "InvalidArgument" if not signature else "SignatureDoesNotMatch")--[email protected]("token_state", ["valid", "missing", "incorrect", "expired"])-def test_post_uses_sts_issued_credentials(post_form, token_state):- response = routed_request(post_form.key, "sts", "POST", "/",- body=b"Action=GetSessionToken&DurationSeconds=900",- headers={"content-type": "application/x-www-form-urlencoded"})- assert response[0] == 200- root = ElementTree.fromstring(response[2])- credentials = {name: root.findtext(".//{*}" + name) for name in ("AccessKeyId", "SecretAccessKey", "SessionToken")}- access_key = credentials["AccessKeyId"]- try:- token = credentials["SessionToken"]- if token_state == "missing":- token = None- elif token_state == "incorrect":- token = uuid.uuid4().hex- elif token_state == "expired":- sts._sessions[access_key]["Expiration"] = time.time() - 60- form = post_form.generate(access_key=access_key, secret=credentials["SecretAccessKey"], token=token)- if token_state == "valid":- assert post_form.submit(form)[0] == 204- else:- post_form.assert_rejected(form, "ExpiredToken" if token_state == "expired" else "InvalidToken")- finally:- sts._sessions.pop(access_key, None)---def test_post_configured_root_credentials(post_form, monkeypatch):- key, secret = "local-root-" + uuid.uuid4().hex, uuid.uuid4().hex- monkeypatch.setenv("AWS_ACCESS_KEY_ID", key)- monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", secret)- assert post_form.submit(post_form.generate(access_key=key, secret=secret))[0] == 204---def test_rejected_post_preserves_existing_object_and_disk(post_form, monkeypatch, tmp_path):- monkeypatch.setattr(s3, "DATA_DIR", str(tmp_path))- monkeypatch.setattr(s3, "S3_PERSIST", True)- events = []- monkeypatch.setattr(s3, "_fire_s3_event_async", lambda *a, **kw: events.append(kw))- assert post_form.submit(post_form.generate(), data=b"original")[0] == 204- files = {str(path): path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()}- assert files- invalid = post_form.generate(secret=uuid.uuid4().hex)- assert post_form.submit(invalid, data=b"replacement")[0] == 403- assert {str(path): path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()} == files- assert len(events) == 1- obj = s3._buckets[post_form.bucket]["objects"]["uploads/data.txt"]- assert s3._read_body(post_form.bucket, "uploads/data.txt", obj) == b"original"- s3._buckets.clear()- s3._load_persisted_data()- obj = s3._buckets[post_form.bucket]["objects"]["uploads/data.txt"]- assert s3._read_body(post_form.bucket, "uploads/data.txt", obj) == b"original"---def test_post_after_persisted_reload(post_form, monkeypatch, tmp_path):- monkeypatch.setattr(s3, "DATA_DIR", str(tmp_path))- monkeypatch.setattr(s3, "S3_PERSIST", True)- assert post_form.submit(post_form.generate(), data=b"first")[0] == 204- s3._buckets.clear()- s3._load_persisted_data()- assert post_form.submit(post_form.generate(), data=b"second")[0] == 204diff --git a/tests/test_sqs.py b/tests/test_sqs.pyindex 3d94bff1..d9497618 100644--- a/tests/test_sqs.py+++ b/tests/test_sqs.py@@ -1,3 +1,5 @@+import asyncio+import copyimport ioimport jsonimport os@@ -5,8 +7,9 @@ import reimport timeimport uuidimport uuid as _uuid_mod+import xml.etree.ElementTree as ETimport zipfile-from urllib.parse import urlparse+from urllib.parse import urlencode, urlparseimport boto3import pytest@@ -15,7 +18,7 @@ from botocore.exceptions import ClientErrorfrom conftest import REGION, inprocess_iam_user, routed_request, sqs_policy_allow_s3, sqs_policy_allow_snsfrom ministack.core.iam_evaluator import EvalContext, evaluate_resource_policy-from ministack.core.responses import get_account_id, request_scope+from ministack.core.responses import AccountRegionScopedDict, get_account_id, request_scopefrom ministack.services import s3 as s3_svcfrom ministack.services import sns as sns_svcfrom ministack.services import sqs as sqs_svc@@ -2509,3 +2512,89 @@ def test_sqs_dlq_move_enqueue_time_and_source_arn(monkeypatch, fifo):remaining = sum(counts(dlq))# Standard keeps the original enqueue time (expired); FIFO reset it on the move (still there).assert remaining == (1 if fifo else 0)+++def queue(monkeypatch):+ monkeypatch.setattr(sqs_svc, "_queues", AccountRegionScopedDict())+ monkeypatch.setattr(sqs_svc, "_queue_name_to_url", AccountRegionScopedDict())+ url = sqs_svc._act_create_queue({"QueueName": "policy-removal"}, "")["QueueUrl"]+ dlq = sqs_svc._act_create_queue({"QueueName": "policy-removal-dlq"}, "")["QueueUrl"]+ arn = sqs_svc._act_get_queue_attributes({"QueueUrl": dlq}, "")["Attributes"]["QueueArn"]+ policies = {+ "Policy": json.dumps({"Version": "2012-10-17", "Statement": []}),+ "RedrivePolicy": json.dumps({"deadLetterTargetArn": arn, "maxReceiveCount": "3"}),+ "RedriveAllowPolicy": json.dumps({"redrivePermission": "denyAll"}),+ }+ sqs_svc._act_set_queue_attributes({"QueueUrl": url, "Attributes": policies}, "")+ return url, policies+++def _request(protocol, action, url, attributes=None, names=None):+ if protocol == "json":+ data = {"QueueUrl": url}+ if attributes is not None:+ data["Attributes"] = attributes+ if names is not None:+ data["AttributeNames"] = names+ headers = {"x-amz-target": f"AmazonSQS.{action}"}+ body = json.dumps(data).encode()+ else:+ data = {"Action": action, "QueueUrl": url}+ for i, (key, value) in enumerate((attributes or {}).items(), 1):+ data[f"Attribute.{i}.Name"] = key+ data[f"Attribute.{i}.Value"] = value+ for i, name in enumerate(names or [], 1):+ data[f"AttributeName.{i}"] = name+ headers = {"content-type": "application/x-www-form-urlencoded"}+ body = urlencode(data).encode()+ return asyncio.run(sqs_svc.handle_request("POST", "/", headers, body, {}))+++def _read(protocol, url, names):+ status, _, body = _request(protocol, "GetQueueAttributes", url, names=names)+ assert status == 200+ if protocol == "json":+ return json.loads(body)["Attributes"]+ ns = "{http://queue.amazonaws.com/doc/2012-11-05/}"+ return {entry.findtext(f"{ns}Name"): entry.findtext(f"{ns}Value")+ for entry in ET.fromstring(body).iter(f"{ns}Attribute")}++[email protected]("protocol", ["json", "query"])[email protected]("attribute", ["Policy", "RedrivePolicy", "RedriveAllowPolicy"])+def test_empty_policy_removes_attribute_from_all_and_specific_reads(queue, protocol, attribute):+ url, policies = queue+ assert _read(protocol, url, [attribute]) == {attribute: policies[attribute]}+ for _ in range(2):+ status, _, body = _request(protocol, "SetQueueAttributes", url, {attribute: ""})+ assert status == 200, body+ assert _read(protocol, url, [attribute]) == {}+ remaining = _read(protocol, url, ["All"])+ assert attribute not in remaining+ for other in policies.keys() - {attribute}:+ assert remaining[other] == policies[other]+ assert remaining["VisibilityTimeout"] == "30"++[email protected]("invalid", [{"RedrivePolicy": "not-json"},+ {"RedrivePolicy": '"double-encoded"'},+ {"VisibilityTimeout": "-1"}])+def test_invalid_update_preserves_all_attributes(queue, invalid):+ url, _ = queue+ before = copy.deepcopy(sqs_svc._queues[url])+ status, _, body = _request("json", "SetQueueAttributes", url, {"Policy": "", **invalid})+ assert status == 400+ assert json.loads(body)["__type"] == "InvalidAttributeValue"+ assert sqs_svc._queues[url] == before+++def test_removed_policies_remain_absent_after_persistence_round_trip(queue):+ url, policies = queue+ assert _request("json", "SetQueueAttributes", url, dict.fromkeys(policies, ""))[0] == 200+ state = sqs_svc.get_state()+ sqs_svc._queues.clear()+ sqs_svc._queue_name_to_url.clear()+ sqs_svc.load_persisted_state(state)+ assert policies.keys().isdisjoint(_read("json", url, ["All"]))+ assert _read("json", url, ["QueueArn"])["QueueArn"].endswith(":policy-removal")diff --git a/tests/test_sqs_policy_removal.py b/tests/test_sqs_policy_removal.pydeleted file mode 100644index f8227a53..00000000--- a/tests/test_sqs_policy_removal.py+++ /dev/null@@ -1,99 +0,0 @@-# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT-"""Terraform removes queue policies with explicit empty attribute values."""--import asyncio-import copy-import json-import xml.etree.ElementTree as ET-from urllib.parse import urlencode--import pytest--from ministack.core.responses import AccountRegionScopedDict-from ministack.services import sqs---def queue(monkeypatch):- monkeypatch.setattr(sqs, "_queues", AccountRegionScopedDict())- monkeypatch.setattr(sqs, "_queue_name_to_url", AccountRegionScopedDict())- url = sqs._act_create_queue({"QueueName": "policy-removal"}, "")["QueueUrl"]- dlq = sqs._act_create_queue({"QueueName": "policy-removal-dlq"}, "")["QueueUrl"]- arn = sqs._act_get_queue_attributes({"QueueUrl": dlq}, "")["Attributes"]["QueueArn"]- policies = {- "Policy": json.dumps({"Version": "2012-10-17", "Statement": []}),- "RedrivePolicy": json.dumps({"deadLetterTargetArn": arn, "maxReceiveCount": "3"}),- "RedriveAllowPolicy": json.dumps({"redrivePermission": "denyAll"}),- }- sqs._act_set_queue_attributes({"QueueUrl": url, "Attributes": policies}, "")- return url, policies---def _request(protocol, action, url, attributes=None, names=None):- if protocol == "json":- data = {"QueueUrl": url}- if attributes is not None:- data["Attributes"] = attributes- if names is not None:- data["AttributeNames"] = names- headers = {"x-amz-target": f"AmazonSQS.{action}"}- body = json.dumps(data).encode()- else:- data = {"Action": action, "QueueUrl": url}- for i, (key, value) in enumerate((attributes or {}).items(), 1):- data[f"Attribute.{i}.Name"] = key- data[f"Attribute.{i}.Value"] = value- for i, name in enumerate(names or [], 1):- data[f"AttributeName.{i}"] = name- headers = {"content-type": "application/x-www-form-urlencoded"}- body = urlencode(data).encode()- return asyncio.run(sqs.handle_request("POST", "/", headers, body, {}))---def _read(protocol, url, names):- status, _, body = _request(protocol, "GetQueueAttributes", url, names=names)- assert status == 200- if protocol == "json":- return json.loads(body)["Attributes"]- ns = "{http://queue.amazonaws.com/doc/2012-11-05/}"- return {entry.findtext(f"{ns}Name"): entry.findtext(f"{ns}Value")- for entry in ET.fromstring(body).iter(f"{ns}Attribute")}--[email protected]("protocol", ["json", "query"])[email protected]("attribute", ["Policy", "RedrivePolicy", "RedriveAllowPolicy"])-def test_empty_policy_removes_attribute_from_all_and_specific_reads(queue, protocol, attribute):- url, policies = queue- assert _read(protocol, url, [attribute]) == {attribute: policies[attribute]}- for _ in range(2):- status, _, body = _request(protocol, "SetQueueAttributes", url, {attribute: ""})- assert status == 200, body- assert _read(protocol, url, [attribute]) == {}- remaining = _read(protocol, url, ["All"])- assert attribute not in remaining- for other in policies.keys() - {attribute}:- assert remaining[other] == policies[other]- assert remaining["VisibilityTimeout"] == "30"--[email protected]("invalid", [{"RedrivePolicy": "not-json"},- {"RedrivePolicy": '"double-encoded"'},- {"VisibilityTimeout": "-1"}])-def test_invalid_update_preserves_all_attributes(queue, invalid):- url, _ = queue- before = copy.deepcopy(sqs._queues[url])- status, _, body = _request("json", "SetQueueAttributes", url, {"Policy": "", **invalid})- assert status == 400- assert json.loads(body)["__type"] == "InvalidAttributeValue"- assert sqs._queues[url] == before---def test_removed_policies_remain_absent_after_persistence_round_trip(queue):- url, policies = queue- assert _request("json", "SetQueueAttributes", url, dict.fromkeys(policies, ""))[0] == 200- state = sqs.get_state()- sqs._queues.clear()- sqs._queue_name_to_url.clear()- sqs.load_persisted_state(state)- assert policies.keys().isdisjoint(_read("json", url, ["All"]))- assert _read("json", url, ["QueueArn"])["QueueArn"].endswith(":policy-removal")