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
remove aiohttp dependency, switch to stdlib native (#463)
Nahuel Nucera5b6b3ca3ca38
diff --git a/ministack/services/sns.py b/ministack/services/sns.pyindex a855e5b8..bbdc0d9e 100644--- a/ministack/services/sns.py+++ b/ministack/services/sns.py@@ -885,22 +885,47 @@ def _deliver_to_lambda(endpoint: str, envelope: str, topic_arn: str, sub_arn: stlogger.error("SNS fanout → Lambda %s failed: %s", func_name, exc)+def _http_post_sync(endpoint: str, payload: str, sns_message_type: str) -> int:+ """Blocking HTTP POST for SNS delivery. Runs on a worker thread so the+ event loop stays unblocked. Uses stdlib only — aiohttp was dropped because+ it isn't a declared dependency and wasn't shipped in the Docker image,+ which silently skipped every HTTP subscription confirmation (#460).++ Handles `http://user:pass@host/path` userinfo by stripping it from the URL+ and promoting to an Authorization: Basic header, matching real AWS SNS+ behaviour for HTTP(S) endpoints with embedded credentials. urllib leaves+ userinfo in the URL by default, which would break the Host header."""+ import base64 as _b64+ import urllib.parse+ import urllib.request+ parsed = urllib.parse.urlsplit(endpoint)+ headers = {+ "Content-Type": "text/plain; charset=UTF-8",+ "x-amz-sns-message-type": sns_message_type,+ }+ if parsed.username is not None:+ user = urllib.parse.unquote(parsed.username)+ pwd = urllib.parse.unquote(parsed.password or "")+ token = _b64.b64encode(f"{user}:{pwd}".encode("utf-8")).decode("ascii")+ headers["Authorization"] = f"Basic {token}"+ netloc = parsed.hostname or ""+ if parsed.port is not None:+ netloc = f"{netloc}:{parsed.port}"+ endpoint = urllib.parse.urlunsplit((parsed.scheme, netloc, parsed.path, parsed.query, parsed.fragment))+ req = urllib.request.Request(+ endpoint,+ data=payload.encode("utf-8"),+ headers=headers,+ method="POST",+ )+ with urllib.request.urlopen(req, timeout=5) as resp:+ return resp.status++async def _deliver_to_http(endpoint: str, payload: str):try:- import aiohttp- timeout = aiohttp.ClientTimeout(total=5)- async with aiohttp.ClientSession(timeout=timeout) as session:- async with session.post(- endpoint,- data=payload,- headers={- "Content-Type": "text/plain; charset=UTF-8",- "x-amz-sns-message-type": "Notification",- },- ) as resp:- logger.info("SNS HTTP delivery to %s: %s", endpoint, resp.status)- except ImportError:- logger.warning("aiohttp not installed — HTTP delivery skipped")+ status = await asyncio.to_thread(_http_post_sync, endpoint, payload, "Notification")+ logger.info("SNS HTTP delivery to %s: %s", endpoint, status)except Exception as exc:logger.warning("SNS HTTP delivery to %s failed: %s", endpoint, exc)@@ -922,20 +947,8 @@ async def _send_subscription_confirmation(topic_arn: str, sub: dict):"SigningCertURL": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-fake.pem",})try:- import aiohttp- timeout = aiohttp.ClientTimeout(total=5)- async with aiohttp.ClientSession(timeout=timeout) as session:- async with session.post(- endpoint,- data=payload,- headers={- "Content-Type": "text/plain; charset=UTF-8",- "x-amz-sns-message-type": "SubscriptionConfirmation",- },- ) as resp:- logger.info("SNS SubscriptionConfirmation sent to %s: %s", endpoint, resp.status)- except ImportError:- logger.info("aiohttp not installed — subscription confirmation for %s skipped", endpoint)+ status = await asyncio.to_thread(_http_post_sync, endpoint, payload, "SubscriptionConfirmation")+ logger.info("SNS SubscriptionConfirmation sent to %s: %s", endpoint, status)except Exception as exc:logger.warning("SNS SubscriptionConfirmation to %s failed: %s", endpoint, exc)diff --git a/tests/test_sns.py b/tests/test_sns.pyindex f42e8bae..83b63742 100644--- a/tests/test_sns.py+++ b/tests/test_sns.py@@ -1097,3 +1097,120 @@ def test_sns_fifo_e2e_fanout_with_dedup(sns, sqs):WaitTimeSeconds=1,)assert len(dup_msgs.get("Messages", [])) == 0, "Duplicate message should not be delivered"+++def test_sns_http_subscription_confirmation_delivered(sns):+ """HTTP subscribe() must POST a SubscriptionConfirmation to the endpoint (#460).++ Regression for the aiohttp-not-installed silent skip: the Docker image+ never shipped aiohttp, so every HTTP subscription's confirmation was+ logged-and-dropped. stdlib urllib must deliver.+ """+ import http.server+ import socketserver+ import threading as _threading++ received = []++ class _Handler(http.server.BaseHTTPRequestHandler):+ def do_POST(self):+ length = int(self.headers.get("Content-Length", "0"))+ body = self.rfile.read(length).decode("utf-8", errors="replace")+ received.append({+ "headers": dict(self.headers),+ "body": body,+ })+ self.send_response(200)+ self.end_headers()++ def log_message(self, *_args, **_kwargs):+ pass++ httpd = socketserver.TCPServer(("127.0.0.1", 0), _Handler)+ port = httpd.server_address[1]+ server_thread = _threading.Thread(target=httpd.serve_forever, daemon=True)+ server_thread.start()++ try:+ uid = _uuid_mod.uuid4().hex[:8]+ topic_arn = sns.create_topic(Name=f"intg-sns-http-conf-{uid}")["TopicArn"]+ sns.subscribe(+ TopicArn=topic_arn,+ Protocol="http",+ Endpoint=f"http://127.0.0.1:{port}/hook",+ )++ deadline = time.time() + 5+ while time.time() < deadline and not received:+ time.sleep(0.05)++ assert received, "SubscriptionConfirmation POST never arrived"+ first = received[0]+ header_lookup = {k.lower(): v for k, v in first["headers"].items()}+ assert header_lookup.get("x-amz-sns-message-type") == "SubscriptionConfirmation"+ parsed = json.loads(first["body"])+ assert parsed["Type"] == "SubscriptionConfirmation"+ assert parsed["TopicArn"] == topic_arn+ assert "Token" in parsed and parsed["Token"]+ assert "SubscribeURL" in parsed+ finally:+ httpd.shutdown()+ httpd.server_close()+++def test_sns_http_subscription_basic_auth_userinfo(sns):+ """`http://user:pass@host/path` endpoints must deliver Authorization: Basic (#460).++ Real AWS SNS promotes URL userinfo to a Basic auth header. urllib leaves+ userinfo in the URL by default, which also corrupts the Host header, so+ the SNS HTTP helper must parse-and-inject explicitly.+ """+ import base64 as _b64+ import http.server+ import socketserver+ import threading as _threading++ received = []++ class _Handler(http.server.BaseHTTPRequestHandler):+ def do_POST(self):+ length = int(self.headers.get("Content-Length", "0"))+ self.rfile.read(length)+ received.append({"headers": dict(self.headers)})+ self.send_response(200)+ self.end_headers()++ def log_message(self, *_args, **_kwargs):+ pass++ httpd = socketserver.TCPServer(("127.0.0.1", 0), _Handler)+ port = httpd.server_address[1]+ _threading.Thread(target=httpd.serve_forever, daemon=True).start()++ try:+ uid = _uuid_mod.uuid4().hex[:8]+ topic_arn = sns.create_topic(Name=f"intg-sns-http-basic-{uid}")["TopicArn"]+ sns.subscribe(+ TopicArn=topic_arn,+ Protocol="http",+ Endpoint=f"http://alice:[email protected]:{port}/hook",+ )++ deadline = time.time() + 5+ while time.time() < deadline and not received:+ time.sleep(0.05)++ assert received, "SubscriptionConfirmation POST never arrived"+ header_lookup = {k.lower(): v for k, v in received[0]["headers"].items()}++ auth = header_lookup.get("authorization", "")+ assert auth.startswith("Basic "), f"Expected Basic auth header, got {auth!r}"+ decoded = _b64.b64decode(auth[len("Basic "):]).decode("utf-8")+ assert decoded == "alice:s3cret"++ host = header_lookup.get("host", "")+ assert "@" not in host, f"Host header must not contain userinfo, got {host!r}"+ assert host == f"127.0.0.1:{port}"+ finally:+ httpd.shutdown()+ httpd.server_close()