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
Record direct-to-phone SNS publishes and serve them back (#1682)
himangshu5385cfdcbf48
diff --git a/README.md b/README.mdindex 67c0c2ab..8ea7276a 100644--- a/README.md+++ b/README.md@@ -99,6 +99,12 @@ curl http://localhost:4566/_ministack/sqs/messages# Filter by account and/or a specific queuecurl "http://localhost:4566/_ministack/sqs/messages?account=000000000000&QueueUrl=http://localhost:4566/000000000000/my-queue"++# Inspect SMS sent via SNS Publish with a PhoneNumber — grouped by recipient+curl http://localhost:4566/_ministack/sns/sms-messages++# Filter by recipient, account and/or region+curl "http://localhost:4566/_ministack/sns/sms-messages?phoneNumber=%2B15551234567"```The reset endpoint is especially useful in CI pipelines and test suites — call it in `setUp`/`beforeEach` to get a clean environment for every test without restarting the container. Add `?init=1` to re-run your init scripts after the reset, restoring any resources they create (VPCs, queues, seed data, etc.).@@ -124,11 +130,15 @@ docker run -p 4566:4566 \Or use the multi-tenancy feature — a 12-digit access key automatically becomes the account ID (see [Multi-Tenancy](#multi-tenancy) below).-Also compatible with LocalStack's health endpoint:+Also compatible with LocalStack's health and SMS-log endpoints:```bashcurl http://localhost:4566/_localstack/healthcurl http://localhost:4566/health++# Direct-to-phone SNS publishes, in LocalStack's+# {"sms_messages": {"<phone>": [...]}, "region": "<region>"} shape+curl http://localhost:4566/_ministack/sns/sms-messages```---diff --git a/ministack/app.py b/ministack/app.pyindex 77fa2b3a..97ca00a8 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1082,6 +1082,101 @@ async def _handle_sqs_messages_request(method: str, path: str, headers: dict, qureturn 200, {"Content-Type": "application/json"}, json.dumps(response).encode()+_SNS_SMS_PATH = "/_ministack/sns/sms-messages"+++async def _handle_sns_sms_messages_request(method: str, path: str, headers: dict, query_params: dict):+ """Handle the SNS SMS log endpoint.++ A `Publish` that carries a `PhoneNumber` and no `TopicArn` has nowhere to+ deliver to, so sns.py records it and this serves the recording back. Same+ read-only introspection as `/_ministack/ses/messages` and+ `/_ministack/sqs/messages`.++ The body keeps LocalStack's shape —+ `{"sms_messages": {"<phone>": [...]}, "region": "<region>"}` — so a suite+ moving here changes the URL and nothing else. Only the native+ `/_ministack/` path serves it: the compatibility surface stays narrow, and+ a `/_aws/` alias earns its place only against a concrete migration that+ would otherwise be painful.++ Filters:+ ?account=<12-digit-id> restrict to one account+ ?region=<aws-region> restrict to one region+ ?phoneNumber=<e164> restrict to one recipient; the key is present+ with an empty list when nothing was sent to it+ """+ if path != _SNS_SMS_PATH or method != "GET":+ return None++ account_id = None+ if "account" in query_params:+ raw_account = query_params["account"]+ account_id = raw_account[0] if isinstance(raw_account, (list, tuple)) else raw_account+ if not _12_DIGIT_RE.match(account_id):+ return (+ 400,+ {"Content-Type": "application/json"},+ json.dumps(+ {+ "__type": "InvalidAccountID",+ "message": f"Account ID must be 12 digits, got: {account_id}",+ }+ ).encode(),+ )++ default_region = os.environ.get("MINISTACK_REGION", "us-east-1")+ region_filter = None+ if "region" in query_params:+ raw_region = query_params["region"]+ region_filter = raw_region[0] if isinstance(raw_region, (list, tuple)) else raw_region+ phone_filter = None+ if "phoneNumber" in query_params:+ raw_phone = query_params["phoneNumber"]+ phone_filter = raw_phone[0] if isinstance(raw_phone, (list, tuple)) else raw_phone++ try:+ mod = _get_module("sns")+ try:+ all_data = mod._sms_messages.to_dict()+ except Exception:+ all_data = {}++ sms_messages: dict[str, list] = {}+ for scoped_key, records in all_data.items():+ if len(scoped_key) == 3:+ acct, region, phone = scoped_key+ elif len(scoped_key) == 2:+ acct, phone = scoped_key+ region = default_region+ else:+ continue+ if account_id is not None and acct != account_id:+ continue+ if region_filter is not None and region != region_filter:+ continue+ if phone_filter is not None and phone != phone_filter:+ continue+ if isinstance(records, list):+ sms_messages.setdefault(phone, []).extend(records)++ # LocalStack answers a filtered request with the key present and empty+ # rather than with an absent key, and a poller that reads+ # `body.sms_messages[phone]` depends on that.+ if phone_filter is not None:+ sms_messages.setdefault(phone_filter, [])++ response = {+ "sms_messages": sms_messages,+ "region": region_filter or default_region,+ }+ except Exception as e:+ logger.exception("Error retrieving SNS SMS messages: %s", e)+ return 500, {"Content-Type": "application/json"}, json.dumps({"message": str(e)}).encode()++ return 200, {"Content-Type": "application/json"}, json.dumps(response).encode()++async def _handle_pre_body_request(method: str, path: str, headers: dict, query_params: dict, request_id: str):"""Handle fast-path routes that do not require request body parsing."""# OPTIONS on an execute-api host / path MUST flow through apigateway.handle_execute@@ -1120,6 +1215,10 @@ async def _handle_pre_body_request(method: str, path: str, headers: dict, query_if response is not None:return response+ response = await _handle_sns_sms_messages_request(method, path, headers, query_params)+ if response is not None:+ return response+response = _handle_transfer_sftp_ports_request(method, path)if response is not None:return responsediff --git a/ministack/services/sns.py b/ministack/services/sns.pyindex 4b74acec..496cb362 100644--- a/ministack/services/sns.py+++ b/ministack/services/sns.py@@ -128,6 +128,23 @@ _sub_arn_to_topic = AccountRegionScopedDict()_platform_applications = AccountRegionScopedDict()_platform_endpoints = AccountRegionScopedDict()+# Direct-to-phone publishes, keyed by recipient phone number. SES and SQS both+# keep what they were sent so a test can read it back+# (/_ministack/ses/messages, /_ministack/sqs/messages); SNS was the one+# messaging service that logged a line and stored nothing, so an SMS was the+# only thing you could send and not observe. Served by app.py at+# /_ministack/sns/sms-messages.+_sms_messages = AccountRegionScopedDict()+++def _sms_log_for(phone_number: str) -> list:+ """The record list for one phone number in the current account and region."""+ records = _sms_messages.get(phone_number)+ if records is None:+ records = []+ _sms_messages[phone_number] = records+ return records+# ── Persistence ────────────────────────────────────────────@@ -135,6 +152,7 @@ def get_state():return {"topics": copy.deepcopy(_topics),"sub_arn_to_topic": copy.deepcopy(_sub_arn_to_topic),+ "sms_messages": copy.deepcopy(_sms_messages),"platform_applications": copy.deepcopy(_platform_applications),"platform_endpoints": copy.deepcopy(_platform_endpoints),}@@ -148,6 +166,7 @@ def _restore_state(data):if data:_topics.update(data.get("topics", {}))_sub_arn_to_topic.update(data.get("sub_arn_to_topic", {}))+ _sms_messages.update(data.get("sms_messages", {}))_platform_applications.update(data.get("platform_applications", {}))_platform_endpoints.update(data.get("platform_endpoints", {}))@@ -730,7 +749,21 @@ def _publish(params):if phone_number and not topic_arn:msg_id = new_uuid()- logger.info("SNS SMS stub to %s: %s", phone_number, message[:80])+ # There is nowhere for an SMS to go, so record it instead of dropping+ # it. Field names and nulls match what the endpoint serves, so the+ # record needs no reshaping on the way out. `_p` defaults an absent+ # parameter to "", and an absent Subject reads as null, not "".+ _sms_log_for(phone_number).append({+ "PhoneNumber": phone_number,+ "TopicArn": None,+ "SubscriptionArn": None,+ "MessageId": msg_id,+ "Message": message,+ "MessageAttributes": _parse_message_attributes(params),+ "MessageStructure": message_structure or None,+ "Subject": subject or None,+ })+ logger.info("SNS SMS to %s: %s", phone_number, message[:80])return _xml(200, "PublishResponse",f"<PublishResult><MessageId>{msg_id}</MessageId></PublishResult>")@@ -1721,5 +1754,6 @@ def _build_envelope(topic_arn: str, msg_id: str, message: str, subject: str,def reset():_topics.clear()_sub_arn_to_topic.clear()+ _sms_messages.clear()_platform_applications.clear()_platform_endpoints.clear()diff --git a/tests/test_sns.py b/tests/test_sns.pyindex 6ae32cce..b1dee471 100644--- a/tests/test_sns.py+++ b/tests/test_sns.py@@ -2,6 +2,7 @@ import ioimport jsonimport osimport time+import urllib.errorimport urllib.requestimport uuid as _uuid_modimport zipfile@@ -2185,3 +2186,125 @@ def test_sns_to_lambda_fanout_non_default_account(sqs):msgs = sqs_c.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=2)got = msgs.get("Messages", [])assert got, "SNS→Lambda delivery never arrived for a non-default account"+++# ---------------------------------------------------------------------------+# The SMS log — /_ministack/sns/sms-messages+# ---------------------------------------------------------------------------++def _sms_log(path: str = "/_ministack/sns/sms-messages", **params):+ url = f"{ENDPOINT.rstrip('/')}{path}"+ if params:+ url = f"{url}?{urlencode(params)}"+ with urllib.request.urlopen(url) as resp:+ assert resp.status == 200+ return json.loads(resp.read())+++def test_sns_sms_publish_is_recorded(sns):+ """A PhoneNumber publish is kept and served back, keyed by recipient."""+ phone = f"+1555{_uuid_mod.uuid4().int % 10_000_000:07d}"+ body = f"ministack sms log {_uuid_mod.uuid4().hex[:8]}"++ published = sns.publish(+ PhoneNumber=phone,+ Message=body,+ MessageAttributes={+ "AWS.SNS.SMS.SMSType": {"DataType": "String", "StringValue": "Transactional"}+ },+ )++ records = _sms_log(phoneNumber=phone)["sms_messages"][phone]+ assert len(records) == 1+ record = records[0]+ assert record["PhoneNumber"] == phone+ assert record["Message"] == body+ assert record["MessageId"] == published["MessageId"]+ assert record["TopicArn"] is None+ assert record["SubscriptionArn"] is None+ assert record["Subject"] is None+ assert record["MessageStructure"] is None+ assert record["MessageAttributes"]["AWS.SNS.SMS.SMSType"] == {+ "DataType": "String",+ "StringValue": "Transactional",+ }+++def test_sns_sms_log_is_served_only_at_the_ministack_path(sns):+ """There is no `/_aws/` alias — the native path is the only one.++ This asserted the opposite until review: the endpoint also answered at+ LocalStack's `/_aws/sns/sms-messages`. The compatibility surface is kept+ narrow on purpose — `/_ministack/ses/messages` and+ `/_ministack/sqs/messages` carry no alias either — and one is added only+ against a concrete migration that would otherwise be painful. None was+ named, so the alias went and this guards its absence.++ The BODY still keeps LocalStack's shape, which is where the real+ compatibility lives: a suite moving here changes the URL and nothing else.+ """+ phone = f"+1555{_uuid_mod.uuid4().int % 10_000_000:07d}"+ sns.publish(PhoneNumber=phone, Message="compat path")++ body = _sms_log(phoneNumber=phone)+ assert body["region"] == "us-east-1"+ assert [r["Message"] for r in body["sms_messages"][phone]] == ["compat path"]++ url = f"{ENDPOINT.rstrip('/')}/_aws/sns/sms-messages"+ with pytest.raises(urllib.error.HTTPError) as excinfo:+ urllib.request.urlopen(url)+ assert excinfo.value.code == 404+++def test_sns_sms_unknown_phone_returns_an_empty_list(sns):+ """A filtered read names the recipient even when nothing was sent to it."""+ phone = f"+1555{_uuid_mod.uuid4().int % 10_000_000:07d}"+ assert _sms_log(phoneNumber=phone)["sms_messages"] == {phone: []}+++def test_sns_sms_publishes_accumulate_in_order(sns):+ """Repeated publishes to one recipient append rather than replace."""+ phone = f"+1555{_uuid_mod.uuid4().int % 10_000_000:07d}"+ for i in range(3):+ sns.publish(PhoneNumber=phone, Message=f"msg-{i}")++ records = _sms_log(phoneNumber=phone)["sms_messages"][phone]+ assert [r["Message"] for r in records] == ["msg-0", "msg-1", "msg-2"]+ assert len({r["MessageId"] for r in records}) == 3+++def test_sns_sms_regions_are_separate(sns):+ """A publish in one region is not visible under another region's filter."""+ phone = f"+1555{_uuid_mod.uuid4().int % 10_000_000:07d}"+ west = _regional_client("sns", "us-west-2")+ sns.publish(PhoneNumber=phone, Message="east sms")+ west.publish(PhoneNumber=phone, Message="west sms")++ east_log = _sms_log(phoneNumber=phone, region="us-east-1")+ west_log = _sms_log(phoneNumber=phone, region="us-west-2")+ assert [r["Message"] for r in east_log["sms_messages"][phone]] == ["east sms"]+ assert east_log["region"] == "us-east-1"+ assert [r["Message"] for r in west_log["sms_messages"][phone]] == ["west sms"]+ assert west_log["region"] == "us-west-2"+++def test_sns_sms_invalid_account_rejected(sns):+ """?account=<not-12-digit> returns 400 InvalidAccountID."""+ import urllib.error++ try:+ urllib.request.urlopen(f"{ENDPOINT.rstrip('/')}/_ministack/sns/sms-messages?account=abc")+ raise AssertionError("expected 400")+ except urllib.error.HTTPError as exc:+ assert exc.code == 400+ assert json.loads(exc.read())["__type"] == "InvalidAccountID"+++def test_sns_topic_publish_is_not_in_the_sms_log(sns):+ """Only direct-to-phone publishes are recorded; topic publishes are not."""+ phone = f"+1555{_uuid_mod.uuid4().int % 10_000_000:07d}"+ topic_arn = sns.create_topic(Name=f"sms-log-topic-{_uuid_mod.uuid4().hex[:8]}")["TopicArn"]+ sns.publish(TopicArn=topic_arn, Message="not an sms")++ assert _sms_log(phoneNumber=phone)["sms_messages"] == {phone: []}+ sns.delete_topic(TopicArn=topic_arn)