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
fix(s3,sqs,ecs): close 6 AWS-parity gaps (response-* overrides, AWSTraceHeader, batch size, null tag values, task lifecycle reconciliation) (#668)
Nahuel Nucera6a247da87c0c
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex 2b9d72c3..bcbfa526 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -1237,6 +1237,12 @@ def _list_tasks(data):for arn, t in _tasks.items():if t.get("clusterArn") != cluster_arn:continue+ # Reconcile lifecycle on the fly: a task whose container has exited+ # naturally (handler returned, process crashed) should report STOPPED+ # — not the stale RUNNING that survives until someone calls+ # DescribeTasks. _maybe_mark_stopped is a no-op for tasks not in+ # RUNNING or without docker ids, so the hot path is cheap.+ _maybe_mark_stopped(t)if t.get("desiredStatus") != status_filter:continueif family:diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 05355504..a60e4405 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -294,6 +294,97 @@ def _parse_range(range_header: str, total: int):return start, end+_RESPONSE_OVERRIDE_PARAMS = (+ "response-cache-control",+ "response-content-disposition",+ "response-content-encoding",+ "response-content-language",+ "response-content-type",+ "response-expires",+)+++def _apply_response_overrides(resp_headers: dict, query_params: dict) -> None:+ """Apply the six ``response-*`` GetObject query-string overrides to the+ outgoing response headers, matching real S3:++ response-cache-control → Cache-Control+ response-content-disposition → Content-Disposition+ response-content-encoding → Content-Encoding+ response-content-language → Content-Language+ response-content-type → Content-Type+ response-expires → Expires++ Each override REPLACES the corresponding response header. Empty values+ are ignored (boto3 doesn't send the param if you pass ``None``). The+ signedness gate runs separately in ``_reject_response_overrides_if_unsigned``;+ by the time this helper runs we've already accepted the request.+ """+ overrides = (+ ("response-cache-control", "Cache-Control"),+ ("response-content-disposition", "Content-Disposition"),+ ("response-content-encoding", "Content-Encoding"),+ ("response-content-language", "Content-Language"),+ ("response-content-type", "Content-Type"),+ ("response-expires", "Expires"),+ )+ for qkey, hkey in overrides:+ val = _qp(query_params, qkey, "")+ if not val:+ continue+ # Replace, don't append: the put-side preserved-headers dict stores+ # keys lowercased (cache-control, content-disposition, …) and the+ # default headers dict uses mixed case (Cache-Control). HTTP libs+ # serialise both, so without an explicit case-insensitive remove the+ # client sees the override appended to the original (e.g.+ # "max-age=600, no-store"). Strip every case variant of the target+ # before writing the override value.+ target_lc = hkey.lower()+ for existing in list(resp_headers):+ if existing.lower() == target_lc:+ del resp_headers[existing]+ resp_headers[hkey] = val+++def _reject_response_overrides_if_unsigned(+ headers: dict, query_params: dict, bucket_name: str, key: str,+):+ """Implement the AWS rule for GetObject's six ``response-*`` query params.++ Per the AWS API reference:++ "When you use these parameters, you must sign the request by using+ either an Authorization header or a presigned URL. These parameters+ cannot be used with an unsigned (anonymous) request."++ A request is considered signed if it carries an ``Authorization`` header+ or a presigned-URL marker (``X-Amz-Signature`` / ``X-Amz-Algorithm`` in+ the query string — boto3 lower-cases query keys when calling our+ handlers, so check both cases). Otherwise the six ``response-*`` params+ are rejected with ``InvalidRequest`` (400) and the AWS-canonical message+ "Request specific response headers cannot be used for anonymous GET+ requests."+ """+ has_override = any(+ _qp(query_params, p, "") for p in _RESPONSE_OVERRIDE_PARAMS+ )+ if not has_override:+ return None+ if headers.get("authorization"):+ return None+ if (_qp(query_params, "X-Amz-Signature", "")+ or _qp(query_params, "x-amz-signature", "")+ or _qp(query_params, "X-Amz-Algorithm", "")+ or _qp(query_params, "x-amz-algorithm", "")):+ return None+ return _error(+ "InvalidRequest",+ "Request specific response headers cannot be used for anonymous GET requests.",+ 400,+ f"/{bucket_name}/{key}",+ )++def _validate_content_md5(headers: dict, body: bytes):md5_header = headers.get("content-md5", "")if not md5_header:@@ -1987,6 +2078,14 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =if bucket is None:return _no_such_bucket(bucket_name)+ # AWS rule: the six response-* override query parameters require a signed+ # request (Authorization header or presigned URL). An unsigned/anonymous+ # GET that carries any of them is rejected with InvalidRequest (400).+ # See: https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html+ err = _reject_response_overrides_if_unsigned(headers, query_params, bucket_name, key)+ if err is not None:+ return err+version_id = _qp(query_params, "versionId", "")if version_id:vkey = (bucket_name, key)@@ -2031,8 +2130,10 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =slice_body = body[start : end + 1]resp_headers["Content-Length"] = str(len(slice_body))resp_headers["Content-Range"] = f"bytes {start}-{end}/{obj['size']}"+ _apply_response_overrides(resp_headers, query_params)return 206, resp_headers, slice_body+ _apply_response_overrides(resp_headers, query_params)return 200, resp_headers, bodydiff --git a/ministack/services/sqs.py b/ministack/services/sqs.pyindex db7f178e..a87bb901 100644--- a/ministack/services/sqs.py+++ b/ministack/services/sqs.py@@ -374,10 +374,7 @@ def _act_send_message(data: dict, qurl: str) -> dict:"receive_count": 0,"first_receive_at": None,"message_attributes": msg_attrs,- "sys": {- "SenderId": get_account_id(),- "SentTimestamp": str(int(now * 1000)),- },+ "sys": _build_send_sys_attrs(now, sys_attrs),"group_id": group_id,"dedup_id": dedup_id,"dedup_cache_key": dedup_cache_key if q["is_fifo"] else None,@@ -670,6 +667,24 @@ def _act_send_message_batch(data: dict, qurl: str) -> dict:if len(entries) > 10:raise _Err("TooManyEntriesInBatchRequest","Too many messages in a batch request. A maximum of 10 messages are allowed.")++ # AWS rule: "The maximum allowed individual message size and the maximum+ # total payload size (the sum of the individual lengths of all of the+ # batched messages) are both 1 MiB 1,048,576 bytes." Reject the entire+ # batch with BatchRequestTooLong (HTTP 400) if the aggregate is over.+ # See https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessageBatch.html+ _BATCH_MAX_BYTES = 1_048_576+ total_bytes = sum(+ len((e.get("MessageBody") or "").encode("utf-8"))+ for e in entries+ )+ if total_bytes > _BATCH_MAX_BYTES:+ raise _Err(+ "BatchRequestTooLong",+ "Batch requests cannot be longer than 1048576 bytes. "+ f"You have sent {total_bytes} bytes.",+ )+ok: list = []fail: list = []for e in entries:@@ -733,7 +748,23 @@ def _act_list_queue_tags(data: dict, qurl: str) -> dict:def _act_tag_queue(data: dict, qurl: str) -> dict:url = data.get("QueueUrl", qurl)q = _get_q(url)- q.setdefault("tags", {}).update(data.get("Tags") or {})+ raw_tags = data.get("Tags") or {}+ # Real AWS rejects null tag VALUES (a JSON null in the wire payload) with+ # InvalidParameterValue (400). boto3's Python client blocks this at the+ # client-side via shape validation, but Java SDK v2, Go SDK, and raw HTTP+ # callers can ship `{"Tags": {"key": null}}`. Previously we stored the+ # Python None as-is, which then serialised back to literal "null"+ # via XML serialisation. Refuse them at the door instead.+ # Tags map is `string -> string` per the service-2 model — a null value+ # is not a valid string.+ for k, v in raw_tags.items():+ if v is None:+ raise _Err(+ "InvalidParameterValue",+ f"Value for parameter Tag.Value is invalid. Reason: "+ f"Tag value for key '{k}' is null.",+ )+ q.setdefault("tags", {}).update(raw_tags)return {}@@ -943,6 +974,29 @@ def _prune_dedup(q: dict) -> None:# ── Build system attributes for a received message ────────+def _build_send_sys_attrs(now: float, sys_attrs_input: dict) -> dict:+ """Build the per-message ``sys`` dict for SendMessage.++ AWS allows callers to ship ``MessageSystemAttributes`` on SendMessage —+ currently only ``AWSTraceHeader`` (X-Ray propagation) is accepted, with+ ``DataType=String``. Receivers see the value back via ReceiveMessage's+ ``MessageSystemAttributeNames=['AWSTraceHeader']`` (or ``All``).+ See https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html+ """+ sys: dict = {+ "SenderId": get_account_id(),+ "SentTimestamp": str(int(now * 1000)),+ }+ if not sys_attrs_input:+ return sys+ trace = sys_attrs_input.get("AWSTraceHeader")+ if isinstance(trace, dict):+ v = trace.get("StringValue") or trace.get("stringValue")+ if v:+ sys["AWSTraceHeader"] = v+ return sys++def _build_sys_attrs(msg: dict, names: list) -> dict:if not names:return {}@@ -964,6 +1018,9 @@ def _build_sys_attrs(msg: dict, names: list) -> dict:r["MessageDeduplicationId"] = msg["dedup_id"]if msg.get("group_id") and (want_all or "MessageGroupId" in names):r["MessageGroupId"] = msg["group_id"]+ trace = msg["sys"].get("AWSTraceHeader")+ if trace and (want_all or "AWSTraceHeader" in names):+ r["AWSTraceHeader"] = tracereturn rdiff --git a/tests/test_ecs.py b/tests/test_ecs.pyindex 1fc77245..878c0f3e 100644--- a/tests/test_ecs.py+++ b/tests/test_ecs.py@@ -71,6 +71,48 @@ def test_ecs_run_task_stops_after_exit(ecs):breakassert stopped, "Task should transition to STOPPED after container exits"++def test_ecs_list_tasks_reflects_natural_container_exit(ecs):+ """ListTasks must also reconcile lifecycle when a container has exited+ on its own. Previously only DescribeTasks ran the reconciler, so a user+ who only ever called ListTasks(desiredStatus=RUNNING) saw the dead task+ forever, and ListTasks(desiredStatus=STOPPED) returned an empty list.++ Reference: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-lifecycle-explanation.html+ "Some tasks are meant to run as batch jobs that naturally progress+ through from PENDING to RUNNING to STOPPED."+ """+ cluster = "task-lifecycle-listtasks"+ ecs.create_cluster(clusterName=cluster)+ ecs.register_task_definition(+ family="short-lived-list",+ containerDefinitions=[{+ "name": "worker",+ "image": "alpine:latest",+ "command": ["sh", "-c", "echo done"],+ "essential": True,+ }],+ )+ resp = ecs.run_task(cluster=cluster, taskDefinition="short-lived-list")+ task_arn = resp["tasks"][0]["taskArn"]++ # Give the container time to actually exit before we test the reconciler.+ # 6s is enough for `echo done` + Docker bookkeeping on every CI host+ # the existing run_task tests already pass on.+ time.sleep(6)++ # NOTE: explicitly NOT calling describe_tasks — the bug is that+ # list_tasks alone never reconciled.+ running = ecs.list_tasks(cluster=cluster, desiredStatus="RUNNING")["taskArns"]+ assert task_arn not in running, (+ "list_tasks(RUNNING) should not return a task whose container exited"+ )+ stopped = ecs.list_tasks(cluster=cluster, desiredStatus="STOPPED")["taskArns"]+ assert task_arn in stopped, (+ "list_tasks(STOPPED) should surface the naturally-exited task"+ )++def test_ecs_run_task_network_connectivity(ecs):"""ECS container can reach Ministack (proves network detection works)."""endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")diff --git a/tests/test_s3.py b/tests/test_s3.pyindex bb9ef73e..b382d817 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -327,6 +327,84 @@ def test_s3_get_object_range(s3):assert "bytes" in resp.get("ContentRange", "")assert resp["ResponseMetadata"]["HTTPStatusCode"] == 206++def test_s3_get_object_rejects_response_overrides_on_unsigned_request(s3):+ """AWS rejects unsigned GetObject requests carrying any of the six+ ``response-*`` override query parameters with HTTP 400 InvalidRequest.++ Reference: https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html+ "When you use these parameters, you must sign the request by using+ either an Authorization header or a presigned URL. These parameters+ cannot be used with an unsigned (anonymous) request."+ """+ import urllib.request+ bkt = "intg-s3-unsigned-resp-override"+ s3.create_bucket(Bucket=bkt)+ s3.put_object(Bucket=bkt, Key="data.txt", Body=b"hello")++ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ # No Authorization header, no presign markers — raw anonymous GET.+ for param in (+ "response-cache-control=no-cache",+ "response-content-disposition=attachment%3B%20filename%3Dfoo.txt",+ "response-content-encoding=gzip",+ "response-content-language=en",+ "response-content-type=text%2Fplain",+ "response-expires=0",+ ):+ url = f"{endpoint}/{bkt}/data.txt?{param}"+ try:+ urllib.request.urlopen(url, timeout=5).read()+ pytest.fail(f"expected 400 for unsigned request with {param}")+ except urllib.error.HTTPError as e:+ assert e.code == 400, f"{param} → wrong status {e.code}"+ body = e.read().decode()+ assert "InvalidRequest" in body, f"{param} → missing InvalidRequest in {body[:200]}"+ assert "anonymous" in body, f"{param} → missing 'anonymous' phrase in {body[:200]}"++ # And — same params on a SIGNED boto3 call must still work, untouched.+ resp = s3.get_object(+ Bucket=bkt,+ Key="data.txt",+ ResponseContentDisposition="attachment; filename=foo.txt",+ )+ assert resp["Body"].read() == b"hello"+++def test_s3_get_object_response_overrides_replace_headers(s3):+ """Real S3 lets a signed GetObject override response headers via six+ ``response-*`` query parameters: Cache-Control, Content-Disposition,+ Content-Encoding, Content-Language, Content-Type, Expires. boto3 exposes+ them as ``ResponseCacheControl`` / ``ResponseContentDisposition`` / etc.+ Each override REPLACES the corresponding header on the response.+ """+ bkt = "intg-s3-resp-overrides"+ s3.create_bucket(Bucket=bkt)+ s3.put_object(+ Bucket=bkt, Key="orig.txt", Body=b"payload",+ ContentType="text/x-original",+ CacheControl="max-age=600",+ )++ resp = s3.get_object(+ Bucket=bkt, Key="orig.txt",+ ResponseContentType="application/json",+ ResponseContentDisposition='attachment; filename="renamed.json"',+ ResponseCacheControl="no-store",+ ResponseContentEncoding="identity",+ ResponseContentLanguage="en-US",+ ResponseExpires="Thu, 01 Jan 1970 00:00:00 GMT",+ )+ assert resp["Body"].read() == b"payload"+ assert resp["ContentType"] == "application/json"+ h = resp["ResponseMetadata"]["HTTPHeaders"]+ assert h["content-type"] == "application/json"+ assert h["content-disposition"] == 'attachment; filename="renamed.json"'+ assert h["cache-control"] == "no-store"+ assert h["content-encoding"] == "identity"+ assert h["content-language"] == "en-US"+ assert h["expires"] == "Thu, 01 Jan 1970 00:00:00 GMT"+def test_s3_object_metadata(s3):bkt = "intg-s3-meta"s3.create_bucket(Bucket=bkt)diff --git a/tests/test_sqs.py b/tests/test_sqs.pyindex 9e2ca565..fea9b1eb 100644--- a/tests/test_sqs.py+++ b/tests/test_sqs.py@@ -367,6 +367,119 @@ def test_sqs_message_system_attribute_names_modern_field(sqs):assert attrs.get("ApproximateReceiveCount") == "1"assert "SentTimestamp" in attrs++def test_sqs_tag_queue_rejects_null_tag_value(sqs):+ """TagQueue rejects JSON null tag VALUES with InvalidParameterValue (400).++ boto3's Python client enforces the `string -> string` map shape locally so+ we can't trigger this through it directly. Java SDK v2, Go SDK, and raw+ HTTP callers can send `{"Tags": {"key": null}}`; previously the null was+ stored as Python None then serialised back as the literal string "null".+ Real AWS rejects at intake.+ """+ import urllib.request, json as _json+ url = sqs.create_queue(QueueName="intg-sqs-tag-null")["QueueUrl"]++ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ req = urllib.request.Request(+ endpoint + "/",+ data=_json.dumps({+ "QueueUrl": url,+ "Tags": {"valid": "ok", "broken": None},+ }).encode(),+ headers={+ "Content-Type": "application/x-amz-json-1.0",+ "X-Amz-Target": "AmazonSQS.TagQueue",+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/sqs/aws4_request",+ },+ method="POST",+ )+ try:+ urllib.request.urlopen(req, timeout=5).read()+ pytest.fail("expected 400 InvalidParameterValue for null tag value")+ except urllib.error.HTTPError as e:+ assert e.code == 400+ body = e.read().decode()+ assert "InvalidParameterValue" in body, body[:300]+ assert "null" in body.lower(), body[:300]++ # And — the valid tag in the same call MUST NOT have been partially+ # applied. AWS is all-or-nothing on this validation.+ tags = sqs.list_queue_tags(QueueUrl=url).get("Tags", {})+ assert "valid" not in tags+ assert "broken" not in tags+++def test_sqs_send_message_batch_rejects_oversized_aggregate(sqs):+ """SendMessageBatch's aggregate payload cap is 1 MiB. The contributor PR+ enforced per-message size against the queue's MaximumMessageSize but never+ checked the batch sum, so 10 × 150 KiB messages (queue allows them+ individually) snuck through. Real AWS returns BatchRequestTooLong (400)+ for the whole batch when the sum is over.+ See: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessageBatch.html+ """+ url = sqs.create_queue(+ QueueName="intg-sqs-batch-too-long",+ Attributes={"MaximumMessageSize": "262144"}, # default+ )["QueueUrl"]++ # 10 × 150 KiB → 1.5 MiB total. Each individual entry is within the queue's+ # 256-KiB MaximumMessageSize, but the batch aggregate exceeds the 1-MiB cap.+ body = "x" * (150 * 1024)+ entries = [{"Id": f"m{i}", "MessageBody": body} for i in range(10)]++ with pytest.raises(ClientError) as exc:+ sqs.send_message_batch(QueueUrl=url, Entries=entries)+ code = exc.value.response["Error"]["Code"]+ assert code in (+ "AWS.SimpleQueueService.BatchRequestTooLong",+ "BatchRequestTooLong",+ ), f"unexpected error code: {code}"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400++ # Under-cap batch should succeed (5 × 150 KiB = 750 KiB).+ ok = sqs.send_message_batch(QueueUrl=url, Entries=entries[:5])+ assert len(ok["Successful"]) == 5+ assert not ok.get("Failed")+++def test_sqs_send_message_preserves_awstraceheader(sqs):+ """SendMessage's MessageSystemAttributes.AWSTraceHeader carries an X-Ray+ trace context that AWS preserves through the queue and returns to the+ receiver via ReceiveMessage's MessageSystemAttributeNames=['AWSTraceHeader']+ (or 'All'). Previously this was captured then dropped silently.+ See: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html+ """+ url = sqs.create_queue(QueueName="intg-sqs-trace-hdr")["QueueUrl"]+ trace = "Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1"+ sqs.send_message(+ QueueUrl=url,+ MessageBody="traced",+ MessageSystemAttributes={+ "AWSTraceHeader": {"DataType": "String", "StringValue": trace},+ },+ )++ # Explicit name+ msgs = sqs.receive_message(+ QueueUrl=url,+ MaxNumberOfMessages=1,+ MessageSystemAttributeNames=["AWSTraceHeader"],+ )+ assert msgs["Messages"][0]["Attributes"]["AWSTraceHeader"] == trace++ # Re-receive after the visibility window via "All"+ msg = msgs["Messages"][0]+ sqs.change_message_visibility(+ QueueUrl=url, ReceiptHandle=msg["ReceiptHandle"], VisibilityTimeout=0,+ )+ msgs2 = sqs.receive_message(+ QueueUrl=url,+ MaxNumberOfMessages=1,+ MessageSystemAttributeNames=["All"],+ )+ assert msgs2["Messages"][0]["Attributes"]["AWSTraceHeader"] == trace+def test_sqs_nonexistent_queue(sqs):with pytest.raises(ClientError) as exc:sqs.get_queue_url(QueueName="intg-sqs-does-not-exist")