Skip to content

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

fix(sqs): reflect caller Host header in QueueUrl (#1152) (#1201)

Thejuse225e9eecef2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e83beb37..20e89503 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Fixed
+- **SQS — `QueueUrl` used a hardcoded `localhost` host, breaking Docker-executed Lambdas (#1152)** — a Node.js Lambda running under `LAMBDA_EXECUTOR=docker` could not post to SQS without hardcoding the endpoint in its client: the AWS JS SDK v3 SQS client uses the returned `QueueUrl` as its request endpoint (`useQueueUrlAsEndpoint`), and every URL was rendered as `http://localhost:4566/…`, which inside the Lambda container resolves to the container itself rather than the host running MiniStack, so the request failed with connection refused. `CreateQueue`, `GetQueueUrl`, and `ListQueues` now render `QueueUrl`(s) using the caller's incoming `Host` header (how they actually reached MiniStack, e.g. `host.docker.internal:4566`), the same approach LocalStack takes; internal queue state stays keyed on canonical URLs and lookups remain host-agnostic. An explicitly configured `MINISTACK_HOST` pins the host and disables the rewrite.
### Added
- **SNS — `ListPlatformApplications`** — the mobile-push action returned `InvalidAction` even though platform applications created with `CreatePlatformApplication` were already stored. It now lists the caller's platform applications with their attributes and `NextToken` pagination; results are account+region scoped, matching AWS's per-region platform applications. Reported by @ctalibard-sk.
- **Kinesis Data Firehose — `AWS::KinesisFirehose::DeliveryStream` CloudFormation support** — stacks containing a delivery stream failed with `Unsupported resource type` even though the Firehose API already implemented `CreateDeliveryStream`. The resource now provisions through CloudFormation into the existing Firehose control plane (S3, Extended S3, Iceberg, and the other destination configs), `Ref` returns the delivery stream name, and `Fn::GetAtt Arn` returns its ARN. Reported by @ryan-bennett.
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index 2dd9a525..81129017 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -23,6 +23,7 @@ Actions:
import asyncio
import base64
+import contextvars
import copy
import hashlib
import json
@@ -78,6 +79,61 @@ DEFAULT_HOST = os.environ.get("MINISTACK_HOST", "localhost")
DEFAULT_PORT = os.environ.get("GATEWAY_PORT", "4566")
_DEDUP_WINDOW_S = 300 # 5 minutes
+# When the operator pins MINISTACK_HOST explicitly, keep the configured host in
+# every QueueUrl and never rewrite from the request. Otherwise we reflect the
+# Host the caller reached us on (see _externalize_url) so a Lambda in the Docker
+# executor gets a QueueUrl that resolves back to ministack, not to itself.
+_HOST_EXPLICIT = "MINISTACK_HOST" in os.environ
+_CANONICAL_NETLOC = f"{DEFAULT_HOST}:{DEFAULT_PORT}"
+# Host is attacker-controlled header input that ends up in response bodies, so
+# only accept a conservative hostname/IPv6/port charset before echoing it back.
+_HOST_SANITY_RE = re.compile(r"^[A-Za-z0-9.\-\[\]:_]+$")
+_request_host: contextvars.ContextVar[str] = contextvars.ContextVar(
+ "_request_host", default="")
+
+
+def _externalize_url(url: str) -> str:
+ """Rewrite a canonical queue URL's host with the caller's Host header.
+
+ AWS JS SDK v3 uses the QueueUrl itself as the request endpoint
+ (useQueueUrlAsEndpoint defaults true), so a `localhost` URL handed to a
+ Lambda in the Docker executor points back at the Lambda container. Reflect
+ the host the caller actually used (like LocalStack) so the URL is reusable.
+ Internal state stays keyed on canonical URLs; lookups are host-agnostic.
+ """
+ if _HOST_EXPLICIT or not isinstance(url, str):
+ return url
+ host = _request_host.get()
+ if not host or not _HOST_SANITY_RE.match(host):
+ return url
+ parts = urlparse(url)
+ # Only touch our own canonical netloc; leave anything else untouched. Host
+ # is echoed verbatim — if it carries no port we don't invent one (a reverse
+ # proxy on port 80 is valid).
+ if parts.netloc != _CANONICAL_NETLOC:
+ return url
+ return parts._replace(netloc=host).geturl()
+
+
+def _externalize_result(result: dict) -> dict:
+ """Rewrite queue-URL keys in an outgoing result with the request Host.
+
+ Operates on a shallow copy so stored queue state stays canonical.
+ """
+ if _HOST_EXPLICIT or not isinstance(result, dict):
+ return result
+ host = _request_host.get()
+ if not host or not _HOST_SANITY_RE.match(host):
+ return result
+ if "QueueUrl" not in result and "QueueUrls" not in result:
+ return result
+ out = dict(result)
+ if "QueueUrl" in out:
+ out["QueueUrl"] = _externalize_url(out["QueueUrl"])
+ if "QueueUrls" in out:
+ out["QueueUrls"] = [_externalize_url(u) for u in out["QueueUrls"]]
+ return out
+
# ── Exceptions ──────────────────────────────────────────────
@@ -201,6 +257,9 @@ except Exception:
async def handle_request(method: str, path: str, headers: dict,
body: bytes, query_params: dict) -> tuple:
"""Handle SQS requests — supports both legacy Query API and modern JSON API."""
+ # Record how the caller reached us so responses can echo that host in
+ # queue URLs (see _externalize_url). Header keys are lowercased upstream.
+ _request_host.set(headers.get("host", ""))
target = headers.get("x-amz-target", "")
# JSON protocol (X-Amz-Target: AmazonSQS.*)
@@ -260,7 +319,10 @@ async def _dispatch(action: str, data: dict, qurl: str) -> dict:
result = fn(data, qurl)
if asyncio.iscoroutine(result):
result = await result
- return result
+ # Single choke point for the two protocol layers (_handle_json /
+ # _handle_query). Internal callers (SNS fan-out, ESM helpers) invoke the
+ # action functions directly and so keep canonical URLs.
+ return _externalize_result(result)
# ────────────────────────────────────────────────────────────
diff --git a/tests/test_sqs.py b/tests/test_sqs.py
index 91e6c6b3..c5e658d6 100644
--- a/tests/test_sqs.py
+++ b/tests/test_sqs.py
@@ -150,6 +150,104 @@ def test_sqs_queue_url_reflects_env_host(sqs):
assert expected_host in url
assert "intg-sqs-urlhost" in url
+
+# ── #1152: QueueUrl reflects the caller's Host header ───────────────────────
+#
+# AWS JS SDK v3 uses the QueueUrl itself as the request endpoint
+# (useQueueUrlAsEndpoint), so a Lambda in the Docker executor needs a QueueUrl
+# whose host resolves back to ministack (e.g. host.docker.internal), not the
+# hardcoded `localhost`. When the operator pins MINISTACK_HOST the rewriting is
+# intentionally off, so these tests are skipped in that configuration.
+
+_DOCKER_HOST = "host.docker.internal:4566"
+
+_skip_if_host_pinned = pytest.mark.skipif(
+ bool(os.environ.get("MINISTACK_HOST")),
+ reason="explicit MINISTACK_HOST pins the queue-url host; rewriting is off",
+)
+
+
+def _json_sqs_with_host(target, payload_dict, host_header):
+ """Send a JSON-protocol SQS request with an explicit Host header and return
+ (status, parsed_body). Uses raw http.client so the Host header can be forced
+ to a value different from the TCP host boto3 would otherwise send."""
+ import http.client
+
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ p = urlparse(endpoint)
+ conn = http.client.HTTPConnection(p.hostname or "localhost", p.port or 4566)
+ body = json.dumps(payload_dict)
+ conn.putrequest("POST", "/", skip_host=True)
+ conn.putheader("Host", host_header)
+ conn.putheader("X-Amz-Target", f"AmazonSQS.{target}")
+ conn.putheader("Content-Type", "application/x-amz-json-1.0")
+ conn.putheader("Content-Length", str(len(body)))
+ conn.endheaders()
+ conn.send(body.encode())
+ resp = conn.getresponse()
+ status = resp.status
+ data = json.loads(resp.read() or b"{}")
+ conn.close()
+ return status, data
+
+
+@_skip_if_host_pinned
+def test_sqs_create_queue_reflects_request_host_json(sqs):
+ qname = f"intg-sqs-host-json-{_uuid_mod.uuid4().hex[:8]}"
+ status, payload = _json_sqs_with_host(
+ "CreateQueue", {"QueueName": qname}, _DOCKER_HOST)
+ assert status == 200, payload
+ assert payload["QueueUrl"].startswith(f"http://{_DOCKER_HOST}/")
+ assert qname in payload["QueueUrl"]
+ sqs.delete_queue(QueueUrl=sqs.get_queue_url(QueueName=qname)["QueueUrl"])
+
+
+@_skip_if_host_pinned
+def test_sqs_get_queue_url_reflects_request_host_json(sqs):
+ qname = f"intg-sqs-host-geturl-{_uuid_mod.uuid4().hex[:8]}"
+ sqs.create_queue(QueueName=qname)
+ status, payload = _json_sqs_with_host(
+ "GetQueueUrl", {"QueueName": qname}, _DOCKER_HOST)
+ assert status == 200, payload
+ assert payload["QueueUrl"].startswith(f"http://{_DOCKER_HOST}/")
+ assert qname in payload["QueueUrl"]
+ sqs.delete_queue(QueueUrl=sqs.get_queue_url(QueueName=qname)["QueueUrl"])
+
+
+@_skip_if_host_pinned
+def test_sqs_list_queues_reflects_request_host_json(sqs):
+ prefix = f"intg-sqs-host-list-{_uuid_mod.uuid4().hex[:8]}-"
+ sqs.create_queue(QueueName=f"{prefix}a")
+ sqs.create_queue(QueueName=f"{prefix}b")
+ status, payload = _json_sqs_with_host(
+ "ListQueues", {"QueueNamePrefix": prefix}, _DOCKER_HOST)
+ assert status == 200, payload
+ urls = payload.get("QueueUrls", [])
+ assert len(urls) >= 2
+ assert all(u.startswith(f"http://{_DOCKER_HOST}/") for u in urls)
+ for u in urls:
+ sqs.delete_queue(QueueUrl=u)
+
+
+@_skip_if_host_pinned
+def test_sqs_host_rewritten_url_is_usable_roundtrip(sqs):
+ """The rewritten host.docker.internal URL must still resolve to the queue via
+ host-agnostic lookup — proves we only rewrite the response, not stored state."""
+ qname = f"intg-sqs-host-rt-{_uuid_mod.uuid4().hex[:8]}"
+ status, payload = _json_sqs_with_host(
+ "CreateQueue", {"QueueName": qname}, _DOCKER_HOST)
+ assert status == 200, payload
+ docker_url = payload["QueueUrl"]
+ assert docker_url.startswith(f"http://{_DOCKER_HOST}/")
+ # boto3 is pointed at localhost; it passes QueueUrl in the request body, so
+ # the server must resolve the host.docker.internal URL by name.
+ sqs.send_message(QueueUrl=docker_url, MessageBody="via-docker-url")
+ msgs = sqs.receive_message(
+ QueueUrl=docker_url, MaxNumberOfMessages=1, WaitTimeSeconds=2)
+ assert [m["Body"] for m in msgs.get("Messages", [])] == ["via-docker-url"]
+ sqs.delete_queue(QueueUrl=docker_url)
+
+
def test_sqs_send_receive_delete(sqs):
url = sqs.create_queue(QueueName="intg-sqs-srd")["QueueUrl"]
sqs.send_message(QueueUrl=url, MessageBody="test-body")