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(gateway): validate body framing and isolate diagnostic queue aliases (#2062)
Dzmitry Shchamialioub09ca922d849
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex badc4a5b..00128bfe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **Gateway**: reject malformed request-body and aws-chunked framing; preserve account-isolated SQS diagnostic aliases and tombstone-aware peeking.- **SES**: validate source/recipient addresses, content-field presence and configuration sets while accepting present empty content and ASCII/Punycode addresses.- **Container reaping — one unreadable container no longer stops the sweep** — the boot sweep and the periodic reaper now list containers without inspecting each one, so a container whose inspect fails is skipped instead of leaving every leftover running. Reported by @iot-rocket.- **API Gateway — management IAM actions and resource paths** — with `AUTH=true`, REST and HTTP/WebSocket API management requests use `apigateway:GET`, `POST`, `PUT`, `PATCH` and `DELETE` instead of SDK operation names. Resource ARNs preserve stage names, nested resources and collection paths, and ignore trailing slashes as AWS does, so scoped grants and explicit stage denies apply to the requested resource.diff --git a/ministack/app.py b/ministack/app.pyindex 538b16bb..05f2c123 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -565,6 +565,14 @@ def _get_reset_lock() -> asyncio.Lock:# ---------------------------------------------------------------------------+class _IncompleteRequestBody(Exception):+ """The request body ended before its declared framing was complete."""+++class _RequestBodyDisconnected(Exception):+ """The client disconnected before the request body was complete."""++def _decode_aws_chunked_body(body: bytes, headers: dict) -> bytes:"""Decode AWS chunked request bodies and normalize content-encoding headers."""sha256_header = headers.get("x-amz-content-sha256", "")@@ -583,40 +591,75 @@ def _decode_aws_chunked_body(body: bytes, headers: dict) -> bytes:# sends for a large streaming PutObject.chunks = []pos = 0- trailer = b""+ trailer = Nonewhile pos < len(body):crlf = body.find(b"\r\n", pos)if crlf == -1:- break- chunk_header = body[pos:crlf].decode("ascii", errors="replace")- size_hex = chunk_header.split(";")[0].strip()+ raise _IncompleteRequestBody("Truncated aws-chunked frame header")try:- chunk_size = int(size_hex, 16)- except ValueError:- break+ chunk_header = body[pos:crlf].decode("ascii")+ except UnicodeDecodeError as e:+ raise _IncompleteRequestBody("Invalid aws-chunked frame header") from e+ size_hex = chunk_header.split(";")[0].strip()+ if not re.fullmatch(r"[0-9A-Fa-f]+", size_hex):+ raise _IncompleteRequestBody("Invalid aws-chunked frame size")+ chunk_size = int(size_hex, 16)if chunk_size == 0:# Whatever follows the final chunk is the trailing header# section the request announced in x-amz-trailer.trailer = body[crlf + 2 :]breakdata_start = crlf + 2- chunks.append(body[data_start : data_start + chunk_size])- pos = data_start + chunk_size + 2 # skip trailing \r\n+ data_end = data_start + chunk_size+ if data_end + 2 > len(body) or body[data_end : data_end + 2] != b"\r\n":+ raise _IncompleteRequestBody("Truncated aws-chunked frame data")+ chunks.append(body[data_start:data_end])+ pos = data_end + 2 # skip trailing \r\n+ if trailer is None:+ raise _IncompleteRequestBody("Missing aws-chunked terminating frame")++ trailer_values = {}+ if trailer == b"\r\n":+ trailer_lines = []+ elif trailer.endswith(b"\r\n\r\n"):+ trailer_lines = trailer[:-4].split(b"\r\n")+ else:+ raise _IncompleteRequestBody("Incomplete aws-chunked trailer section")+ for line in trailer_lines:+ name, sep, value = line.partition(b":")+ if not sep or not name:+ raise _IncompleteRequestBody("Invalid aws-chunked trailer")+ try:+ name = name.decode("ascii").strip().lower()+ except UnicodeDecodeError as e:+ raise _IncompleteRequestBody("Invalid aws-chunked trailer name") from e+ if not name:+ raise _IncompleteRequestBody("Invalid aws-chunked trailer name")+ trailer_values.setdefault(name, value.decode("utf-8", errors="replace").strip())++ announced_trailers = {+ name.strip().lower()+ for name in headers.get("x-amz-trailer", "").split(",")+ if name.strip()+ }+ if not announced_trailers.issubset(trailer_values):+ raise _IncompleteRequestBody("Missing announced aws-chunked trailer")+decoded = b"".join(chunks)+ decoded_length = headers.get("x-amz-decoded-content-length")+ if decoded_length is not None:+ if not re.fullmatch(r"[0-9]+", decoded_length.strip()):+ raise _IncompleteRequestBody("Invalid X-Amz-Decoded-Content-Length")+ if len(decoded) != int(decoded_length):+ raise _IncompleteRequestBody("Decoded aws-chunked length mismatch")# A checksum computed while the body streamed arrives here rather than# among the request headers, and the rest of the request has no way to# tell the two apart -- so lift it into the headers, where every# checksum reader already looks. An explicit header wins: the trailer# is the late copy of the same field, not an override.- for line in trailer.split(b"\r\n"):- name, sep, value = line.partition(b":")- if not sep:- continue- name = name.decode("ascii", errors="replace").strip().lower()- if name:- headers.setdefault(- name, value.decode("utf-8", errors="replace").strip())+ for name, value in trailer_values.items():+ headers.setdefault(name, value)body = decodedif "aws-chunked" in content_encoding:@@ -665,15 +708,35 @@ async def _read_request_body(receive, method: str, headers: dict) -> bytes:chunks = []while True:message = await receive()+ if message.get("type") == "http.disconnect":+ raise _RequestBodyDisconnected+ if message.get("type") != "http.request":+ raise _IncompleteRequestBody("Unexpected ASGI message while reading request body")chunk = message.get("body", b"")if chunk:chunks.append(chunk)if not message.get("more_body", False):breakbody = b"".join(chunks)+ content_length = headers.get("content-length")+ if content_length is not None:+ content_length = content_length.strip()+ if not re.fullmatch(r"[0-9]+", content_length) or len(body) != int(content_length):+ raise _IncompleteRequestBody("Content-Length does not match request body")return _decode_aws_chunked_body(body, headers)+def _incomplete_request_body_response(method: str, path: str, headers: dict, query_params: dict):+ """Use the routed protocol's existing error envelope for an incomplete body."""+ message = "You did not provide the number of bytes specified by the Content-Length HTTP header"+ service = detect_service(method, path, headers, query_params)+ if service == "s3":+ return _get_module("s3")._error("IncompleteBody", message, 400)+ from ministack.core.responses import error_response_json++ return error_response_json("IncompleteBody", message, 400)++def _encode_header_value(v: str) -> bytes:try:return v.encode("latin-1")@@ -1048,6 +1111,10 @@ async def _handle_sqs_messages_request(method: str, path: str, headers: dict, qutry:mod = _get_module("sqs")now = time.time()+ queue_name_filter = None+ queue_account_filter = None+ if queue_url_filter is not None:+ queue_account_filter, queue_name_filter = mod._queue_ref_from_urlish(queue_url_filter)# Legacy AccountScopedDict state is keyed by (account_id, queue_url);# AccountRegionScopedDict state is keyed by (account_id, region, queue_url).@@ -1069,13 +1136,18 @@ async def _handle_sqs_messages_request(method: str, path: str, headers: dict, qucontinueif region_filter is not None and region != region_filter:continue- if queue_url_filter is not None and qurl != queue_url_filter:- continueif not isinstance(queue, dict):continue+ if queue_url_filter is not None:+ if queue.get("name") != queue_name_filter:+ continue+ if queue_account_filter and acct != queue_account_filter:+ continuemsgs = queue.get("messages") or []rendered = []for m in msgs:+ if m is None:+ continuerendered.append({"MessageId": m.get("id"),@@ -1094,7 +1166,8 @@ async def _handle_sqs_messages_request(method: str, path: str, headers: dict, qu"SequenceNumber": m.get("seq"),})- per_account.setdefault(acct, {}).setdefault(region, {})[qurl] = rendered+ display_qurl = queue_url_filter if queue_url_filter is not None else qurl+ per_account.setdefault(acct, {}).setdefault(region, {})[display_qurl] = renderedresponse = {"messages": per_account}except Exception as e:@@ -2806,7 +2879,14 @@ async def app(scope, receive, send):):return- body = await _read_request_body(receive, method, headers)+ try:+ body = await _read_request_body(receive, method, headers)+ except _RequestBodyDisconnected:+ return+ except _IncompleteRequestBody:+ response = _incomplete_request_body_response(method, path, headers, query_params)+ await _send_if_handled(send, response, receive)+ returnif await _send_if_handled(send, await _handle_post_body_shortcuts(method, path, headers, body, query_params, request_id), receivediff --git a/tests/test_request_body.py b/tests/test_request_body.pynew file mode 100644index 00000000..fd1a42b0--- /dev/null+++ b/tests/test_request_body.py@@ -0,0 +1,104 @@+import asyncio+import xml.etree.ElementTree as ET++import pytest++from ministack import app as app_module+++ ("body", "headers"),+ [+ (b"3", {"content-encoding": "aws-chunked"}),+ (b"x\r\n", {"content-encoding": "aws-chunked"}),+ (b"3\r\nab", {"content-encoding": "aws-chunked"}),+ (b"3\r\nabc\r\n", {"content-encoding": "aws-chunked"}),+ (b"3\r\nabc\r\n0\r\n", {"content-encoding": "aws-chunked"}),+ (+ b"1\r\na\r\n0\r\n\r\n",+ {"content-encoding": "aws-chunked", "x-amz-decoded-content-length": "2"},+ ),+ (+ b"1\r\na\r\n0\r\n\r\n",+ {"content-encoding": "aws-chunked", "x-amz-trailer": "x-amz-checksum-crc32"},+ ),+ ],+)+def test_decode_aws_chunked_rejects_incomplete_or_inconsistent_body(body, headers):+ with pytest.raises(app_module._IncompleteRequestBody):+ app_module._decode_aws_chunked_body(body, headers)+++def test_decode_aws_chunked_accepts_complete_body_and_announced_trailer():+ body = (+ b"3;chunk-signature=ignored\r\nabc\r\n"+ b"0;chunk-signature=ignored\r\n"+ b"x-amz-checksum-crc32: value\r\n\r\n"+ )+ headers = {+ "content-encoding": "aws-chunked",+ "x-amz-decoded-content-length": "3",+ "x-amz-trailer": "x-amz-checksum-crc32",+ }++ assert app_module._decode_aws_chunked_body(body, headers) == b"abc"+ assert headers["x-amz-checksum-crc32"] == "value"+++def _run_asgi_request(monkeypatch, headers, body_message):+ messages = []+ received = iter([body_message])++ async def receive():+ return next(received)++ async def send(message):+ messages.append(message)++ async def unexpected_dispatch(*_args):+ pytest.fail("incomplete request body reached service dispatch")++ monkeypatch.setattr(app_module, "_dispatch_service_request", unexpected_dispatch)+ scope = {+ "type": "http",+ "asgi": {"version": "3.0", "spec_version": "2.3"},+ "http_version": "1.1",+ "method": "PUT",+ "scheme": "http",+ "path": "/bucket/key",+ "raw_path": b"/bucket/key",+ "root_path": "",+ "query_string": b"",+ "headers": [(b"host", b"localhost:4566"), *headers],+ "client": ("127.0.0.1", 55555),+ "server": ("127.0.0.1", 4566),+ }++ asyncio.run(app_module.app(scope, receive, send))+ return messages+++ ("headers", "body"),+ [+ ([(b"content-length", b"5")], b"abc"),+ ([(b"content-encoding", b"aws-chunked")], b"3\r\nab"),+ ],+)+def test_incomplete_s3_body_returns_incomplete_body_before_dispatch(monkeypatch, headers, body):+ messages = _run_asgi_request(+ monkeypatch,+ headers,+ {"type": "http.request", "body": body, "more_body": False},+ )+ response = next(message for message in messages if message["type"] == "http.response.start")+ response_body = next(message["body"] for message in messages if message["type"] == "http.response.body")++ assert response["status"] == 400+ assert ET.fromstring(response_body).findtext("Code") == "IncompleteBody"+++def test_s3_body_disconnect_stops_before_dispatch(monkeypatch):+ messages = _run_asgi_request(monkeypatch, [], {"type": "http.disconnect"})++ assert messages == []\ No newline at end of file