Skip to content

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

Scope IoT state by region (#1211)

Ian Oberstd0e472df4eb8
diff --git a/ministack/app.py b/ministack/app.py
index 6f82d51e..c1c3af0f 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -1709,7 +1709,8 @@ async def app(scope, receive, send):
_ws_key = extract_access_key_id(ws_headers, ws_query)
if _ws_key:
set_request_account_id(_ws_key)
- set_request_region(extract_region(ws_headers, ws_query))
+ ws_region = extract_region(ws_headers, ws_query)
+ set_request_region(ws_region)
ws_host = ws_headers.get("host", "")
ws_path = scope.get("path", "")
parsed = _parse_execute_api_url(ws_host, ws_path)
@@ -1735,7 +1736,7 @@ async def app(scope, receive, send):
# params or Authorization header, fall back to default.
account_id = _ws_resolve_iot_account_id(scope, ws_headers)
await _get_module("iot").handle_websocket(
- scope, receive, send, account_id
+ scope, receive, send, account_id, ws_region
)
except Exception:
logger.exception("Error in WebSocket dispatch")
diff --git a/ministack/core/persistence.py b/ministack/core/persistence.py
index 9077b313..4f1cb7f6 100644
--- a/ministack/core/persistence.py
+++ b/ministack/core/persistence.py
@@ -35,6 +35,7 @@ SERVICE_STATE_FORMAT_VERSIONS = {
"emr": 3,
"eks": 3,
"inspector2": 3,
+ "iot": 3,
"efs": 3,
"s3files": 3,
"batch": 3,
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index c22b8e0b..713c6e95 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -14,12 +14,13 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:
- ``DescribeEndpoint`` returning a per-account hostname
This is the control plane — pure HTTP/JSON, no MQTT broker
-dependency. The data plane (``iot_data.py``, ``iot_broker.py``) is
+dependency. The data plane (``iot_data.py``) is
implemented separately and only depends on this module for certificate
lookups (mTLS).
-State is fully isolated per account via ``AccountScopedDict`` and persisted
-through ``get_state``/``restore_state``. The Local CA (used to sign
+State is fully isolated per account and region via
+``AccountRegionScopedDict`` and persisted through
+``get_state``/``restore_state``. The Local CA (used to sign
``CreateKeysAndCertificate`` certificates) is also persisted so previously
issued client certificates remain valid across restarts.
"""
@@ -43,7 +44,7 @@ from typing import Awaitable, Callable
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.persistence import load_state
from ministack.core.responses import (
- AccountScopedDict,
+ AccountRegionScopedDict,
_request_account_id,
error_response_json,
get_account_id,
@@ -67,16 +68,16 @@ _NAME_RE = re.compile(r"^[a-zA-Z0-9:_-]{1,128}$")
# ---------------------------------------------------------------------------
-# Module-level state (account-scoped)
+# Module-level state (account-and-region-scoped)
# ---------------------------------------------------------------------------
-_things: AccountScopedDict = AccountScopedDict() # thingName -> Thing dict
-_thing_types: AccountScopedDict = AccountScopedDict()
-_thing_groups: AccountScopedDict = AccountScopedDict()
-_certificates: AccountScopedDict = AccountScopedDict() # certificateId -> Certificate dict
-_policies: AccountScopedDict = AccountScopedDict() # policyName -> Policy dict
-_topic_rules: AccountScopedDict = AccountScopedDict() # ruleName -> TopicRule dict
-_shadows: AccountScopedDict = AccountScopedDict() # (thingName, shadowName) -> shadow dict
+_things: AccountRegionScopedDict = AccountRegionScopedDict() # thingName -> Thing dict
+_thing_types: AccountRegionScopedDict = AccountRegionScopedDict()
+_thing_groups: AccountRegionScopedDict = AccountRegionScopedDict()
+_certificates: AccountRegionScopedDict = AccountRegionScopedDict()
+_policies: AccountRegionScopedDict = AccountRegionScopedDict()
+_topic_rules: AccountRegionScopedDict = AccountRegionScopedDict()
+_shadows: AccountRegionScopedDict = AccountRegionScopedDict()
# Local CA state — lazily generated on first use, persisted across restarts.
import threading
@@ -132,14 +133,21 @@ def _broker_get_state() -> dict:
"payload": base64.b64encode(msg.payload).decode("ascii"),
"qos": msg.qos,
})
- return {"retained": retained_list}
+ return {"region_scoped": True, "retained": retained_list}
def _broker_restore_state(data: dict | None) -> None:
if not data:
return
+ legacy_topics = not data.get("region_scoped", False)
for entry in data.get("retained", []):
topic = entry["topic"]
+ if legacy_topics:
+ account_id, separator, unscoped_topic = topic.partition("/")
+ if separator:
+ topic = (
+ f"{account_id}/{get_region()}/{unscoped_topic}"
+ )
payload = base64.b64decode(entry["payload"])
qos = entry.get("qos", 0)
_retained[topic] = _RetainedMessage(topic, payload, qos)
@@ -1453,9 +1461,9 @@ def _list_topic_rules(qp: dict) -> tuple:
# ---------------------------------------------------------------------------
-def lookup_certificate_by_id(cert_id: str) -> dict | None:
- """Return the Certificate record for a given certificateId in the current account, or None."""
- return _certificates.get(cert_id)
+def lookup_certificate_by_id(cert_id: str, region: str) -> dict | None:
+ """Return a certificate in the current account and explicit region."""
+ return _certificates.get_scoped(get_account_id(), region, cert_id)
# ---------------------------------------------------------------------------
@@ -1640,8 +1648,8 @@ def delete_thing_shadow(thing_name: str, shadow_name: str) -> tuple:
#
# Multi-tenancy is enforced by transparent topic prefixing: every
# PUBLISH/SUBSCRIBE topic seen on the wire is internally prefixed with the
-# caller's account_id before it hits the registry, and the prefix is
-# stripped on outbound delivery.
+# caller's account_id and region before it hits the registry, and the prefix
+# is stripped on outbound delivery.
_broker_logger = logging.getLogger("iot_broker")
@@ -1650,8 +1658,8 @@ _broker_logger = logging.getLogger("iot_broker")
# ---------------------------------------------------------------------------
_subscriptions: dict[str, set["_Subscription"]] = {}
-_connected_clients: dict[tuple[str, str], "_WSSession"] = {}
-_persistent_sessions: dict[tuple[str, str], "_PersistentSessionState"] = {}
+_connected_clients: dict[tuple[str, str, str], "_WSSession"] = {}
+_persistent_sessions: dict[tuple[str, str, str], "_PersistentSessionState"] = {}
_broker_lock = asyncio.Lock()
_SESSION_EXPIRY_SECONDS: int = int(os.environ.get("IOT_SESSION_EXPIRY_SECONDS", "3600"))
@@ -1686,18 +1694,27 @@ _RETRANSMIT_INTERVAL_SECONDS = int(os.environ.get("IOT_RETRANSMIT_SECONDS", "10"
class _Subscription:
- __slots__ = ("subscription_id", "filter_prefixed", "account_id", "deliver", "granted_qos")
+ __slots__ = (
+ "subscription_id",
+ "filter_prefixed",
+ "account_id",
+ "region",
+ "deliver",
+ "granted_qos",
+ )
def __init__(
self,
filter_prefixed: str,
account_id: str,
+ region: str,
deliver: Callable[[str, bytes, int], Awaitable[None]],
granted_qos: int = 0,
):
self.subscription_id = uuid.uuid4().hex
self.filter_prefixed = filter_prefixed
self.account_id = account_id
+ self.region = region
self.deliver = deliver
self.granted_qos = granted_qos
@@ -1713,12 +1730,12 @@ class _Subscription:
# ---------------------------------------------------------------------------
-def _scoped_topic(account_id: str, topic: str) -> str:
- return f"{account_id}/{topic}"
+def _scoped_topic(account_id: str, region: str, topic: str) -> str:
+ return f"{account_id}/{region}/{topic}"
-def _unscope_topic(account_id: str, scoped_topic: str) -> str:
- prefix = f"{account_id}/"
+def _unscope_topic(account_id: str, region: str, scoped_topic: str) -> str:
+ prefix = f"{account_id}/{region}/"
if scoped_topic.startswith(prefix):
return scoped_topic[len(prefix):]
return scoped_topic
@@ -1782,8 +1799,12 @@ async def broker_stop() -> None:
_BASIC_INGEST_PREFIX = "$aws/rules/"
-def _rules_for_account(account_id: str) -> list[dict]:
- return [v for (acct, _key), v in _topic_rules._data.items() if acct == account_id]
+def _rules_for_account(account_id: str, region: str) -> list[dict]:
+ return [
+ value
+ for (acct, reg, _key), value in _topic_rules._data.items()
+ if acct == account_id and reg == region
+ ]
def _rule_event(payload: bytes):
@@ -1821,8 +1842,10 @@ def _run_rule_actions(account_id: str, rule: dict, payload: bytes) -> None:
_dispatch_rule_to_lambda(account_id, lam["functionArn"], event)
-def _evaluate_topic_rules(account_id: str, topic: str, payload: bytes) -> None:
- for rule in _rules_for_account(account_id):
+def _evaluate_topic_rules(
+ account_id: str, region: str, topic: str, payload: bytes
+) -> None:
+ for rule in _rules_for_account(account_id, region):
filter_ = _rule_topic_filter(rule.get("sql", ""))
if filter_ and _topic_matches(filter_, topic):
_run_rule_actions(account_id, rule, payload)
@@ -1830,6 +1853,7 @@ def _evaluate_topic_rules(account_id: str, topic: str, payload: bytes) -> None:
async def broker_publish(
account_id: str,
+ region: str,
topic: str,
payload: bytes,
qos: int = 0,
@@ -1839,10 +1863,14 @@ async def broker_publish(
# to that rule's actions and bypasses pub/sub delivery entirely.
if topic.startswith(_BASIC_INGEST_PREFIX):
rule_name = topic[len(_BASIC_INGEST_PREFIX):].split("/", 1)[0]
- _run_rule_actions(account_id, _topic_rules.get_scoped(account_id, None, rule_name), payload)
+ _run_rule_actions(
+ account_id,
+ _topic_rules.get_scoped(account_id, region, rule_name),
+ payload,
+ )
return
- scoped = _scoped_topic(account_id, topic)
+ scoped = _scoped_topic(account_id, region, topic)
if retain:
if not payload:
@@ -1854,54 +1882,69 @@ async def broker_publish(
subs = [s for sset in _subscriptions.values() for s in sset]
for sub in subs:
+ if sub.account_id != account_id or sub.region != region:
+ continue
if _topic_matches(sub.filter_prefixed, scoped):
try:
effective_qos = min(qos, sub.granted_qos)
- await sub.deliver(_unscope_topic(sub.account_id, scoped), payload, effective_qos)
+ await sub.deliver(
+ _unscope_topic(sub.account_id, sub.region, scoped),
+ payload,
+ effective_qos,
+ )
except Exception:
_broker_logger.exception("IoT broker: subscriber %s delivery failed", sub.subscription_id)
if qos >= 1:
for key, ps in list(_persistent_sessions.items()):
- ps_account_id, ps_client_id = key
- if ps_account_id != account_id:
+ ps_account_id, ps_region, _ps_client_id = key
+ if ps_account_id != account_id or ps_region != region:
continue
if key in _connected_clients:
continue
if _is_session_expired(ps):
continue
for filt in ps.subscriptions:
- scoped_filter = _scoped_topic(ps_account_id, filt)
+ scoped_filter = _scoped_topic(ps_account_id, ps_region, filt)
if _topic_matches(scoped_filter, scoped):
ps.queued_messages.append((topic, payload, qos))
if len(ps.queued_messages) > _MAX_QUEUED_MESSAGES:
ps.queued_messages = ps.queued_messages[-_MAX_QUEUED_MESSAGES:]
break
- _evaluate_topic_rules(account_id, topic, payload)
+ _evaluate_topic_rules(account_id, region, topic, payload)
async def broker_subscribe(
account_id: str,
+ region: str,
topic_filter: str,
callback: Callable[[str, bytes, int], Awaitable[None]],
granted_qos: int = 0,
) -> str:
- filter_prefixed = _scoped_topic(account_id, topic_filter)
- sub = _Subscription(filter_prefixed, account_id, callback, granted_qos)
+ filter_prefixed = _scoped_topic(account_id, region, topic_filter)
+ sub = _Subscription(
+ filter_prefixed, account_id, region, callback, granted_qos
+ )
async with _broker_lock:
_subscriptions.setdefault(filter_prefixed, set()).add(sub)
has_wildcard = "+" in topic_filter or "#" in topic_filter
if not has_wildcard:
+ scope_prefix = f"{account_id}/{region}/"
retained_to_send = [
- r for k, r in _retained.items() if _topic_matches(filter_prefixed, k)
+ r
+ for k, r in _retained.items()
+ if k.startswith(scope_prefix)
+ and _topic_matches(filter_prefixed, k)
]
else:
retained_to_send = []
for r in retained_to_send:
try:
- await sub.deliver(_unscope_topic(account_id, r.topic), r.payload, r.qos)
+ await sub.deliver(
+ _unscope_topic(account_id, region, r.topic), r.payload, r.qos
+ )
except Exception:
_broker_logger.exception("IoT broker: retained-message delivery failed")
@@ -1930,16 +1973,20 @@ def broker_reset() -> None:
# ---------------------------------------------------------------------------
-def _register_client(account_id: str, client_id: str, session: "_WSSession") -> None:
- _connected_clients[(account_id, client_id)] = session
+def _register_client(
+ account_id: str, region: str, client_id: str, session: "_WSSession"
+) -> None:
+ _connected_clients[(account_id, region, client_id)] = session
-def _deregister_client(account_id: str, client_id: str) -> None:
- _connected_clients.pop((account_id, client_id), None)
+def _deregister_client(account_id: str, region: str, client_id: str) -> None:
+ _connected_clients.pop((account_id, region, client_id), None)
-async def _force_disconnect_duplicate(account_id: str, client_id: str) -> None:
- key = (account_id, client_id)
+async def _force_disconnect_duplicate(
+ account_id: str, region: str, client_id: str
+) -> None:
+ key = (account_id, region, client_id)
existing = _connected_clients.get(key)
if existing is not None:
_broker_logger.info("IoT broker: duplicate client_id=%s, forcing old connection closed", client_id)
@@ -2058,9 +2105,10 @@ def _max_frame_buffer_bytes() -> int:
class _WSSession:
- def __init__(self, send_coro, account_id: str):
+ def __init__(self, send_coro, account_id: str, region: str):
self._send = send_coro
self.account_id = account_id
+ self.region = region
self._sub_ids: list[str] = []
self._sub_filters: dict[str, str] = {}
self._sub_granted_qos: dict[str, int] = {}
@@ -2183,10 +2231,14 @@ class _WSSession:
self._will_retain = False
self._graceful_disconnect = False
- await _force_disconnect_duplicate(self.account_id, self._client_id)
- _register_client(self.account_id, self._client_id, self)
+ await _force_disconnect_duplicate(
+ self.account_id, self.region, self._client_id
+ )
+ _register_client(
+ self.account_id, self.region, self._client_id, self
+ )
- session_key = (self.account_id, self._client_id)
+ session_key = (self.account_id, self.region, self._client_id)
session_present = False
if clean_session:
@@ -2197,7 +2249,11 @@ class _WSSession:
session_present = True
for topic_filter in existing_ps.subscriptions:
sid = await broker_subscribe(
- self.account_id, topic_filter, self.deliver_to_client, 1
+ self.account_id,
+ self.region,
+ topic_filter,
+ self.deliver_to_client,
+ 1,
)
self._sub_ids.append(sid)
self._sub_filters[sid] = topic_filter
@@ -2230,7 +2286,14 @@ class _WSSession:
_broker_logger.warning("IoT broker: PUBLISH rejected — invalid topic: %r", topic)
return False
payload = body[off:]
- await broker_publish(self.account_id, topic, payload, qos=qos, retain=retain)
+ await broker_publish(
+ self.account_id,
+ self.region,
+ topic,
+ payload,
+ qos=qos,
+ retain=retain,
+ )
if qos == 1 and packet_id is not None:
await self.send_bytes(_make_puback(packet_id))
return True
@@ -2245,7 +2308,13 @@ class _WSSession:
off += 1
granted_qos = min(req_qos, 1)
granted.append(granted_qos)
- sid = await broker_subscribe(self.account_id, topic, self.deliver_to_client, granted_qos)
+ sid = await broker_subscribe(
+ self.account_id,
+ self.region,
+ topic,
+ self.deliver_to_client,
+ granted_qos,
+ )
self._sub_ids.append(sid)
self._sub_filters[sid] = topic
self._sub_granted_qos[sid] = granted_qos
@@ -2288,6 +2357,7 @@ class _WSSession:
if not self._graceful_disconnect and self._will_topic is not None:
await broker_publish(
self.account_id,
+ self.region,
self._will_topic,
self._will_message or b"",
qos=self._will_qos,
@@ -2301,10 +2371,10 @@ class _WSSession:
self._sub_filters.clear()
self._sub_granted_qos.clear()
if self._client_id:
- _deregister_client(self.account_id, self._client_id)
+ _deregister_client(self.account_id, self.region, self._client_id)
def _preserve_session(self) -> None:
- session_key = (self.account_id, self._client_id)
+ session_key = (self.account_id, self.region, self._client_id)
unprefixed_filters = list(self._sub_filters.values())
existing = _persistent_sessions.get(session_key)
if existing is not None:
@@ -2316,7 +2386,9 @@ class _WSSession:
)
-async def handle_websocket(scope: dict, receive, send, account_id: str) -> None:
+async def handle_websocket(
+ scope: dict, receive, send, account_id: str, region: str
+) -> None:
"""Drive an MQTT-over-WebSocket session."""
msg = await receive()
if msg.get("type") != "websocket.connect":
@@ -2341,7 +2413,7 @@ async def handle_websocket(scope: dict, receive, send, account_id: str) -> None:
await send(accept)
ctx_token = _request_account_id.set(account_id)
- session = _WSSession(send, account_id)
+ session = _WSSession(send, account_id, region)
max_buffer = _max_frame_buffer_bytes()
try:
diff --git a/ministack/services/iot_data.py b/ministack/services/iot_data.py
index f97c3d64..b9894a4f 100644
--- a/ministack/services/iot_data.py
+++ b/ministack/services/iot_data.py
@@ -9,7 +9,7 @@ requests with the ``iotdata`` scope) or via the host pattern
``data-ats.iot.{region}.{host}`` / ``data.iot.{region}.{host}``.
Bridges into the in-memory MQTT broker via :mod:`ministack.services.iot`,
-which applies account-scoped topic prefixing transparently.
+which applies account-and-region-scoped topic prefixing transparently.
"""
from __future__ import annotations
@@ -21,6 +21,7 @@ from urllib.parse import unquote
from ministack.core.responses import (
error_response_json,
get_account_id,
+ get_region,
json_response,
)
from ministack.services import iot as _iot_module
@@ -168,7 +169,12 @@ async def _publish(raw_topic: str, body: bytes, qp: dict) -> tuple:
try:
await _iot_module.broker_publish(
- get_account_id(), topic, body or b"", qos=qos, retain=retain
+ get_account_id(),
+ get_region(),
+ topic,
+ body or b"",
+ qos=qos,
+ retain=retain,
)
except Exception as e:
logger.exception("iot-data publish failed")
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 0a112f58..3c80018e 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -603,26 +603,396 @@ import asyncio
import struct
from ministack.services.iot import (
+ _RETRANSMIT_INTERVAL_SECONDS,
PKT_CONNACK,
PKT_CONNECT,
PKT_DISCONNECT,
PKT_PUBACK,
PKT_PUBLISH,
PKT_SUBSCRIBE,
- _InFlightMessage,
- _RETRANSMIT_INTERVAL_SECONDS,
- _Subscription,
- _WSSession,
_encode_remaining_length,
_encode_string,
+ _InFlightMessage,
_make_puback,
_make_suback,
_persistent_sessions,
- broker_publish as publish,
+ broker_publish,
+ broker_subscribe,
+)
+from ministack.services.iot import (
+ _Subscription as _IoTSubscription,
+)
+from ministack.services.iot import (
+ _WSSession as _IoTWSSession,
+)
+from ministack.services.iot import (
broker_reset as reset,
- broker_subscribe as subscribe,
)
+_TEST_REGION = "us-east-1"
+
+
+def _WSSession(send, account_id, region=_TEST_REGION):
+ return _IoTWSSession(send, account_id, region)
+
+
+def _Subscription(
+ filter_prefixed,
+ account_id,
+ deliver,
+ granted_qos=0,
+ region=_TEST_REGION,
+):
+ return _IoTSubscription(
+ filter_prefixed,
+ account_id,
+ region,
+ deliver,
+ granted_qos,
+ )
+
+
+async def publish(account_id, topic, payload, **kwargs):
+ await broker_publish(
+ account_id, _TEST_REGION, topic, payload, **kwargs
+ )
+
+
+async def subscribe(account_id, topic_filter, callback, granted_qos=0):
+ return await broker_subscribe(
+ account_id,
+ _TEST_REGION,
+ topic_filter,
+ callback,
+ granted_qos,
+ )
+
+
+def test_iot_control_plane_identity_stores_are_region_scoped():
+ from ministack.core.responses import AccountRegionScopedDict
+ from ministack.services import iot as iot_module
+
+ stores = (
+ iot_module._things,
+ iot_module._thing_types,
+ iot_module._thing_groups,
+ iot_module._certificates,
+ iot_module._policies,
+ iot_module._topic_rules,
+ iot_module._shadows,
+ )
+ assert all(isinstance(store, AccountRegionScopedDict) for store in stores)
+
+
+def test_iot_region_scoped_control_plane_accepts_same_resource_names():
+ from ministack.core.responses import (
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import iot as iot_module
+
+ account_id = "123456789012"
+ resource_name = "same_regional_name"
+ policy_document = json.dumps({
+ "Version": "2012-10-17",
+ "Statement": [],
+ })
+
+ async def _request(region, method, path, payload=None):
+ set_request_account_id(account_id)
+ set_request_region(region)
+ body = json.dumps(payload or {}).encode()
+ return await iot_module.handle_request(
+ method, path, {}, body, {}
+ )
+
+ async def _run():
+ try:
+ east_thing = await _request(
+ "us-east-1",
+ "POST",
+ f"/things/{resource_name}",
+ {"attributePayload": {"attributes": {"scope": "east"}}},
+ )
+ west_thing = await _request(
+ "us-west-2",
+ "POST",
+ f"/things/{resource_name}",
+ {"attributePayload": {"attributes": {"scope": "west"}}},
+ )
+ assert east_thing[0] == 200
+ assert west_thing[0] == 200
+
+ for region, expected in (
+ ("us-east-1", "east"),
+ ("us-west-2", "west"),
+ ):
+ response = await _request(
+ region, "GET", f"/things/{resource_name}"
+ )
+ assert response[0] == 200
+ assert json.loads(response[2])["attributes"]["scope"] == expected
+
+ policy = await _request(
+ region,
+ "POST",
+ f"/policies/{resource_name}",
+ {"policyDocument": policy_document},
+ )
+ rule = await _request(
+ region,
+ "POST",
+ f"/rules/{resource_name}",
+ {
+ "sql": "SELECT * FROM 'regional/topic'",
+ "actions": [],
+ },
+ )
+ assert policy[0] == 200
+ assert rule[0] == 200
+ finally:
+ iot_module.reset()
+ iot_module.broker_reset()
+
+ asyncio.run(_run())
+
+
+def test_iot_broker_publish_and_retained_messages_are_region_isolated():
+ reset()
+
+ async def _run():
+ account_id = "123456789012"
+ east_received = []
+ west_received = []
+
+ async def east_callback(topic, payload, qos):
+ east_received.append((topic, payload, qos))
+
+ async def west_callback(topic, payload, qos):
+ west_received.append((topic, payload, qos))
+
+ await broker_subscribe(
+ account_id,
+ "us-east-1",
+ "sensors/temp",
+ east_callback,
+ )
+ await broker_subscribe(
+ account_id,
+ "us-west-2",
+ "sensors/temp",
+ west_callback,
+ )
+ await broker_publish(
+ account_id,
+ "us-east-1",
+ "sensors/temp",
+ b"21C",
+ retain=True,
+ )
+
+ assert east_received == [("sensors/temp", b"21C", 0)]
+ assert west_received == []
+
+ east_retained = []
+ west_retained = []
+
+ async def east_retained_callback(topic, payload, qos):
+ east_retained.append((topic, payload, qos))
+
+ async def west_retained_callback(topic, payload, qos):
+ west_retained.append((topic, payload, qos))
+
+ await broker_subscribe(
+ account_id,
+ "us-east-1",
+ "sensors/temp",
+ east_retained_callback,
+ )
+ await broker_subscribe(
+ account_id,
+ "us-west-2",
+ "sensors/temp",
+ west_retained_callback,
+ )
+
+ assert east_retained == [("sensors/temp", b"21C", 0)]
+ assert west_retained == []
+
+ asyncio.run(_run())
+ reset()
+
+
[email protected]("wildcard_region", ["+", "#"])
+def test_iot_broker_region_wildcards_cannot_bypass_isolation(
+ wildcard_region,
+):
+ reset()
+
+ async def _run():
+ account_id = "123456789012"
+ live_received = []
+ retained_received = []
+
+ async def live_callback(topic, payload, qos):
+ live_received.append((topic, payload, qos))
+
+ async def retained_callback(topic, payload, qos):
+ retained_received.append((topic, payload, qos))
+
+ await broker_subscribe(
+ account_id,
+ wildcard_region,
+ "sensors/temp",
+ live_callback,
+ )
+ await broker_publish(
+ account_id,
+ "us-east-1",
+ "sensors/temp",
+ b"east",
+ retain=True,
+ )
+ await broker_subscribe(
+ account_id,
+ wildcard_region,
+ "sensors/temp",
+ retained_callback,
+ )
+
+ assert live_received == []
+ assert retained_received == []
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_iot_broker_persistent_sessions_are_region_isolated():
+ reset()
+
+ async def _run():
+ account_id = "123456789012"
+ client_id = "shared-regional-client"
+ connect = _build_connect_body(
+ client_id=client_id, clean_session=False
+ )
+
+ east_send, _ = _mock_send()
+ east_session = _WSSession(
+ east_send, account_id, region="us-east-1"
+ )
+ await east_session.handle_packet(PKT_CONNECT, 0, connect)
+ await east_session.handle_packet(
+ PKT_SUBSCRIBE,
+ 0x02,
+ _build_subscribe_body(1, [("events/#", 1)]),
+ )
+ await east_session.handle_packet(PKT_DISCONNECT, 0, b"")
+ await east_session.cleanup()
+
+ west_send, west_sent = _mock_send()
+ west_session = _WSSession(
+ west_send, account_id, region="us-west-2"
+ )
+ await west_session.handle_packet(PKT_CONNECT, 0, connect)
+
+ session_present, return_code = _parse_connack(west_sent)
+ assert session_present is False
+ assert return_code == 0
+ assert (
+ account_id,
+ "us-east-1",
+ client_id,
+ ) in _persistent_sessions
+ assert (
+ account_id,
+ "us-west-2",
+ client_id,
+ ) in _persistent_sessions
+
+ await west_session.cleanup()
+ await broker_publish(
+ account_id,
+ "us-east-1",
+ "events/one",
+ b"east-only",
+ qos=1,
+ )
+ east_state = _persistent_sessions[
+ (account_id, "us-east-1", client_id)
+ ]
+ west_state = _persistent_sessions[
+ (account_id, "us-west-2", client_id)
+ ]
+ assert east_state.queued_messages == [
+ ("events/one", b"east-only", 1)
+ ]
+ assert west_state.queued_messages == []
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_iot_topic_rules_and_basic_ingest_use_publish_region(monkeypatch):
+ from ministack.services import iot as iot_module
+
+ reset()
+ iot_module._topic_rules.clear()
+ account_id = "123456789012"
+ east_rule = {
+ "ruleName": "regional_rule",
+ "sql": "SELECT * FROM 'sensors/#'",
+ "ruleDisabled": False,
+ "actions": [],
+ }
+ west_rule = {
+ **east_rule,
+ "sql": "SELECT * FROM 'west/#'",
+ "description": "west",
+ }
+ iot_module._topic_rules.set_scoped(
+ account_id, "us-east-1", "regional_rule", east_rule
+ )
+ iot_module._topic_rules.set_scoped(
+ account_id, "us-west-2", "regional_rule", west_rule
+ )
+ dispatched = []
+
+ def _capture_rule_action(dispatched_account_id, rule, payload):
+ dispatched.append((dispatched_account_id, rule, payload))
+
+ monkeypatch.setattr(
+ iot_module, "_run_rule_actions", _capture_rule_action
+ )
+
+ async def _run():
+ await broker_publish(
+ account_id,
+ "us-east-1",
+ "sensors/temperature",
+ b'{"value": 21}',
+ )
+ assert dispatched == [
+ (account_id, east_rule, b'{"value": 21}')
+ ]
+
+ dispatched.clear()
+ await broker_publish(
+ account_id,
+ "us-west-2",
+ "$aws/rules/regional_rule",
+ b'{"value": 22}',
+ )
+ assert dispatched == [
+ (account_id, west_rule, b'{"value": 22}')
+ ]
+
+ try:
+ asyncio.run(_run())
+ finally:
+ iot_module._topic_rules.clear()
+ reset()
+
def _build_connect_body(
client_id="test",
@@ -1089,7 +1459,11 @@ def test_clean_session_1_discards_prior_state():
await session1.cleanup()
# Verify persistent session exists
- assert ("123456789012", "device2") in _persistent_sessions
+ assert (
+ "123456789012",
+ _TEST_REGION,
+ "device2",
+ ) in _persistent_sessions
# Second connection: cleanSession=1 — should discard prior state
send2, sent2 = _mock_send()
@@ -1103,7 +1477,11 @@ def test_clean_session_1_discards_prior_state():
assert return_code == 0
# Verify persistent session was discarded
- assert ("123456789012", "device2") not in _persistent_sessions
+ assert (
+ "123456789012",
+ _TEST_REGION,
+ "device2",
+ ) not in _persistent_sessions
# Publish to the old subscription topic — should NOT be delivered
await publish("123456789012", "alerts/fire", b"alarm", qos=1)
@@ -1147,7 +1525,9 @@ def test_offline_qos1_messages_queued_and_delivered_on_reconnect():
await publish("123456789012", "data/stream", b"msg3", qos=1)
# Verify messages are queued
- ps = _persistent_sessions.get(("123456789012", "device3"))
+ ps = _persistent_sessions.get(
+ ("123456789012", _TEST_REGION, "device3")
+ )
assert ps is not None
assert len(ps.queued_messages) == 3
@@ -1202,7 +1582,9 @@ def test_qos0_messages_not_queued_for_offline_sessions():
await publish("123456789012", "events/log", b"info2", qos=0)
# Verify no messages queued (QoS 0 not queued)
- ps = _persistent_sessions.get(("123456789012", "device4"))
+ ps = _persistent_sessions.get(
+ ("123456789012", _TEST_REGION, "device4")
+ )
assert ps is not None
assert len(ps.queued_messages) == 0
@@ -1234,7 +1616,9 @@ def test_queue_bounded_to_1000_messages():
await publish("123456789012", "bulk/data", f"msg{i}".encode(), qos=1)
# Verify queue is bounded to 1000
- ps = _persistent_sessions.get(("123456789012", "device5"))
+ ps = _persistent_sessions.get(
+ ("123456789012", _TEST_REGION, "device5")
+ )
assert ps is not None
assert len(ps.queued_messages) == 1000
@@ -1268,7 +1652,9 @@ def test_expired_session_not_restored():
await session1.cleanup()
# Manually expire the session by setting created_at far in the past
- ps = _persistent_sessions.get(("123456789012", "device6"))
+ ps = _persistent_sessions.get(
+ ("123456789012", _TEST_REGION, "device6")
+ )
assert ps is not None
ps.created_at = time.time() - 7200 # 2 hours ago (default expiry is 1 hour)
@@ -1334,7 +1720,7 @@ def test_wildcard_subscription_persisted_and_restored():
def test_different_accounts_sessions_isolated():
- """Persistent sessions are scoped by (account_id, client_id)."""
+ """Persistent sessions are scoped by account, region, and client ID."""
reset()
async def _run():
diff --git a/tests/test_iot_data.py b/tests/test_iot_data.py
index 5ec40294..17283324 100644
--- a/tests/test_iot_data.py
+++ b/tests/test_iot_data.py
@@ -24,7 +24,6 @@ from urllib.parse import quote, urlparse
import pytest
from botocore.exceptions import ClientError
-
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
@@ -118,7 +117,6 @@ import asyncio # noqa: E402
import websockets # noqa: E402
-
# Minimal MQTT 3.1.1 codec for the test client.
@@ -186,14 +184,30 @@ def _parse_packet(buf: bytes) -> tuple[int, int, bytes, int] | None:
async def _ws_subscribe_and_collect(
ws_url: str, topic: str, ready_event: threading.Event, received: list, stop: threading.Event
):
+ def _record_publish(msg) -> int | None:
+ buf = msg if isinstance(msg, (bytes, bytearray)) else msg.encode("latin-1")
+ parsed = _parse_packet(bytes(buf))
+ if not parsed:
+ return None
+ ptype, _flags, body, _ = parsed
+ if ptype == 3: # PUBLISH
+ topic_len = struct.unpack_from("!H", body, 0)[0]
+ delivered_topic = body[2:2 + topic_len].decode("utf-8")
+ payload = body[2 + topic_len:]
+ received.append((delivered_topic, payload))
+ return ptype
+
async with websockets.connect(ws_url, subprotocols=["mqtt"]) as ws:
await ws.send(_make_connect("test-client"))
# Wait for CONNACK
await asyncio.wait_for(ws.recv(), timeout=2.0)
# Subscribe
await ws.send(_make_subscribe(packet_id=1, topic=topic, qos=0))
- # Wait for SUBACK
- await asyncio.wait_for(ws.recv(), timeout=2.0)
+ # Retained PUBLISH frames may precede SUBACK in the in-process broker.
+ while True:
+ msg = await asyncio.wait_for(ws.recv(), timeout=2.0)
+ if _record_publish(msg) == 9: # SUBACK
+ break
ready_event.set()
# Collect PUBLISH frames until stop or timeout.
@@ -203,16 +217,7 @@ async def _ws_subscribe_and_collect(
msg = await asyncio.wait_for(ws.recv(), timeout=0.5)
except asyncio.TimeoutError:
continue
- buf = msg if isinstance(msg, (bytes, bytearray)) else msg.encode("latin-1")
- parsed = _parse_packet(bytes(buf))
- if not parsed:
- continue
- ptype, _flags, body, _ = parsed
- if ptype == 3: # PUBLISH
- topic_len = struct.unpack_from("!H", body, 0)[0]
- t = body[2:2 + topic_len].decode("utf-8")
- payload = body[2 + topic_len:]
- received.append((t, payload))
+ _record_publish(msg)
def test_iot_lambda_publishes_browser_subscribes_e2e(iot_data_client):
@@ -254,6 +259,155 @@ def test_iot_lambda_publishes_browser_subscribes_e2e(iot_data_client):
assert delivered_payload == payload
+def test_iot_ws_publish_isolated_between_regions():
+ """The same account and topic must remain isolated by IoT data region."""
+ import boto3
+ from botocore.config import Config
+
+ topic = _unique("regional/sensor")
+ parsed = urlparse(ENDPOINT)
+ ws_host = parsed.hostname or "localhost"
+ ws_port = parsed.port or 4566
+
+ def _ws_url(region):
+ credential = quote(
+ f"test/20260726/{region}/iotdevicegateway/aws4_request",
+ safe="",
+ )
+ return (
+ f"ws://prefix-ats.iot.{region}.{ws_host}:{ws_port}/mqtt"
+ f"?X-Amz-Credential={credential}"
+ )
+
+ east_ready = threading.Event()
+ west_ready = threading.Event()
+ stop = threading.Event()
+ east_received = []
+ west_received = []
+
+ east_thread = threading.Thread(
+ target=lambda: asyncio.run(_ws_subscribe_and_collect(
+ _ws_url("us-east-1"),
+ topic,
+ east_ready,
+ east_received,
+ stop,
+ )),
+ daemon=True,
+ )
+ west_thread = threading.Thread(
+ target=lambda: asyncio.run(_ws_subscribe_and_collect(
+ _ws_url("us-west-2"),
+ topic,
+ west_ready,
+ west_received,
+ stop,
+ )),
+ daemon=True,
+ )
+ east_thread.start()
+ west_thread.start()
+ assert east_ready.wait(timeout=5)
+ assert west_ready.wait(timeout=5)
+
+ east_client = boto3.client(
+ "iot-data",
+ endpoint_url=ENDPOINT,
+ aws_access_key_id="test",
+ aws_secret_access_key="test",
+ region_name="us-east-1",
+ config=Config(retries={"mode": "standard"}),
+ )
+ east_client.publish(topic=topic, payload=b"east-only")
+
+ deadline = time.time() + 5
+ while time.time() < deadline and not east_received:
+ time.sleep(0.05)
+ time.sleep(0.6)
+ stop.set()
+ east_thread.join(timeout=2)
+ west_thread.join(timeout=2)
+
+ assert east_received == [(topic, b"east-only")]
+ assert west_received == []
+
+
[email protected]("wildcard_region", ["+", "#"])
+def test_iot_ws_credential_region_wildcards_cannot_bypass_isolation(
+ wildcard_region,
+):
+ """Credential-region wildcards cannot receive live or retained messages."""
+ import boto3
+ from botocore.config import Config
+
+ topic = _unique("wildcard-region/sensor")
+ parsed = urlparse(ENDPOINT)
+ ws_host = parsed.hostname or "localhost"
+ ws_port = parsed.port or 4566
+ credential = quote(
+ (
+ "test/20260726/"
+ f"{wildcard_region}/iotdevicegateway/aws4_request"
+ ),
+ safe="",
+ )
+ ws_url = (
+ f"ws://prefix-ats.iot.us-east-1.{ws_host}:{ws_port}/mqtt"
+ f"?X-Amz-Credential={credential}"
+ )
+ live_ready = threading.Event()
+ live_stop = threading.Event()
+ live_received = []
+
+ live_thread = threading.Thread(
+ target=lambda: asyncio.run(_ws_subscribe_and_collect(
+ ws_url,
+ topic,
+ live_ready,
+ live_received,
+ live_stop,
+ )),
+ daemon=True,
+ )
+ live_thread.start()
+ assert live_ready.wait(timeout=5)
+
+ east_client = boto3.client(
+ "iot-data",
+ endpoint_url=ENDPOINT,
+ aws_access_key_id="test",
+ aws_secret_access_key="test",
+ region_name="us-east-1",
+ config=Config(retries={"mode": "standard"}),
+ )
+ east_client.publish(topic=topic, payload=b"east", retain=True)
+
+ time.sleep(0.6)
+ live_stop.set()
+ live_thread.join(timeout=2)
+ assert live_received == []
+
+ retained_ready = threading.Event()
+ retained_stop = threading.Event()
+ retained_received = []
+ retained_thread = threading.Thread(
+ target=lambda: asyncio.run(_ws_subscribe_and_collect(
+ ws_url,
+ topic,
+ retained_ready,
+ retained_received,
+ retained_stop,
+ )),
+ daemon=True,
+ )
+ retained_thread.start()
+ assert retained_ready.wait(timeout=5)
+ time.sleep(0.6)
+ retained_stop.set()
+ retained_thread.join(timeout=2)
+ assert retained_received == []
+
+
def test_iot_ws_topic_isolation_between_accounts(iot_data_client):
"""A subscriber in account A must NOT see a publish from account B.
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index a45d08c0..8cf7296a 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -514,12 +514,11 @@ def test_save_dict_includes_sibling_imported_modules():
dropped. The fallback through `sys.modules` is the fix."""
import sys as _sys
- from ministack.app import _build_persistence_save_dict, _loaded_modules
-
# Force-import appsync_events the way appsync.py does it — a plain
# sibling import that bypasses `_get_module` and therefore does NOT
# populate `_loaded_modules`.
import ministack.services.appsync_events # noqa: F401
+ from ministack.app import _build_persistence_save_dict, _loaded_modules
# Simulate the bug condition: module is in sys.modules but absent
# from _loaded_modules.
@@ -2347,6 +2346,198 @@ def test_default_state_format_version_stays_v2_and_refuses_newer(monkeypatch, tm
assert persistence.load_state("future") is None
+def test_iot_legacy_state_migrates_resource_and_retained_regions():
+ import base64
+
+ from ministack.core.responses import (
+ AccountScopedDict,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import iot
+
+ account_id = "123456789012"
+ boot_region = "us-east-1"
+ resource_region = "us-west-2"
+ resource_name = "legacy-regional"
+
+ def legacy_store(value):
+ store = AccountScopedDict()
+ store._data[(account_id, resource_name)] = value
+ return store
+
+ legacy_state = {
+ "things": legacy_store({
+ "thingName": resource_name,
+ "thingArn": (
+ f"arn:aws:iot:{resource_region}:{account_id}:"
+ f"thing/{resource_name}"
+ ),
+ }),
+ "certificates": legacy_store({
+ "certificateId": resource_name,
+ "certificateArn": (
+ f"arn:aws:iot:{resource_region}:{account_id}:"
+ f"cert/{resource_name}"
+ ),
+ }),
+ "policies": legacy_store({
+ "policyName": resource_name,
+ "policyArn": (
+ f"arn:aws:iot:{resource_region}:{account_id}:"
+ f"policy/{resource_name}"
+ ),
+ }),
+ "topic_rules": legacy_store({
+ "ruleName": resource_name,
+ "ruleArn": (
+ f"arn:aws:iot:{resource_region}:{account_id}:"
+ f"rule/{resource_name}"
+ ),
+ }),
+ "mqtt_broker": {
+ "retained": [{
+ "topic": f"{account_id}/sensors/temperature",
+ "payload": base64.b64encode(b"21C").decode("ascii"),
+ "qos": 1,
+ }],
+ },
+ }
+
+ set_request_account_id(account_id)
+ set_request_region(boot_region)
+ iot.reset()
+ iot.broker_reset()
+ try:
+ iot.restore_state(legacy_state)
+
+ for store in (
+ iot._things,
+ iot._certificates,
+ iot._policies,
+ iot._topic_rules,
+ ):
+ assert store.get_scoped(
+ account_id, resource_region, resource_name
+ ) is not None
+ assert store.get_scoped(
+ account_id, boot_region, resource_name
+ ) is None
+
+ retained_key = (
+ f"{account_id}/{boot_region}/sensors/temperature"
+ )
+ assert iot._retained[retained_key].payload == b"21C"
+ assert (
+ f"{account_id}/{resource_region}/sensors/temperature"
+ not in iot._retained
+ )
+ finally:
+ iot.reset()
+ iot.broker_reset()
+
+
+def test_iot_region_scoped_v3_state_is_idempotent(monkeypatch, tmp_path):
+ import base64
+ import json as _json
+
+ from ministack.core.responses import AccountRegionScopedDict
+
+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)
+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
+
+ account_id = "123456789012"
+ region = "us-west-2"
+ resource_name = "regional-resource"
+
+ def regional_store(value):
+ store = AccountRegionScopedDict()
+ store.set_scoped(account_id, region, resource_name, value)
+ return store
+
+ state = {
+ "things": regional_store({
+ "thingName": resource_name,
+ "thingArn": (
+ f"arn:aws:iot:{region}:{account_id}:thing/{resource_name}"
+ ),
+ }),
+ "certificates": regional_store({
+ "certificateId": resource_name,
+ "certificateArn": (
+ f"arn:aws:iot:{region}:{account_id}:cert/{resource_name}"
+ ),
+ }),
+ "policies": regional_store({
+ "policyName": resource_name,
+ "policyArn": (
+ f"arn:aws:iot:{region}:{account_id}:policy/{resource_name}"
+ ),
+ }),
+ "topic_rules": regional_store({
+ "ruleName": resource_name,
+ "ruleArn": (
+ f"arn:aws:iot:{region}:{account_id}:rule/{resource_name}"
+ ),
+ }),
+ "mqtt_broker": {
+ "region_scoped": True,
+ "retained": [{
+ "topic": f"{account_id}/{region}/sensors/temperature",
+ "payload": base64.b64encode(b"21C").decode("ascii"),
+ "qos": 1,
+ }],
+ },
+ }
+
+ persistence.save_state("iot", state)
+ first_snapshot = _json.loads((tmp_path / "iot.json").read_text())
+ assert first_snapshot["__ministack_format__"] == 3
+
+ loaded = persistence.load_state("iot")
+ assert loaded is not None
+ persistence.save_state("iot", loaded)
+ second_snapshot = _json.loads((tmp_path / "iot.json").read_text())
+
+ assert second_snapshot == first_snapshot
+
+
+def test_iot_region_scoped_state_is_rejected_by_v2_reader(
+ monkeypatch, tmp_path
+):
+ import json as _json
+
+ from ministack.core.responses import AccountRegionScopedDict
+
+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)
+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
+
+ things = AccountRegionScopedDict()
+ things.set_scoped(
+ "123456789012",
+ "us-west-2",
+ "regional-thing",
+ {
+ "thingName": "regional-thing",
+ "thingArn": (
+ "arn:aws:iot:us-west-2:123456789012:"
+ "thing/regional-thing"
+ ),
+ },
+ )
+ persistence.save_state("iot", {"things": things})
+
+ raw = _json.loads((tmp_path / "iot.json").read_text())
+ assert raw["__ministack_format__"] == 3
+ loaded = persistence.load_state("iot")["things"]
+ assert loaded.get_scoped(
+ "123456789012", "us-west-2", "regional-thing"
+ )["thingName"] == "regional-thing"
+
+ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})
+ assert persistence.load_state("iot") is None
+
+
def test_ecs_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path):
"""A rollback binary must reject ECS's regional schema instead of
accepting it as v2 and silently dropping every regional store."""