Skip to content

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

fix(iot): topic-rule WHERE evaluation, SQL functions, non-Lambda actions (#1380)

iot-rocket98e944791487
diff --git a/ministack/core/responses.py b/ministack/core/responses.py
index ad2c90b4..0b54a7ef 100644
--- a/ministack/core/responses.py
+++ b/ministack/core/responses.py
@@ -4,6 +4,7 @@ Handles XML responses (S3, SQS, SNS, IAM, STS, CloudWatch) and
JSON responses (DynamoDB, Lambda, SecretsManager, CloudWatch Logs).
"""
+import contextlib
import contextvars
import hashlib
import json
@@ -65,6 +66,25 @@ def get_region() -> str:
return _request_region.get()
+def request_scope(account_id: str, region: str):
+ """Pin the request-scoped account and region around a block that reaches
+ into another service's store.
+
+ Cross-service work that starts outside an HTTP request — a background poller,
+ an MQTT broker session, an event dispatcher — has no request scope of its own,
+ but the stores it writes to are scoped by these contextvars. Such a caller
+ knows the account and region it is acting for and pins them here.
+ """
+ account_token = _request_account_id.set(account_id)
+ region_token = _request_region.set(region)
+ try:
+ yield
+ finally:
+ _request_region.reset(region_token)
+ _request_account_id.reset(account_token)
+
+
class AccountScopedDict:
"""A dict-like container that namespaces keys by the current request's account ID.
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 8ae14baa..13372a2d 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -35,6 +35,7 @@ from __future__ import annotations
import asyncio
import base64
+import contextvars
import copy
import hashlib
import json
@@ -57,6 +58,7 @@ from ministack.core.responses import (
get_region,
json_response,
new_uuid,
+ request_scope,
)
from ministack.core.x509_utils import (
generate_ca,
@@ -216,6 +218,10 @@ def reset() -> None:
_policies.clear()
_topic_rules.clear()
_shadows.clear()
+ # The warn-once ledger is module state keyed on rule SQL that no longer
+ # exists, so a reset has to clear it or the next test to store the same rule
+ # gets no warning.
+ _warned_sql_funcs.clear()
_indexing_config.clear()
with _CA_LOCK:
_ca_cert_pem = None
@@ -1973,6 +1979,83 @@ _SELECT_ALIAS_RE = re.compile(
)
_SELECT_FUNC_RE = re.compile(r"^(?P<name>[A-Za-z_]\w*)\s*\((?P<args>.*)\)$", re.DOTALL)
_SELECT_ATTR_RE = re.compile(r"^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)*$")
+# A SQL string literal escapes an embedded quote by doubling it: 'it''s'.
+_SQL_STRING_RE = re.compile(r"^'(?:[^']|'')*'$")
+
+
+def _sql_string_value(expr: str) -> str | None:
+ """Return the value of a SQL string literal, or ``None`` when ``expr`` is not
+ one. A doubled ``''`` inside the literal is an escaped quote."""
+ if _SQL_STRING_RE.match(expr):
+ return expr[1:-1].replace("''", "'")
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Rule SQL type conversions
+# ---------------------------------------------------------------------------
+#
+# AWS specifies one conversion table for the whole rule SQL dialect, applied
+# whenever an operator or a function is handed a value of a type it does not
+# want: https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-data-types.html
+# These three helpers are that table. Every operator below coerces through
+# them, so a value of the wrong type resolves the same way wherever it turns up
+# rather than each operator inventing its own policy — the trap this replaces
+# was `regexp_matches(temp, '^2')` matching {"temp": 22} while `temp LIKE '2%'`
+# did not. ``None`` is the "no conversion" answer, i.e. AWS's Undefined.
+
+# The pattern AWS parses a string with when it wants a number, verbatim from the
+# conversion table.
+_SQL_NUMERIC_STRING_RE = re.compile(r"^-?\d+(\.\d+)?([eE]-?\d+)?$")
+
+
+def _sql_as_number(value) -> int | float | None:
+ """Convert to Int/Decimal: numbers pass through, a numeric-looking string
+ converts, and anything else — Boolean included, which AWS converts only
+ through an explicit cast() — is Undefined."""
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, (int, float)):
+ return value
+ if isinstance(value, str) and _SQL_NUMERIC_STRING_RE.match(value.strip()):
+ text = value.strip()
+ try:
+ return int(text)
+ except ValueError:
+ return float(text)
+ return None
+
+
+def _sql_as_string(value) -> str | None:
+ """Convert to String: an Int, Decimal, Boolean, Array or Object renders;
+ Null and Undefined do not, and stay Undefined."""
+ if value is _MISSING or value is None:
+ return None
+ if isinstance(value, str):
+ return value
+ if isinstance(value, bool):
+ # AWS renders a Boolean lowercase, the way JSON does — not Python's
+ # "True"/"False".
+ return "true" if value else "false"
+ if isinstance(value, (int, float)):
+ return str(value)
+ # Array and Object render as their JSON serialization.
+ return json.dumps(value, separators=(",", ":"))
+
+
+def _sql_as_bool(value) -> bool | None:
+ """Convert to Boolean: a Boolean passes through and the strings "true" and
+ "false" convert (case insensitive). Every other value, a number included, is
+ Undefined."""
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, str):
+ lowered = value.strip().lower()
+ if lowered == "true":
+ return True
+ if lowered == "false":
+ return False
+ return None
def _rule_select_clause(sql: str) -> str:
@@ -1994,6 +2077,20 @@ def _rule_select_clause(sql: str) -> str:
return proj.strip()
+def _rule_where_clause(sql: str) -> str:
+ """Extract the WHERE predicate of a rule SQL statement ("" when absent).
+
+ When a ``FROM '<topic>'`` clause is present the predicate is whatever
+ follows it; for the FROM-less Basic Ingest form the predicate follows the
+ projection directly.
+ """
+ sql = sql or ""
+ m = re.search(r"\bFROM\s+'[^']*'", sql, re.IGNORECASE)
+ tail = sql[m.end():] if m else sql
+ m = re.search(r"\bWHERE\s+(.+)$", tail, re.IGNORECASE | re.DOTALL)
+ return m.group(1).strip() if m else ""
+
+
def _split_select_items(clause: str) -> list[str]:
"""Split a SELECT (or function-argument) list on its top-level commas."""
items: list[str] = []
@@ -2062,7 +2159,42 @@ def _encode_base64(value, payload: bytes):
return base64.b64encode(raw).decode("ascii")
-def _eval_select_function(name: str, args: list[str], topic: str, payload: bytes, message):
+# Rule SQL functions this evaluator implements. AWS's function library is much
+# larger, and a rule using one of the others deploys on AWS, so the emulator
+# accepts them at rule creation rather than failing a working stack — but such a
+# call resolves to Undefined, which silently drops a SELECT field and never
+# satisfies a WHERE clause. Both ends therefore warn, so the misfire is visible
+# instead of looking like "the rule did not match".
+_IMPLEMENTED_SQL_FUNCS = frozenset({
+ "clientid",
+ "encode",
+ "isundefined",
+ "newuuid",
+ "regexp_matches",
+ "replace",
+ "timestamp",
+ "topic",
+})
+_warned_sql_funcs: set[str] = set()
+
+
+def _warn_unimplemented_sql_function(name: str) -> None:
+ """Warn once per function name — rule evaluation runs on every publish, so
+ an unconditional warning would flood the log for one broken rule."""
+ if name in _warned_sql_funcs:
+ return
+ _warned_sql_funcs.add(name)
+ logger.warning(
+ "Rule SQL function %s() is not implemented by MiniStack: it resolves to "
+ "Undefined, so its SELECT field is dropped and a WHERE clause over it "
+ "never matches",
+ name,
+ )
+
+
+def _eval_select_function(
+ name: str, args: list[str], topic: str, payload: bytes, message, client_id: str | None = None
+):
if name == "encode":
if len(args) != 2:
return _MISSING
@@ -2071,7 +2203,7 @@ def _eval_select_function(name: str, args: list[str], topic: str, payload: bytes
return _MISSING
# `encode(*, 'base64')` encodes the payload as published — the bytes
# never round-trip through a text decode.
- value = payload if source == "*" else _eval_select_expr(source, topic, payload, message)
+ value = payload if source == "*" else _eval_select_expr(source, topic, payload, message, client_id)
return _encode_base64(value, payload)
if name == "topic":
if not args:
@@ -2086,15 +2218,41 @@ def _eval_select_function(name: str, args: list[str], topic: str, payload: bytes
return segments[index - 1]
if name == "timestamp" and not args:
return int(time.time() * 1000)
+ if name == "isundefined":
+ if len(args) != 1:
+ return _MISSING
+ return _eval_select_expr(args[0], topic, payload, message, client_id) is _MISSING
+ if name == "newuuid" and not args:
+ return new_uuid()
+ if name == "replace":
+ if len(args) != 3:
+ return _MISSING
+ old, new = _sql_string_value(args[1].strip()), _sql_string_value(args[2].strip())
+ if old is None or new is None:
+ return _MISSING
+ value = _eval_select_expr(args[0], topic, payload, message, client_id)
+ if not isinstance(value, str):
+ # An Undefined (or non-string) source is Undefined on AWS.
+ return _MISSING
+ return value.replace(old, new)
+ if name == "clientid" and not args:
+ # HTTP publishes carry no MQTT client id — AWS resolves clientid() to
+ # Undefined there, so the field is omitted from the projection.
+ return client_id if client_id else _MISSING
+ # principal() and traceid() land here too: this publish path carries no
+ # certificate identity or trace id to report, so they warn like any other
+ # function the evaluator does not implement.
+ _warn_unimplemented_sql_function(name)
return _MISSING
-def _eval_select_expr(expr: str, topic: str, payload: bytes, message):
+def _eval_select_expr(expr: str, topic: str, payload: bytes, message, client_id: str | None = None):
expr = expr.strip()
if expr == "*":
return message
- if len(expr) >= 2 and expr[0] == "'" and expr[-1] == "'":
- return expr[1:-1]
+ literal = _sql_string_value(expr)
+ if literal is not None:
+ return literal
m = _SELECT_FUNC_RE.match(expr)
if m:
return _eval_select_function(
@@ -2103,6 +2261,7 @@ def _eval_select_expr(expr: str, topic: str, payload: bytes, message):
topic,
payload,
message,
+ client_id,
)
if _SELECT_ATTR_RE.match(expr):
return _resolve_attribute(message, expr)
@@ -2113,14 +2272,589 @@ def _eval_select_expr(expr: str, topic: str, payload: bytes, message):
try:
return float(expr)
except ValueError:
+ pass
+ # Last, because every form above is a single token and would otherwise be
+ # re-split: a parenthesised group or an arithmetic expression over them.
+ # Its scanners live with the WHERE parser below, which splits on the same
+ # quote/paren rules.
+ return _eval_sql_arithmetic(expr, topic, payload, message, client_id)
+
+
+# ---------------------------------------------------------------------------
+# Rule SQL WHERE evaluation
+# ---------------------------------------------------------------------------
+#
+# Grammar (validated at rule creation, so anything a stored rule carries is
+# evaluable): a boolean expression over leaf clauses, with AWS's precedence —
+# OR binds loosest, then AND, then NOT, and a parenthesised group overrides all
+# three. A predicate is one of
+# NOT <predicate>
+# <operand> <op> <operand> with op in = == <> != < > <= >=
+# <operand> [NOT] IN (<operand>, ...)
+# <operand> [NOT] LIKE '<pattern>' % matches a run, _ a single character
+# <operand> BETWEEN <operand> AND <operand>
+# <operand> IS [NOT] NULL
+# <operand> a boolean-valued attribute or call
+# regexp_matches(<operand>, '<regex>')
+# where an operand is a quoted string, a numeric literal, a JSON payload
+# attribute path, a SQL function call, or an arithmetic expression over those
+# (+ - * / %, the multiplicative three binding tighter, parentheses regrouping).
+#
+# Evaluation is three-valued — true, false, or Undefined — because AWS's is:
+# every operator here answers Undefined for an operand it cannot use, and only
+# NOT can tell that apart from false. `_eval_where` then fires the rule on true
+# alone, so an Undefined predicate fails closed however it was reached.
+
+_WHERE_OPERATORS = ("<>", "!=", "==", "<=", ">=", "=", "<", ">")
+_REGEXP_MATCHES_RE = re.compile(
+ r"regexp_matches\s*\(\s*(?P<expr>.+?)\s*,\s*'(?P<regex>[^']*)'\s*\)",
+ re.IGNORECASE | re.DOTALL,
+)
+
+
+def _top_level_indices(text: str) -> list[int] | None:
+ """Index every character of ``text`` that sits at parenthesis depth 0 and
+ outside a string literal — the only positions where a top-level token (a
+ boolean keyword, a comparison operator, a group delimiter) can start.
+
+ This is the single scanner the WHERE parser splits on; the helpers below
+ differ only in what they look for at those positions. Returns ``None`` when
+ the text is malformed — an unterminated literal or unbalanced parentheses —
+ so the caller rejects it rather than guessing at a grouping.
+ """
+ tops: list[int] = []
+ depth = 0
+ i = 0
+ n = len(text)
+ while i < n:
+ ch = text[i]
+ if ch == "'":
+ i += 1
+ # A doubled '' inside the literal is an escaped quote, not its end.
+ while i < n and not (text[i] == "'" and text[i + 1:i + 2] != "'"):
+ i += 2 if text[i] == "'" else 1
+ if i >= n:
+ return None
+ i += 1
+ continue
+ if ch == "(":
+ if depth == 0:
+ tops.append(i)
+ depth += 1
+ elif ch == ")":
+ depth -= 1
+ if depth < 0:
+ return None
+ if depth == 0:
+ tops.append(i)
+ elif depth == 0:
+ tops.append(i)
+ i += 1
+ return None if depth else tops
+
+
+def _is_keyword_at(text: str, index: int, keyword: str) -> bool:
+ """True when ``keyword`` starts at ``index`` as a standalone SQL word.
+
+ A keyword may abut a bracket instead of whitespace — ``(a = 1)AND(b = 2)``
+ and ``x IN('a')`` are both SQL AWS accepts — so a bracket counts as a word
+ boundary alongside whitespace.
+ """
+ end = index + len(keyword)
+ if text[index:end].upper() != keyword:
+ return False
+ before = text[index - 1] if index else " "
+ after = text[end] if end < len(text) else " "
+ return (before.isspace() or before == ")") and (after.isspace() or after == "(")
+
+
+def _split_where_terms(pred: str, keyword: str) -> list[str] | None:
+ """Split a WHERE predicate on its top-level ``AND`` / ``OR`` keywords.
+
+ A keyword inside a string literal or a parenthesised group is not a split
+ point, and neither is the ``AND`` belonging to a ``BETWEEN <lo> AND <hi>``.
+ Returns ``None`` when the predicate is malformed.
+ """
+ tops = _top_level_indices(pred)
+ if tops is None:
+ return None
+ parts: list[str] = []
+ start = 0
+ pending_between = 0
+ for i in tops:
+ if _is_keyword_at(pred, i, "BETWEEN"):
+ pending_between += 1
+ elif _is_keyword_at(pred, i, keyword):
+ if keyword == "AND" and pending_between:
+ pending_between -= 1
+ continue
+ parts.append(pred[start:i].strip())
+ start = i + len(keyword)
+ parts.append(pred[start:].strip())
+ return parts
+
+
+def _split_where_keyword(clause: str, keyword: str) -> tuple[str, str] | None:
+ """Split ``clause`` around its first top-level ``keyword``, or ``None`` when
+ the clause does not carry one (or is malformed)."""
+ tops = _top_level_indices(clause)
+ if tops is None:
+ return None
+ for i in tops:
+ if _is_keyword_at(clause, i, keyword):
+ return clause[:i].strip(), clause[i + len(keyword):].strip()
+ return None
+
+
+def _strip_where_group(pred: str) -> str | None:
+ """Return the body of ``pred`` when a single pair of parentheses wraps the
+ whole predicate, else ``None`` (``(a) AND (b)`` is not a wrapped group)."""
+ if not (pred.startswith("(") and pred.endswith(")")):
+ return None
+ # Everything a wrapping group encloses sits at depth 1 or deeper, so its own
+ # delimiters are the only characters left at top level.
+ if _top_level_indices(pred) != [0, len(pred) - 1]:
+ return None
+ return pred[1:-1].strip()
+
+
+# Arithmetic binds tighter than any comparison, so an operand is split on these
+# only after the comparison split has run. Multiplicative binds tighter than
+# additive; within a tier the split is left-associative.
+_ARITHMETIC_TIERS = (("+", "-"), ("*", "/", "%"))
+
+
+def _split_arithmetic(expr: str) -> tuple[str, str, str] | None:
+ """Split ``expr`` at its loosest-binding top-level arithmetic operator, or
+ ``None`` when it carries none (or is malformed).
+
+ Scanning each tier right to left makes the split left-associative: the last
+ top-level ``-`` in ``a - b - c`` is the root, so it groups as ``(a - b) - c``.
+ A ``+``/``-`` that opens the expression or follows another operator is a
+ sign rather than a binary operator — ``a * -5`` is a product, not a
+ difference — so it is not a split point.
+ """
+ tops = _top_level_indices(expr)
+ if tops is None:
+ return None
+ for tier in _ARITHMETIC_TIERS:
+ for i in reversed(tops):
+ if expr[i] not in tier:
+ continue
+ left = expr[:i].strip()
+ if not left or left[-1] in "+-*/%":
+ continue
+ return left, expr[i], expr[i + 1:].strip()
+ return None
+
+
+def _sql_arithmetic(op: str, left, right):
+ """Apply one arithmetic operator under AWS's operand rules.
+
+ https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-operators.html
+ ``+`` is overloaded: a String operand on either side makes it concatenation,
+ which is why it is settled before the numeric conversion. Everything else is
+ numeric, Int op Int stays Int, and an operand that will not convert leaves
+ the whole expression Undefined.
+ """
+ if op == "+" and (isinstance(left, str) or isinstance(right, str)):
+ parts = (_sql_as_string(left), _sql_as_string(right))
+ return _MISSING if None in parts else parts[0] + parts[1]
+ lnum, rnum = _sql_as_number(left), _sql_as_number(right)
+ if lnum is None or rnum is None:
+ return _MISSING
+ if op == "+":
+ return lnum + rnum
+ if op == "-":
+ return lnum - rnum
+ if op == "*":
+ return lnum * rnum
+ if rnum == 0:
+ # AWS does not document division by zero; Undefined is the answer that
+ # keeps a rule from firing on a value the emulator had to invent.
+ return _MISSING
+ if op == "%":
+ # SQL's remainder takes the sign of the dividend; Python's % takes the
+ # divisor's, so it needs correcting rather than using directly.
+ remainder = abs(lnum) % abs(rnum)
+ return -remainder if lnum < 0 else remainder
+ if isinstance(lnum, int) and isinstance(rnum, int):
+ # Int / Int is an Int on AWS. Python's // floors, so negative quotients
+ # need nudging back to the truncation SQL divides with.
+ quotient = lnum // rnum
+ return quotient + 1 if quotient < 0 and quotient * rnum != lnum else quotient
+ return lnum / rnum
+
+
+def _eval_sql_arithmetic(expr: str, topic: str, payload: bytes, message, client_id: str | None):
+ """Evaluate a parenthesised group or an arithmetic expression, or return the
+ missing-value sentinel when ``expr`` is neither."""
+ inner = _strip_where_group(expr)
+ if inner is not None:
+ return _eval_select_expr(inner, topic, payload, message, client_id)
+ parts = _split_arithmetic(expr)
+ if parts is None:
+ return _MISSING
+ left_expr, op, right_expr = parts
+ left = _eval_select_expr(left_expr, topic, payload, message, client_id)
+ right = _eval_select_expr(right_expr, topic, payload, message, client_id)
+ if left is _MISSING or right is _MISSING:
+ return _MISSING
+ return _sql_arithmetic(op, left, right)
+
+
+def _split_comparison(clause: str) -> tuple[str, str, str] | None:
+ """Split ``<left> <op> <right>`` at the first top-level comparison operator."""
+ tops = _top_level_indices(clause)
+ if tops is None:
+ return None
+ for i in tops:
+ for op in _WHERE_OPERATORS:
+ if clause.startswith(op, i):
+ return clause[:i].strip(), op, clause[i + len(op):].strip()
+ return None
+
+
+def _strip_trailing_not(expr: str) -> tuple[str, bool]:
+ """Peel the ``NOT`` off the left operand of ``NOT IN`` / ``NOT LIKE``."""
+ m = re.fullmatch(r"(?P<expr>.*?)\s+NOT", expr.strip(), re.IGNORECASE | re.DOTALL)
+ if m:
+ return m.group("expr").strip(), True
+ return expr.strip(), False
+
+
+def _like_to_regex(pattern: str) -> str:
+ """Translate a SQL LIKE pattern to a regex: ``%`` matches any run of
+ characters, ``_`` exactly one, everything else is literal."""
+ return "".join(
+ ".*" if ch == "%" else "." if ch == "_" else re.escape(ch) for ch in pattern
+ )
+
+
+def _valid_where_operand(expr: str) -> bool:
+ """A WHERE operand `_eval_select_expr` can resolve: string literal, number,
+ payload attribute path, function call, or arithmetic over those.
+
+ The order mirrors the evaluator's, so validation accepts exactly what
+ evaluation resolves.
+ """
+ expr = expr.strip()
+ if not expr:
+ return False
+ if _sql_string_value(expr) is not None:
+ return True
+ if _SELECT_ATTR_RE.match(expr) or _SELECT_FUNC_RE.match(expr):
+ return True
+ try:
+ float(expr)
+ return True
+ except ValueError:
+ pass
+ inner = _strip_where_group(expr)
+ if inner is not None:
+ return _valid_where_operand(inner)
+ parts = _split_arithmetic(expr)
+ return parts is not None and _valid_where_operand(parts[0]) and _valid_where_operand(parts[2])
+
+
+def _parse_where_leaf(clause: str) -> tuple | None:
+ """Parse one leaf clause of the grammar above into a node, or ``None``."""
+ m = _REGEXP_MATCHES_RE.fullmatch(clause)
+ if m:
+ if not _valid_where_operand(m.group("expr")):
+ return None
+ try:
+ re.compile(m.group("regex"))
+ except re.error:
+ return None
+ return ("regexp", m.group("expr"), m.group("regex"))
+
+ parts = _split_where_keyword(clause, "IS")
+ if parts is not None:
+ left, rest = parts
+ negated = re.fullmatch(r"NOT\s+NULL", rest, re.IGNORECASE) is not None
+ if not negated and rest.upper() != "NULL":
+ return None
+ return ("isnull", left, negated) if _valid_where_operand(left) else None
+
+ parts = _split_where_keyword(clause, "BETWEEN")
+ if parts is not None:
+ left, rest = parts
+ bounds = _split_where_keyword(rest, "AND")
+ if bounds is None:
+ return None
+ low, high = bounds
+ if not all(_valid_where_operand(o) for o in (left, low, high)):
+ return None
+ return ("between", left, low, high)
+
+ parts = _split_where_keyword(clause, "IN")
+ if parts is not None:
+ left, negated = _strip_trailing_not(parts[0])
+ inner = _strip_where_group(parts[1])
+ if inner is None or not _valid_where_operand(left):
+ return None
+ options = _split_select_items(inner)
+ if not options or not all(_valid_where_operand(o) for o in options):
+ return None
+ return ("in", left, tuple(options), negated)
+
+ parts = _split_where_keyword(clause, "LIKE")
+ if parts is not None:
+ left, negated = _strip_trailing_not(parts[0])
+ pattern = _sql_string_value(parts[1])
+ if pattern is None or not _valid_where_operand(left):
+ return None
+ return ("like", left, _like_to_regex(pattern), negated)
+
+ cmp_parts = _split_comparison(clause)
+ if cmp_parts is not None:
+ left, op, right = cmp_parts
+ if not (_valid_where_operand(left) and _valid_where_operand(right)):
+ return None
+ return ("cmp", left, op, right)
+
+ # A bare operand is a leaf in its own right: AWS accepts `WHERE enabled` and
+ # `WHERE isUndefined(x)`, each holding only when it resolves to boolean true.
+ clause = clause.strip()
+ if _SELECT_ATTR_RE.match(clause) or _SELECT_FUNC_RE.match(clause):
+ return ("truth", clause)
+ return None
+
+
+def _parse_where(pred: str) -> tuple | None:
+ """Parse a WHERE predicate into an evaluable node tree, or ``None`` if
+ unparseable.
+
+ Nodes are ``("or", [...])`` / ``("and", [...])`` over leaves. OR is split
+ first, so it binds loosest — ``a = 1 AND b = 2 OR c = 3`` groups as
+ ``(a = 1 AND b = 2) OR c = 3``, as on AWS.
+ """
+ pred = (pred or "").strip()
+ if not pred:
+ return None
+ for keyword, kind in (("OR", "or"), ("AND", "and")):
+ terms = _split_where_terms(pred, keyword)
+ if terms is None:
+ return None
+ if len(terms) > 1:
+ nodes: list[tuple] = []
+ for term in terms:
+ node = _parse_where(term)
+ if node is None:
+ return None
+ nodes.append(node)
+ return (kind, tuple(nodes))
+ # NOT binds tighter than AND and looser than any comparison, so it is peeled
+ # after the boolean splits and before the group and leaf forms. It may abut
+ # its operand's bracket — `NOT(a = 1)` is SQL AWS accepts.
+ if re.match(r"NOT\b", pred, re.IGNORECASE):
+ node = _parse_where(pred[3:].strip())
+ return ("not", node) if node is not None else None
+ inner = _strip_where_group(pred)
+ if inner is not None:
+ return _parse_where(inner)
+ return _parse_where_leaf(pred)
+
+
+def _where_values_equal(left, right) -> bool:
+ # Keep JSON booleans distinct from 0/1 (Python would conflate them).
+ if isinstance(left, bool) or isinstance(right, bool):
+ return isinstance(left, bool) and isinstance(right, bool) and left is right
+ return left == right
+
+
+def _eval_where_node(node: tuple, topic: str, payload: bytes, message, client_id: str | None):
+ """Evaluate one parsed WHERE node to true, false, or Undefined.
+
+ Undefined is what each AWS operator answers for an operand it cannot use,
+ and it composes as SQL's three-valued logic: it loses to a true OR sibling
+ and to a false AND sibling, survives every other combination, and is the one
+ value NOT cannot flip. `_eval_where` turns whatever reaches the top into a
+ fire/do-not-fire decision.
+ """
+ kind = node[0]
+ if kind == "or":
+ undefined = False
+ for child in node[1]:
+ result = _eval_where_node(child, topic, payload, message, client_id)
+ if result is True:
+ return True
+ undefined = undefined or result is _MISSING
+ return _MISSING if undefined else False
+ if kind == "and":
+ undefined = False
+ for child in node[1]:
+ result = _eval_where_node(child, topic, payload, message, client_id)
+ if result is False:
+ return False
+ undefined = undefined or result is _MISSING
+ return _MISSING if undefined else True
+ if kind == "not":
+ inner = _eval_where_node(node[1], topic, payload, message, client_id)
+ # NOT Undefined is Undefined, so a predicate over an absent attribute
+ # still fails closed once negated.
+ return _MISSING if inner is _MISSING else not inner
+ if kind == "regexp":
+ text = _sql_as_string(_eval_select_expr(node[1], topic, payload, message, client_id))
+ return _MISSING if text is None else re.search(node[2], text) is not None
+ if kind == "truth":
+ # A bare operand is a predicate only if it converts to a Boolean: true,
+ # false, or the strings spelling them. A number does not, on AWS.
+ value = _sql_as_bool(_eval_select_expr(node[1], topic, payload, message, client_id))
+ return _MISSING if value is None else value
+ if kind == "isnull":
+ value = _eval_select_expr(node[1], topic, payload, message, client_id)
+ if value is _MISSING:
+ # Undefined is not NULL, and it is not "not NULL" either.
+ return _MISSING
+ return value is not None if node[2] else value is None
+ if kind == "between":
+ bounds = [
+ _sql_as_number(_eval_select_expr(expr, topic, payload, message, client_id))
+ for expr in node[1:]
+ ]
+ if any(bound is None for bound in bounds):
+ return _MISSING
+ value, low, high = bounds
+ return low <= value <= high
+ if kind == "in":
+ value = _eval_select_expr(node[1], topic, payload, message, client_id)
+ if value is _MISSING:
+ return _MISSING
+ hit = any(
+ _where_values_equal(value, _eval_select_expr(opt, topic, payload, message, client_id))
+ for opt in node[2]
+ )
+ return not hit if node[3] else hit
+ if kind == "like":
+ # LIKE wants a String, so a number or a boolean converts to one rather
+ # than dropping out — the same conversion regexp_matches() applies.
+ text = _sql_as_string(_eval_select_expr(node[1], topic, payload, message, client_id))
+ if text is None:
+ return _MISSING
+ hit = re.fullmatch(node[2], text) is not None
+ return not hit if node[3] else hit
+
+ _, left_expr, op, right_expr = node
+ left = _eval_select_expr(left_expr, topic, payload, message, client_id)
+ right = _eval_select_expr(right_expr, topic, payload, message, client_id)
+ if left is _MISSING or right is _MISSING:
+ return _MISSING
+ if op in ("=", "=="):
+ # Equality does not convert: on AWS a mismatched pair is simply unequal.
+ return _where_values_equal(left, right)
+ if op in ("<>", "!="):
+ return not _where_values_equal(left, right)
+ lnum, rnum = _sql_as_number(left), _sql_as_number(right)
+ if lnum is None or rnum is None:
+ # Ordering converts both sides to a number first, and is Undefined for
+ # an operand that will not convert.
return _MISSING
+ if op == "<":
+ return lnum < rnum
+ if op == ">":
+ return lnum > rnum
+ if op == "<=":
+ return lnum <= rnum
+ return lnum >= rnum
+
+
+def _eval_where(pred: str, topic: str, payload: bytes, message, client_id: str | None = None) -> bool:
+ """Evaluate a WHERE predicate against one publish.
+
+ AWS-faithful failure mode: a clause referencing an attribute missing from
+ the payload evaluates to Undefined, and only a predicate that comes out
+ *true* fires the rule — so Undefined does not fire, and neither does its
+ negation (fail closed). Unparseable predicates are rejected at rule
+ creation; one that slips through (legacy stored state) also fails closed.
+ """
+ node = _parse_where(pred)
+ if node is None:
+ _broker_logger.warning(
+ "IoT rule WHERE clause %r cannot be parsed — no publish will ever "
+ "match it (fail closed)",
+ pred,
+ )
+ return False
+ return _eval_where_node(node, topic, payload, message, client_id) is True
+
+
+class RuleSqlError(ValueError):
+ """Rule SQL the engine cannot evaluate, raised by `put_topic_rule`."""
+
+
+def _validate_rule_sql(sql: str) -> str | None:
+ """Return an error message when the rule SQL cannot be parsed, else None."""
+ sql = sql or ""
+ if not re.match(r"\s*SELECT\s+\S", sql, re.IGNORECASE):
+ return "Rule SQL must be of the form SELECT ... [FROM '<topic>'] [WHERE ...]"
+ if re.search(r"\bFROM\b", sql, re.IGNORECASE) and not re.search(
+ r"\bFROM\s+'[^']*'", sql, re.IGNORECASE
+ ):
+ return "FROM clause must name a topic filter in single quotes"
+ pred = _rule_where_clause(sql)
+ if pred and _parse_where(pred) is None:
+ return f"Unsupported WHERE clause: {pred}"
+ return None
+
+
+_SQL_LITERAL_RE = re.compile(r"'(?:[^']|'')*'")
+_SQL_CALL_RE = re.compile(r"\b([A-Za-z_]\w*)\s*\(")
+# Words that may precede a bracket without opening a call: `WHERE (a = 1)`,
+# `x IN ('a', 'b')` and `AND (b = 2)` all put a keyword where the pattern above
+# looks for a function name, and warning about a missing where()/in()/and() is
+# worse than saying nothing.
+_SQL_KEYWORDS = frozenset({
+ "and",
+ "as",
+ "between",
+ "from",
+ "in",
+ "is",
+ "like",
+ "not",
+ "null",
+ "or",
+ "select",
+ "where",
+})
+
+
+def _unimplemented_sql_functions(sql: str) -> list[str]:
+ """Names of the SQL functions ``sql`` calls that this evaluator does not
+ implement. String literals are blanked first so text inside them cannot look
+ like a call, and SQL's own keywords are discounted so a bracketed group or
+ value list is not read as one."""
+ stripped = _SQL_LITERAL_RE.sub("''", sql or "")
+ names = {m.group(1).lower() for m in _SQL_CALL_RE.finditer(stripped)}
+ return sorted(names - _IMPLEMENTED_SQL_FUNCS - _SQL_KEYWORDS)
def put_topic_rule(name: str, payload: dict, *, created_at: float | None = None) -> dict:
- """Store a topic rule from an API-shape (camelCase) ``TopicRulePayload``."""
+ """Store a topic rule from an API-shape (camelCase) ``TopicRulePayload``.
+
+ Raises `RuleSqlError` for SQL the engine cannot evaluate, so a rule that
+ would silently never fire cannot reach the store through any door — the IoT
+ API or the CloudFormation provisioner. SQL that only *calls* something the
+ evaluator lacks is stored (AWS accepts a larger function library than this
+ emulator implements, and rejecting it would fail a stack that deploys on
+ AWS) but warns, so the resulting misfire is visible.
+ """
+ sql = payload.get("sql", "")
+ error = _validate_rule_sql(sql)
+ if error:
+ raise RuleSqlError(error)
+ for func in _unimplemented_sql_functions(sql):
+ logger.warning(
+ "Topic rule %s calls %s(), which MiniStack does not implement: it "
+ "resolves to Undefined, so the rule will not match on it",
+ name,
+ func,
+ )
rule = {
"ruleName": name,
- "sql": payload.get("sql", ""),
+ "sql": sql,
"actions": payload.get("actions", []) or [],
"ruleDisabled": bool(payload.get("ruleDisabled", False)),
"awsIotSqlVersion": payload.get("awsIotSqlVersion", "2016-03-23"),
@@ -2164,14 +2898,20 @@ def _create_topic_rule(name: str, payload: dict) -> tuple:
)
if not payload.get("sql"):
return error_response_json("SqlParseException", "sql is required", 400)
- put_topic_rule(name, payload)
+ try:
+ put_topic_rule(name, payload)
+ except RuleSqlError as exc:
+ return error_response_json("SqlParseException", str(exc), 400)
return json_response({})
def _replace_topic_rule(name: str, payload: dict) -> tuple:
if name not in _topic_rules:
return _error_not_found("Rule", name)
- put_topic_rule(name, payload)
+ try:
+ put_topic_rule(name, payload)
+ except RuleSqlError as exc:
+ return error_response_json("SqlParseException", str(exc), 400)
return json_response({})
@@ -2568,10 +3308,27 @@ def _rule_message(payload: bytes):
return text
-def _rule_event(sql: str, topic: str, payload: bytes):
- """Project a publish payload through a rule's SELECT clause."""
+# Sentinel for "the caller has not decoded the payload yet" — distinct from
+# _MISSING, which is itself a legitimate decoded message (a non-UTF-8 payload).
+_UNDECODED = object()
+
+
+def _rule_event(
+ sql: str,
+ topic: str,
+ payload: bytes,
+ client_id: str | None = None,
+ message=_UNDECODED,
+):
+ """Project a publish payload through a rule's SELECT clause.
+
+ ``message`` lets a caller that already decoded the payload (the dispatch
+ path, which also needs it for the WHERE predicate) pass it in instead of
+ paying for a second JSON parse.
+ """
payload = payload or b""
- message = _rule_message(payload)
+ if message is _UNDECODED:
+ message = _rule_message(payload)
items = _split_select_items(_rule_select_clause(sql)) or ["*"]
if len(items) == 1:
@@ -2582,7 +3339,7 @@ def _rule_event(sql: str, topic: str, payload: bytes):
event: dict = {}
for item in items:
expr, alias = _split_select_alias(item)
- value = _eval_select_expr(expr, topic, payload, message)
+ value = _eval_select_expr(expr, topic, payload, message, client_id)
if value is _MISSING:
continue
if expr == "*" and alias is None:
@@ -2612,12 +3369,198 @@ def _dispatch_rule_to_lambda(
).start()
-def _run_rule_actions(
- account_id: str, region: str, rule: dict, payload: bytes, topic: str = ""
+# Depth guard for republish chains: rule A republishing onto a topic that rule
+# A (or a cycle of rules) matches again would recurse without bound. Real AWS
+# does not loop-protect either — such a rule is user error — but the emulator
+# must at least not crash, so the chain is cut and logged past this depth.
+_MAX_REPUBLISH_DEPTH = 8
+_republish_depth: contextvars.ContextVar[int] = contextvars.ContextVar(
+ "_iot_republish_depth", default=0
+)
+
+
+async def _dispatch_rule_republish(
+ account_id: str, region: str, rule_name: str, spec: dict, event
+) -> None:
+ target_topic = spec.get("topic") or ""
+ if not target_topic:
+ _broker_logger.warning(
+ "IoT rule %s: republish action has no topic — skipped", rule_name
+ )
+ return
+ depth = _republish_depth.get()
+ if depth >= _MAX_REPUBLISH_DEPTH:
+ _broker_logger.warning(
+ "IoT rule %s: republish depth limit (%d) reached — dropping republish to %r "
+ "(a rule republishing onto its own topic filter loops forever on AWS too)",
+ rule_name,
+ _MAX_REPUBLISH_DEPTH,
+ target_topic,
+ )
+ return
+ try:
+ qos = int(spec.get("qos") or 0)
+ except (TypeError, ValueError):
+ qos = 0
+ token = _republish_depth.set(depth + 1)
+ try:
+ await broker_publish(
+ account_id,
+ region,
+ target_topic,
+ json.dumps(event).encode("utf-8"),
+ qos=qos,
+ )
+ finally:
+ _republish_depth.reset(token)
+
+
+def _ddb_attribute_value(raw) -> dict:
+ """Map a projected value to a DynamoDB AttributeValue (dynamoDBv2 puts each
+ payload attribute in its own column)."""
+ if isinstance(raw, bool):
+ return {"BOOL": raw}
+ if isinstance(raw, (int, float)):
+ return {"N": str(raw)}
+ if raw is None:
+ return {"NULL": True}
+ if isinstance(raw, (dict, list)):
+ return {"S": json.dumps(raw)}
+ return {"S": str(raw)}
+
+
+def _dispatch_rule_dynamodb(account_id: str, region: str, rule_name: str, spec: dict, event) -> None:
+ from ministack.services import dynamodb as _dynamodb
+
+ table = (spec.get("putItem") or {}).get("tableName") or ""
+ if not table:
+ _broker_logger.warning(
+ "IoT rule %s: dynamoDBv2 action has no putItem.tableName — skipped", rule_name
+ )
+ return
+ if not isinstance(event, dict):
+ _broker_logger.warning(
+ "IoT rule %s: dynamoDBv2 action needs a JSON-object payload, got %s — skipped",
+ rule_name,
+ type(event).__name__,
+ )
+ return
+ item = {key: _ddb_attribute_value(value) for key, value in event.items()}
+ with request_scope(account_id, region):
+ status = _dynamodb._put_item({"TableName": table, "Item": item})[0]
+ if status >= 400:
+ # Raise rather than log: an undeliverable destination is precisely what
+ # the rule's errorAction exists to hear about, and a missing table is
+ # the failure that actually happens locally.
+ raise RuntimeError(
+ f"DynamoDB PutItem to {table} failed with status {status}"
+ )
+ _broker_logger.debug("IoT rule %s → DynamoDB %s", rule_name, table)
+
+
+def _dispatch_rule_sns(account_id: str, region: str, rule_name: str, spec: dict, event) -> None:
+ from ministack.services import sns as _sns
+
+ target = spec.get("targetArn") or ""
+ if not target:
+ _broker_logger.warning(
+ "IoT rule %s: sns action has no targetArn — skipped", rule_name
+ )
+ return
+ with request_scope(account_id, region):
+ # Through SNS's own internal publish, so the message record, the payload
+ # size limit and the FIFO rules are the ones every other producer gets.
+ result = _sns.publish_internal(target, json.dumps(event))
+ if result is None:
+ # As with DynamoDB above: a topic that is not there is an undeliverable
+ # destination, so it reaches the errorAction instead of a log line.
+ raise RuntimeError(f"SNS topic {target} not found")
+ _broker_logger.debug("IoT rule %s → SNS %s", rule_name, target)
+
+
+async def _dispatch_rule_action(
+ account_id: str, region: str, rule_name: str, action: dict, event
+) -> None:
+ """Dispatch one rule action, letting the target service's failure surface.
+
+ Rule actions and the rule's errorAction share the same shapes, so both go
+ through here.
+ """
+ lam = action.get("lambda")
+ if lam and lam.get("functionArn"):
+ _dispatch_rule_to_lambda(account_id, region, lam["functionArn"], event)
+ elif "republish" in action:
+ await _dispatch_rule_republish(
+ account_id, region, rule_name, action["republish"] or {}, event
+ )
+ elif "dynamoDBv2" in action:
+ _dispatch_rule_dynamodb(
+ account_id, region, rule_name, action["dynamoDBv2"] or {}, event
+ )
+ elif "sns" in action:
+ _dispatch_rule_sns(account_id, region, rule_name, action["sns"] or {}, event)
+ else:
+ _broker_logger.debug(
+ "IoT rule %s: unsupported action type %s — skipped",
+ rule_name,
+ next(iter(action), "?"),
+ )
+
+
+async def _dispatch_rule_error_action(
+ account_id: str,
+ region: str,
+ rule: dict,
+ topic: str,
+ payload: bytes,
+ client_id: str | None,
+ failures: list[dict],
+) -> None:
+ """Run the rule's errorAction, carrying AWS's error message document.
+
+ https://docs.aws.amazon.com/iot/latest/developerguide/rule-error-handling.html
+ """
+ error_action = rule.get("errorAction")
+ if not error_action:
+ return
+ rule_name = rule.get("ruleName", "")
+ error_event = {
+ "ruleName": rule_name,
+ "topic": topic,
+ # The emulator's publish path carries no CloudWatch trace id.
+ "cloudwatchTraceId": "",
+ "clientId": client_id or "",
+ "base64OriginalPayload": base64.b64encode(payload).decode("ascii"),
+ "failures": failures,
+ }
+ try:
+ await _dispatch_rule_action(
+ account_id, region, rule_name, error_action, error_event
+ )
+ except Exception as exc:
+ _broker_logger.warning(
+ "IoT rule %s: errorAction failed: %s: %s",
+ rule_name,
+ type(exc).__name__,
+ exc,
+ )
+
+
+async def _run_rule_actions(
+ account_id: str,
+ region: str,
+ rule: dict,
+ payload: bytes,
+ topic: str = "",
+ client_id: str | None = None,
) -> None:
if not rule or rule.get("ruleDisabled"):
return
- event = _rule_event(rule.get("sql", ""), topic, payload)
+ payload = payload or b""
+ # Decode once: both the SELECT projection and the WHERE predicate read the
+ # same message.
+ message = _rule_message(payload)
+ event = _rule_event(rule.get("sql", ""), topic, payload, client_id, message=message)
if event is _MISSING:
_broker_logger.warning(
"IoT rule %s: payload is not valid UTF-8 and its SELECT clause "
@@ -2625,19 +3568,47 @@ def _run_rule_actions(
rule.get("ruleName"),
)
return
+ where_pred = _rule_where_clause(rule.get("sql", ""))
+ if where_pred and not _eval_where(where_pred, topic, payload, message, client_id):
+ _broker_logger.debug(
+ "IoT rule %s: WHERE clause did not match on %r — no action dispatched",
+ rule.get("ruleName"),
+ topic,
+ )
+ return
+ rule_name = rule.get("ruleName", "")
+ failures: list[dict] = []
for action in rule.get("actions", []) or []:
- lam = action.get("lambda")
- if lam and lam.get("functionArn"):
- _dispatch_rule_to_lambda(account_id, region, lam["functionArn"], event)
+ action_type = next(iter(action), "?")
+ try:
+ await _dispatch_rule_action(account_id, region, rule_name, action, event)
+ except Exception as exc:
+ # Never silently, and never let one failing action kill the loop: a
+ # dropped dispatch is indistinguishable from "the rule did not
+ # match", the hardest kind of local failure to diagnose.
+ _broker_logger.warning(
+ "IoT rule %s: %s action failed: %s: %s",
+ rule_name,
+ action_type,
+ type(exc).__name__,
+ exc,
+ )
+ failures.append(
+ {"action": action_type, "errorMessage": f"{type(exc).__name__}: {exc}"}
+ )
+ if failures:
+ await _dispatch_rule_error_action(
+ account_id, region, rule, topic, payload, client_id, failures
+ )
-def _evaluate_topic_rules(
- account_id: str, region: str, topic: str, payload: bytes
+async def _evaluate_topic_rules(
+ account_id: str, region: str, topic: str, payload: bytes, client_id: str | None = None
) -> 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, region, rule, payload, topic)
+ await _run_rule_actions(account_id, region, rule, payload, topic, client_id)
async def broker_publish(
@@ -2647,13 +3618,14 @@ async def broker_publish(
payload: bytes,
qos: int = 0,
retain: bool = False,
+ client_id: str | None = None,
) -> None:
# Basic Ingest: a publish to `$aws/rules/<ruleName>` is delivered straight
# to that rule's actions and bypasses pub/sub delivery entirely.
if topic.startswith(_BASIC_INGEST_PREFIX):
remainder = topic[len(_BASIC_INGEST_PREFIX):].split("/", 1)
rule_name = remainder[0]
- _run_rule_actions(
+ await _run_rule_actions(
account_id,
region,
_topic_rules.get_scoped(account_id, region, rule_name),
@@ -2661,6 +3633,7 @@ async def broker_publish(
# Under Basic Ingest `topic()` reports the topic after the
# `$aws/rules/<ruleName>/` prefix, as it does on AWS.
remainder[1] if len(remainder) > 1 else "",
+ client_id,
)
return
@@ -2706,7 +3679,7 @@ async def broker_publish(
ps.queued_messages = ps.queued_messages[-_MAX_QUEUED_MESSAGES:]
break
- _evaluate_topic_rules(account_id, region, topic, payload)
+ await _evaluate_topic_rules(account_id, region, topic, payload, client_id)
async def broker_subscribe(
@@ -3087,6 +4060,7 @@ class _WSSession:
payload,
qos=qos,
retain=retain,
+ client_id=self._client_id,
)
if qos == 1 and packet_id is not None:
await self.send_bytes(_make_puback(packet_id))
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index 508f8c69..9086074e 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -610,81 +610,83 @@ def _resolve_dedup_id(topic: dict, params: dict, message: str) -> str:
# Publish
# ---------------------------------------------------------------------------
-def _publish(params):
- topic_arn = _normalize_arn(_p(params, "TopicArn") or _p(params, "TargetArn"))
- phone_number = _p(params, "PhoneNumber")
- message = _p(params, "Message")
- subject = _p(params, "Subject")
- message_structure = _p(params, "MessageStructure")
+class SnsPublishError(ValueError):
+ """A publish AWS rejects, carrying the error code the API answers with."""
+
+ def __init__(self, code: str, message: str):
+ super().__init__(message)
+ self.code = code
+
+
+def publish_internal(
+ topic_arn: str,
+ message,
+ subject: str = "",
+ *,
+ message_structure: str = "",
+ message_attributes: dict | None = None,
+ message_group_id: str = "",
+ message_deduplication_id: str = "",
+) -> dict | None:
+ """Publish to a topic from inside MiniStack, bypassing the HTTP action.
+
+ Cross-service producers (an IoT topic rule, an EventBridge target, a Pipes
+ enrichment) reach SNS in-process, and every site that hand-rolls the message
+ append plus fan-out loses whatever the Publish path does around them — the
+ payload size limit, FIFO grouping and deduplication, and the message_structure
+ / message_attributes fields a subscriber filter policy reads. This is that
+ path, and `_publish` itself is the HTTP wrapper over it.
+
+ Returns ``{"message_id", "sequence_number", "duplicate"}``, or ``None`` when
+ the topic does not exist. Raises `SnsPublishError` for a publish AWS would
+ reject — notably a FIFO topic addressed without a MessageGroupId.
+ """
+ topic = _topics.get(topic_arn)
+ if topic is None:
+ return None
if isinstance(message, (dict, list)):
message = json.dumps(message)
-
- if phone_number and not topic_arn:
- msg_id = new_uuid()
- logger.info("SNS SMS stub to %s: %s", phone_number, message[:80])
- return _xml(200, "PublishResponse",
- f"<PublishResult><MessageId>{msg_id}</MessageId></PublishResult>")
-
- if not topic_arn:
- return _error("InvalidParameterException",
- "TopicArn, TargetArn, or PhoneNumber is required", 400)
-
- if topic_arn not in _topics:
- # Publishing directly to a mobile-push platform endpoint (TargetArn) is
- # valid in AWS — https://docs.aws.amazon.com/sns/latest/api/API_Publish.html
- # We don't deliver anything, but the call must succeed.
- if topic_arn in _platform_endpoints:
- msg_id = new_uuid()
- logger.info("SNS platform-endpoint publish stub to %s", topic_arn)
- return _xml(200, "PublishResponse",
- f"<PublishResult><MessageId>{msg_id}</MessageId></PublishResult>")
- return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)
-
- topic = _topics[topic_arn]
- msg_attrs = _parse_message_attributes(params)
+ msg_attrs = message_attributes or {}
# AWS rejects Publish requests whose Message + MessageAttributes exceed
# 256 KiB. Real-AWS error code is InvalidParameter (400).
if _message_payload_size(message, msg_attrs) > _SNS_MAX_PAYLOAD_BYTES:
- return _error(
+ raise SnsPublishError(
"InvalidParameter",
f"Invalid parameter: Message too long. Maximum size is {_SNS_MAX_PAYLOAD_BYTES} bytes.",
- 400,
)
- fifo = _is_fifo_topic(topic)
+ seq_number = None
+ dedup_id = message_deduplication_id
- # ── FIFO validation, deduplication, and sequencing ──
- if fifo:
- group_id = _p(params, "MessageGroupId") or ""
- if not group_id:
- return _error(
+ # -- FIFO validation, deduplication, and sequencing --
+ if _is_fifo_topic(topic):
+ if not message_group_id:
+ raise SnsPublishError(
"InvalidParameterException",
"Invalid parameter: The MessageGroupId parameter is required for FIFO topics",
- 400,
)
-
# Resolve dedup ID: explicit > CBD SHA-256 > error
try:
- dedup_id = _resolve_dedup_id(topic, params, message)
+ dedup_id = _resolve_dedup_id(
+ topic, {"MessageDeduplicationId": message_deduplication_id}, message
+ )
except ValueError as exc:
- return _error("InvalidParameterException", str(exc), 400)
+ raise SnsPublishError("InvalidParameterException", str(exc)) from exc
# Prune expired cache entries, then check for duplicate
with _fifo_lock:
_prune_sns_dedup(topic)
cached = topic.get("dedup_cache", {}).get(dedup_id)
if cached:
- # Duplicate within the 5-minute window — return cached result
- return _xml(
- 200,
- "PublishResponse",
- f"<PublishResult>"
- f"<MessageId>{cached['message_id']}</MessageId>"
- f"<SequenceNumber>{cached['sequence_number']}</SequenceNumber>"
- f"</PublishResult>",
- )
+ # Duplicate within the 5-minute window — replay the original
+ # result without re-delivering to subscribers.
+ return {
+ "message_id": cached["message_id"],
+ "sequence_number": cached["sequence_number"],
+ "duplicate": True,
+ }
# New message: increment sequence counter
topic["fifo_seq"] = topic.get("fifo_seq", 0) + 1
@@ -697,31 +699,9 @@ def _publish(params):
"message_id": msg_id,
"sequence_number": seq_number,
}
+ else:
+ msg_id = new_uuid()
- topic["messages"].append({
- "id": msg_id,
- "message": message,
- "subject": subject,
- "message_structure": message_structure,
- "message_attributes": msg_attrs,
- "timestamp": int(time.time()),
- })
-
- _fanout(topic_arn, msg_id, message, subject, message_structure, msg_attrs,
- message_group_id=group_id, message_dedup_id=dedup_id)
-
- logger.info("SNS FIFO publish to %s: %s", topic_arn, message[:100])
- return _xml(
- 200,
- "PublishResponse",
- f"<PublishResult>"
- f"<MessageId>{msg_id}</MessageId>"
- f"<SequenceNumber>{seq_number}</SequenceNumber>"
- f"</PublishResult>",
- )
-
- # ── Standard (non-FIFO) publish path ──
- msg_id = new_uuid()
topic["messages"].append({
"id": msg_id,
"message": message,
@@ -730,15 +710,62 @@ def _publish(params):
"message_attributes": msg_attrs,
"timestamp": int(time.time()),
})
-
- group_id = _p(params, "MessageGroupId") or ""
- dedup_id = _p(params, "MessageDeduplicationId") or ""
_fanout(topic_arn, msg_id, message, subject, message_structure, msg_attrs,
- message_group_id=group_id, message_dedup_id=dedup_id)
- logger.info("SNS publish to %s: %s", topic_arn, message[:100])
+ message_group_id=message_group_id, message_dedup_id=dedup_id)
+ logger.info(
+ "SNS%s publish to %s: %s", " FIFO" if seq_number else "", topic_arn, message[:100]
+ )
+ return {"message_id": msg_id, "sequence_number": seq_number, "duplicate": False}
+
+
+def _publish(params):
+ topic_arn = _normalize_arn(_p(params, "TopicArn") or _p(params, "TargetArn"))
+ phone_number = _p(params, "PhoneNumber")
+ message = _p(params, "Message")
+ subject = _p(params, "Subject")
+ message_structure = _p(params, "MessageStructure")
+
+ if isinstance(message, (dict, list)):
+ message = json.dumps(message)
+
+ if phone_number and not topic_arn:
+ msg_id = new_uuid()
+ logger.info("SNS SMS stub to %s: %s", phone_number, message[:80])
+ return _xml(200, "PublishResponse",
+ f"<PublishResult><MessageId>{msg_id}</MessageId></PublishResult>")
+
+ if not topic_arn:
+ return _error("InvalidParameterException",
+ "TopicArn, TargetArn, or PhoneNumber is required", 400)
+
+ if topic_arn not in _topics:
+ # Publishing directly to a mobile-push platform endpoint (TargetArn) is
+ # valid in AWS — https://docs.aws.amazon.com/sns/latest/api/API_Publish.html
+ # We don't deliver anything, but the call must succeed.
+ if topic_arn in _platform_endpoints:
+ msg_id = new_uuid()
+ logger.info("SNS platform-endpoint publish stub to %s", topic_arn)
+ return _xml(200, "PublishResponse",
+ f"<PublishResult><MessageId>{msg_id}</MessageId></PublishResult>")
+ return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)
+
+ try:
+ result = publish_internal(
+ topic_arn,
+ message,
+ subject,
+ message_structure=message_structure,
+ message_attributes=_parse_message_attributes(params),
+ message_group_id=_p(params, "MessageGroupId") or "",
+ message_deduplication_id=_p(params, "MessageDeduplicationId") or "",
+ )
+ except SnsPublishError as exc:
+ return _error(exc.code, str(exc), 400)
- return _xml(200, "PublishResponse",
- f"<PublishResult><MessageId>{msg_id}</MessageId></PublishResult>")
+ inner = f"<MessageId>{result['message_id']}</MessageId>"
+ if result["sequence_number"] is not None:
+ inner += f"<SequenceNumber>{result['sequence_number']}</SequenceNumber>"
+ return _xml(200, "PublishResponse", f"<PublishResult>{inner}</PublishResult>")
def _publish_batch(params):
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 9ebcb56a..a1769003 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -7,6 +7,7 @@ iot-data Publish) is covered separately in ``test_iot_data.py``.
import base64
import json
+import logging
import time
import uuid
@@ -1069,6 +1070,76 @@ def test_iot_replace_topic_rule(iot_client):
iot_client.delete_topic_rule(ruleName=name)
+def test_iot_create_topic_rule_garbage_sql_rejected(iot_client):
+ with pytest.raises(ClientError) as ei:
+ iot_client.create_topic_rule(
+ ruleName=_rule_name(),
+ topicRulePayload={"sql": "this is not sql", "actions": []},
+ )
+ assert ei.value.response["Error"]["Code"] == "SqlParseException"
+
+
+def test_iot_create_topic_rule_unsupported_where_rejected(iot_client):
+ """A WHERE the evaluator cannot parse is rejected at creation instead of
+ being stored and silently never firing.
+
+ Malformed SQL only: syntax AWS accepts has to be accepted here too, or the
+ rule that deploys on AWS fails to create locally.
+ """
+ with pytest.raises(ClientError) as ei:
+ iot_client.create_topic_rule(
+ ruleName=_rule_name(),
+ topicRulePayload={
+ "sql": "SELECT * FROM 'a' WHERE (state = 'on'",
+ "actions": [],
+ },
+ )
+ assert ei.value.response["Error"]["Code"] == "SqlParseException"
+
+
+def test_iot_create_topic_rule_accepts_or_and_parentheses(iot_client):
+ """`OR` and parenthesised groups are valid AWS rule SQL — rejecting them
+ would fail rules that deploy fine on AWS."""
+ name = _rule_name()
+ sql = "SELECT * FROM 'a' WHERE (state = 'on' OR state = 'standby') AND temp > 20"
+ iot_client.create_topic_rule(
+ ruleName=name, topicRulePayload={"sql": sql, "actions": []}
+ )
+ assert iot_client.get_topic_rule(ruleName=name)["rule"]["sql"] == sql
+ iot_client.delete_topic_rule(ruleName=name)
+
+
+def test_iot_create_topic_rule_accepts_full_where_grammar(iot_client):
+ """The rest of the WHERE syntax AWS accepts — over-strict validation here
+ turns a working setup into a hard 400 (or a failed CloudFormation stack)."""
+ name = _rule_name()
+ sql = (
+ "SELECT * FROM 'a' WHERE state IN ('on', 'idle') AND temp BETWEEN 1 AND 5 "
+ "AND serial LIKE 'dev-%' AND nickname IS NOT NULL AND enabled "
+ "AND isUndefined(site) AND note <> 'it''s off'"
+ )
+ iot_client.create_topic_rule(
+ ruleName=name, topicRulePayload={"sql": sql, "actions": []}
+ )
+ assert iot_client.get_topic_rule(ruleName=name)["rule"]["sql"] == sql
+ iot_client.delete_topic_rule(ruleName=name)
+
+
+def test_iot_replace_topic_rule_garbage_sql_rejected(iot_client):
+ name = _rule_name()
+ iot_client.create_topic_rule(
+ ruleName=name, topicRulePayload={"sql": "SELECT * FROM 'a'", "actions": []}
+ )
+ with pytest.raises(ClientError) as ei:
+ iot_client.replace_topic_rule(
+ ruleName=name, topicRulePayload={"sql": "garbage", "actions": []}
+ )
+ assert ei.value.response["Error"]["Code"] == "SqlParseException"
+ # The stored rule is untouched.
+ assert iot_client.get_topic_rule(ruleName=name)["rule"]["sql"] == "SELECT * FROM 'a'"
+ iot_client.delete_topic_rule(ruleName=name)
+
+
def test_iot_replace_missing_topic_rule_404(iot_client):
with pytest.raises(ClientError) as ei:
iot_client.replace_topic_rule(
@@ -1121,6 +1192,84 @@ def test_iot_topic_rule_cfn_deploy(cfn, iot_client):
iot_client.get_topic_rule(ruleName=rule)
+def test_iot_topic_rule_cfn_invalid_sql_fails_resource(cfn, iot_client):
+ """CloudFormation validates rule SQL too: a rule the engine cannot evaluate
+ must fail the resource, not reach CREATE_COMPLETE and silently never fire
+ (real CloudFormation fails on the underlying CreateTopicRule call).
+
+ No provisioner change is needed for that — `RuleSqlError` is a `ValueError`,
+ which is already what the stack runner turns into a CREATE_FAILED carrying
+ the reason.
+ """
+ stack = "iot-badsql-" + uuid.uuid4().hex[:8]
+ rule = _rule_name("badsql")
+ template = {
+ "Resources": {
+ "BadRule": {
+ "Type": "AWS::IoT::TopicRule",
+ "Properties": {
+ "RuleName": rule,
+ "TopicRulePayload": {
+ "Sql": "this is not sql",
+ "Actions": [],
+ },
+ },
+ }
+ },
+ }
+ try:
+ cfn.create_stack(
+ StackName=stack, TemplateBody=json.dumps(template), DisableRollback=True
+ )
+ st = _wait_stack_iot(cfn, stack)
+ assert st["StackStatus"] == "CREATE_FAILED"
+ reason = st.get("StackStatusReason", "")
+ assert "BadRule" in reason and "Rule SQL" in reason
+
+ events = cfn.describe_stack_events(StackName=stack)["StackEvents"]
+ assert any(
+ event["LogicalResourceId"] == "BadRule"
+ and event["ResourceStatus"] == "CREATE_FAILED"
+ for event in events
+ )
+ # Nothing was stored: the invalid rule never entered the rule store.
+ with pytest.raises(ClientError) as ei:
+ iot_client.get_topic_rule(ruleName=rule)
+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ finally:
+ try:
+ cfn.delete_stack(StackName=stack)
+ _wait_stack_gone_iot(cfn, stack)
+ except ClientError:
+ pass
+
+
+def test_iot_topic_rule_cfn_where_with_or_deploys(cfn, iot_client):
+ """A WHERE using OR and parentheses deploys through CloudFormation — the
+ grammar the validator accepts is the same on both paths."""
+ stack = "iot-orsql-" + uuid.uuid4().hex[:8]
+ rule = _rule_name("orsql")
+ sql = "SELECT * FROM 'sensors/+/telemetry' WHERE (temp > 30 OR humidity > 80) AND state = 'on'"
+ template = {
+ "Resources": {
+ "OrRule": {
+ "Type": "AWS::IoT::TopicRule",
+ "Properties": {
+ "RuleName": rule,
+ "TopicRulePayload": {"Sql": sql, "Actions": []},
+ },
+ }
+ },
+ }
+ cfn.create_stack(StackName=stack, TemplateBody=json.dumps(template))
+ st = _wait_stack_iot(cfn, stack)
+ assert st["StackStatus"] == "CREATE_COMPLETE", st.get("StackStatusReason")
+ assert iot_client.get_topic_rule(ruleName=rule)["rule"]["sql"] == sql
+
+ cfn.delete_stack(StackName=stack)
+ _wait_stack_gone_iot(cfn, stack)
+
+
def _wait_stack_iot(cfn, name, timeout=30):
deadline = time.time() + timeout
while time.time() < deadline:
@@ -1562,8 +1711,8 @@ def test_iot_topic_rules_and_basic_ingest_use_publish_region(monkeypatch):
)
dispatched = []
- def _capture_rule_action(
- dispatched_account_id, dispatched_region, rule, payload, topic=""
+ async def _capture_rule_action(
+ dispatched_account_id, dispatched_region, rule, payload, topic="", client_id=None
):
dispatched.append((dispatched_account_id, dispatched_region, rule, payload))
@@ -3214,3 +3363,996 @@ def test_rule_event_from_less_basic_ingest_projects():
"SELECT deviceId AS id, temp", "$aws/rules/myrule", b'{"deviceId": "d1", "temp": 22, "extra": "x"}'
)
assert event == {"id": "d1", "temp": 22}
+
+
+# ----------------------------------------------------------------------
+# Rule SQL functions: newuuid(), replace(), clientid() (and the accepted
+# but unresolvable principal() / traceid()).
+# ----------------------------------------------------------------------
+
+
+def test_rule_event_newuuid_projects_a_fresh_uuid():
+ from ministack.services.iot import _rule_event
+
+ first = _rule_event("SELECT newuuid() AS id FROM 't'", "t", b"{}")
+ second = _rule_event("SELECT newuuid() AS id FROM 't'", "t", b"{}")
+ assert uuid.UUID(first["id"]) # well-formed
+ assert first["id"] != second["id"]
+
+
+def test_rule_event_replace_rewrites_strings():
+ from ministack.services.iot import _rule_event
+
+ event = _rule_event(
+ "SELECT replace(deviceId, 'dev-', 'unit-') AS id FROM 't'",
+ "t",
+ b'{"deviceId": "dev-42"}',
+ )
+ assert event == {"id": "unit-42"}
+
+
+def test_rule_event_replace_of_missing_or_nonstring_is_omitted():
+ from ministack.services.iot import _rule_event
+
+ # Missing source attribute → Undefined → omitted.
+ event = _rule_event(
+ "SELECT replace(absent, 'a', 'b') AS x, deviceId FROM 't'",
+ "t",
+ b'{"deviceId": "d1"}',
+ )
+ assert event == {"deviceId": "d1"}
+ # Non-string source → Undefined on AWS.
+ event = _rule_event(
+ "SELECT replace(count, 'a', 'b') AS x FROM 't'", "t", b'{"count": 3}'
+ )
+ assert event == {}
+
+
+def test_rule_event_clientid_resolves_for_mqtt_and_is_omitted_for_http():
+ from ministack.services.iot import _rule_event
+
+ sql = "SELECT clientid() AS cid, temp FROM 't'"
+ # MQTT publish: the broker threads the publishing client's id through.
+ event = _rule_event(sql, "t", b'{"temp": 22}', client_id="sensor-7")
+ assert event == {"cid": "sensor-7", "temp": 22}
+ # HTTP publish: no MQTT client exists — AWS resolves clientid() to
+ # Undefined, so the field is omitted from the projection.
+ event = _rule_event(sql, "t", b'{"temp": 22}')
+ assert event == {"temp": 22}
+
+
+def test_rule_event_replace_handles_escaped_quotes():
+ """`replace()` takes SQL string literals, so a quote in either argument is
+ written the SQL way — doubled."""
+ from ministack.services.iot import _rule_event
+
+ event = _rule_event(
+ "SELECT replace(note, 'it''s', 'it is') AS n FROM 't'",
+ "t",
+ b'{"note": "it\'s on"}',
+ )
+ assert event == {"n": "it is on"}
+
+
+def test_rule_event_principal_and_traceid_accepted_but_unresolved(caplog):
+ """Both are real AWS functions, so a rule using them is stored rather than
+ failing a stack that deploys on AWS — but this publish path carries no
+ certificate identity or trace id, so they warn like any other function the
+ evaluator does not implement."""
+ from ministack.services import iot as iot_module
+ from ministack.services.iot import _rule_event, _validate_rule_sql
+
+ sql = "SELECT principal() AS p, traceid() AS t, temp FROM 't'"
+ assert _validate_rule_sql(sql) is None
+ # The evaluator warns once per function name for the life of the process.
+ iot_module._warned_sql_funcs.clear()
+ with caplog.at_level(logging.WARNING, logger="iot"):
+ assert _rule_event(sql, "t", b'{"temp": 1}') == {"temp": 1}
+ warned = " ".join(r.message for r in caplog.records)
+ assert "principal()" in warned and "traceid()" in warned
+
+
+def test_eval_where_clientid_reaches_every_leaf_form():
+ """clientid() is an operand like any other, so it resolves inside the whole
+ WHERE grammar, not just a plain comparison."""
+ from ministack.services.iot import _eval_where, _rule_message
+
+ raw = b'{"temp": 1}'
+ message = _rule_message(raw)
+ for pred, expected in (
+ ("clientid() = 'sensor-7'", True),
+ ("clientid() IN ('sensor-7', 'sensor-8')", True),
+ ("clientid() IN ('sensor-8')", False),
+ ("clientid() LIKE 'sensor-%'", True),
+ ("isUndefined(clientid())", False),
+ ):
+ assert _eval_where(pred, "t", raw, message, "sensor-7") is expected
+ # An HTTP publish carries no client id, so every one of them fails closed.
+ for pred in (
+ "clientid() = 'sensor-7'",
+ "clientid() IN ('sensor-7')",
+ "clientid() LIKE 'sensor-%'",
+ ):
+ assert _eval_where(pred, "t", raw, message) is False
+ assert _eval_where("isUndefined(clientid())", "t", raw, message) is True
+
+
+def test_broker_publish_threads_client_id_into_rule_projection(monkeypatch):
+ """`clientid()` sees the WS client's id via broker_publish, end to end."""
+ from ministack.services import iot as iot_module
+
+ reset()
+ iot_module._topic_rules.clear()
+ account_id = "123456789012"
+ iot_module._topic_rules.set_scoped(
+ account_id,
+ _TEST_REGION,
+ "cid_rule",
+ {
+ "ruleName": "cid_rule",
+ "sql": "SELECT clientid() AS cid FROM 'sensors/#'",
+ "ruleDisabled": False,
+ "actions": [{"lambda": {"functionArn": "arn:aws:lambda:us-east-1:123456789012:function:sink"}}],
+ },
+ )
+ dispatched = []
+ monkeypatch.setattr(
+ iot_module,
+ "_dispatch_rule_to_lambda",
+ lambda account, region, arn, event: dispatched.append(event),
+ )
+
+ async def _run():
+ # A WS PUBLISH passes the connected client's id...
+ send, _sent = _mock_send()
+ session = _WSSession(send, account_id)
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("sensor-7"))
+ await session.handle_packet(
+ PKT_PUBLISH, 0, _encode_string("sensors/door") + b'{"n": 1}'
+ )
+ await session.cleanup()
+ # ...while the HTTP publish path passes none.
+ await publish(account_id, "sensors/door", b'{"n": 2}')
+
+ try:
+ asyncio.run(_run())
+ assert dispatched == [{"cid": "sensor-7"}, {}]
+ finally:
+ iot_module._topic_rules.clear()
+ reset()
+
+
+# ----------------------------------------------------------------------
+# Rule SQL WHERE clause (white-box tests for _rule_where_clause /
+# _eval_where / _validate_rule_sql).
+# ----------------------------------------------------------------------
+
+
+ ("sql", "expected"),
+ [
+ ("SELECT * FROM 'a/b' WHERE state = 'on'", "state = 'on'"),
+ ("SELECT * FROM 'a/b'", ""),
+ ("SELECT temp WHERE temp > 20", "temp > 20"), # FROM-less Basic Ingest form
+ ("SELECT temp", ""),
+ # A WHERE-ish string inside the topic filter is not a predicate.
+ ("SELECT * FROM 'a/WHERE x/b'", ""),
+ ],
+)
+def test_rule_where_clause_extraction(sql, expected):
+ from ministack.services.iot import _rule_where_clause
+
+ assert _rule_where_clause(sql) == expected
+
+
+ ("pred", "payload", "expected"),
+ [
+ # equality (both spellings) on strings and numbers
+ ("state = 'on'", {"state": "on"}, True),
+ ("state == 'on'", {"state": "on"}, True),
+ ("state = 'on'", {"state": "off"}, False),
+ ("temp = 22", {"temp": 22}, True),
+ ("temp = 22", {"temp": 23}, False),
+ # inequality (both spellings)
+ ("state <> 'on'", {"state": "off"}, True),
+ ("state != 'on'", {"state": "on"}, False),
+ # a predicate over a missing attribute is Undefined → never matches,
+ # not even for <> (fail closed, as on AWS)
+ ("absent = 'x'", {"state": "on"}, False),
+ ("absent <> 'x'", {"state": "on"}, False),
+ ("absent > 1", {"state": "on"}, False),
+ # numeric comparisons
+ ("temp > 20", {"temp": 22}, True),
+ ("temp > 22", {"temp": 22}, False),
+ ("temp >= 22", {"temp": 22}, True),
+ ("temp < 30", {"temp": 22}, True),
+ ("temp <= 21", {"temp": 22}, False),
+ # ordering comparisons are numeric-only — a string operand is Undefined
+ ("temp > 20", {"temp": "hot"}, False),
+ # nested attribute paths
+ ("state.reported.power = 'on'", {"state": {"reported": {"power": "on"}}}, True),
+ ("state.reported.power = 'on'", {"state": {"reported": {"power": "off"}}}, False),
+ # AND conjunction: all clauses must hold
+ ("state = 'on' AND temp > 20", {"state": "on", "temp": 22}, True),
+ ("state = 'on' AND temp > 20", {"state": "on", "temp": 19}, False),
+ ("state = 'on' AND temp > 20", {"state": "off", "temp": 22}, False),
+ # AND inside a string literal is not a conjunction
+ ("mode = 'UP AND DOWN'", {"mode": "UP AND DOWN"}, True),
+ # OR disjunction: any clause may carry the predicate
+ ("state = 'on' OR state = 'off'", {"state": "off"}, True),
+ ("state = 'on' OR state = 'off'", {"state": "idle"}, False),
+ ("state = 'on' or temp > 20", {"state": "off", "temp": 22}, True),
+ # an Undefined leaf is false, but an OR sibling can still carry it
+ ("absent = 'x' OR state = 'on'", {"state": "on"}, True),
+ ("absent = 'x' OR state = 'on'", {"state": "off"}, False),
+ # precedence: OR binds loosest, so this reads (a AND b) OR c
+ ("state = 'on' AND temp > 20 OR mode = 'test'",
+ {"state": "off", "temp": 1, "mode": "test"}, True),
+ ("state = 'on' AND temp > 20 OR mode = 'test'",
+ {"state": "on", "temp": 22, "mode": "prod"}, True),
+ ("state = 'on' AND temp > 20 OR mode = 'test'",
+ {"state": "on", "temp": 1, "mode": "prod"}, False),
+ # ...and the same predicate the other way round: c OR (a AND b)
+ ("mode = 'test' OR state = 'on' AND temp > 20",
+ {"state": "on", "temp": 1, "mode": "prod"}, False),
+ ("mode = 'test' OR state = 'on' AND temp > 20",
+ {"state": "off", "temp": 1, "mode": "test"}, True),
+ # parentheses override that precedence: (a OR b) AND c
+ ("(state = 'on' OR mode = 'test') AND temp > 20",
+ {"state": "off", "mode": "test", "temp": 22}, True),
+ ("(state = 'on' OR mode = 'test') AND temp > 20",
+ {"state": "off", "mode": "test", "temp": 1}, False),
+ ("(state = 'on' OR mode = 'test') AND temp > 20",
+ {"state": "off", "mode": "prod", "temp": 22}, False),
+ # a group wrapping the whole predicate is a no-op
+ ("(state = 'on')", {"state": "on"}, True),
+ ("((state = 'on'))", {"state": "on"}, True),
+ # nested groups
+ ("((state = 'on' OR state = 'off') AND temp > 20) OR mode = 'test'",
+ {"state": "on", "temp": 22, "mode": "prod"}, True),
+ ("((state = 'on' OR state = 'off') AND temp > 20) OR mode = 'test'",
+ {"state": "idle", "temp": 22, "mode": "prod"}, False),
+ ("((state = 'on' OR state = 'off') AND temp > 20) OR mode = 'test'",
+ {"state": "idle", "temp": 1, "mode": "test"}, True),
+ # AND binds tighter inside an OR branch, groups or not
+ ("mode = 'test' OR (state = 'on' AND temp > 20)",
+ {"state": "on", "temp": 22, "mode": "prod"}, True),
+ # OR inside a string literal is not a disjunction
+ ("mode = 'ON OR OFF'", {"mode": "ON OR OFF"}, True),
+ ("mode = 'ON OR OFF'", {"mode": "ON"}, False),
+ ("mode = 'ON OR OFF' AND temp > 20", {"mode": "ON OR OFF", "temp": 22}, True),
+ # an attribute path may contain the keywords without being one
+ ("android = 'yes' OR orbit = 1", {"orbit": 1}, True),
+ # regexp_matches
+ ("regexp_matches(serial, '^dev-[0-9]+$')", {"serial": "dev-42"}, True),
+ ("regexp_matches(serial, '^dev-[0-9]+$')", {"serial": "gw-42"}, False),
+ ("regexp_matches(absent, '.*')", {"serial": "dev-42"}, False),
+ # booleans stay distinct from 0/1
+ ("armed = 1", {"armed": True}, False),
+ # IN / NOT IN over a value list
+ ("state IN ('on', 'idle')", {"state": "idle"}, True),
+ ("state IN ('on', 'idle')", {"state": "off"}, False),
+ ("state IN('on')", {"state": "on"}, True), # no space before the list
+ ("code IN (1, 2, 3)", {"code": 2}, True),
+ ("code IN (1, 2, 3)", {"code": 4}, False),
+ ("state NOT IN ('on', 'idle')", {"state": "off"}, True),
+ ("state NOT IN ('on', 'idle')", {"state": "on"}, False),
+ ("absent IN ('on')", {"state": "on"}, False),
+ ("absent NOT IN ('on')", {"state": "on"}, False), # Undefined fails closed
+ # LIKE / NOT LIKE — % matches a run, _ exactly one character
+ ("state LIKE 'on%'", {"state": "online"}, True),
+ ("state LIKE 'on%'", {"state": "gone"}, False),
+ ("state LIKE 'o_'", {"state": "on"}, True),
+ ("state LIKE 'o_'", {"state": "one"}, False),
+ ("state LIKE 'on'", {"state": "on"}, True),
+ # the pattern's own regex metacharacters stay literal
+ ("state LIKE 'a.c'", {"state": "abc"}, False),
+ ("state LIKE 'a.c'", {"state": "a.c"}, True),
+ ("state NOT LIKE 'on%'", {"state": "gone"}, True),
+ ("state NOT LIKE 'on%'", {"state": "online"}, False),
+ # LIKE wants a String, so AWS converts an Int or a Boolean to one
+ # first — the same conversion regexp_matches() gets, pinned together
+ # below so the two operators cannot drift apart again.
+ ("temp LIKE '2%'", {"temp": 22}, True),
+ ("flag LIKE 'tr%'", {"flag": True}, True),
+ ("absent LIKE '%'", {"state": "on"}, False),
+ ("nickname LIKE '%'", {"nickname": None}, False), # Null does not convert
+ # BETWEEN, inclusive on both bounds — its AND is not a conjunction
+ ("temp BETWEEN 20 AND 30", {"temp": 22}, True),
+ ("temp BETWEEN 20 AND 30", {"temp": 20}, True),
+ ("temp BETWEEN 20 AND 30", {"temp": 30}, True),
+ ("temp BETWEEN 20 AND 30", {"temp": 31}, False),
+ ("temp BETWEEN 20 AND 30 AND state = 'on'", {"temp": 22, "state": "on"}, True),
+ ("temp BETWEEN 20 AND 30 AND state = 'on'", {"temp": 22, "state": "off"}, False),
+ ("state = 'on' AND temp BETWEEN 20 AND 30", {"state": "on", "temp": 22}, True),
+ ("temp BETWEEN 20 AND 30 OR state = 'on'", {"temp": 99, "state": "on"}, True),
+ ("absent BETWEEN 1 AND 5", {"temp": 3}, False),
+ ("temp BETWEEN 20 AND 30", {"temp": "hot"}, False), # numeric-only
+ # IS NULL / IS NOT NULL over a JSON null
+ ("nickname IS NULL", {"nickname": None}, True),
+ ("nickname IS NULL", {"nickname": "gw"}, False),
+ ("nickname IS NOT NULL", {"nickname": "gw"}, True),
+ ("nickname IS NOT NULL", {"nickname": None}, False),
+ # Undefined is neither NULL nor NOT NULL — both fail closed
+ ("nickname IS NULL", {"state": "on"}, False),
+ ("nickname IS NOT NULL", {"state": "on"}, False),
+ # a bare boolean attribute is a predicate on its own
+ ("enabled", {"enabled": True}, True),
+ ("enabled", {"enabled": False}, False),
+ # AWS converts a value to Boolean only from "true"/"false" — a number
+ # needs an explicit cast(), so it stays Undefined here.
+ ("enabled", {"enabled": "true"}, True),
+ ("enabled", {"enabled": "FALSE"}, False),
+ ("enabled", {"enabled": 1}, False),
+ ("enabled", {"enabled": "yes"}, False),
+ ("enabled", {"state": "on"}, False),
+ ("enabled AND temp > 20", {"enabled": True, "temp": 22}, True),
+ ("enabled AND temp > 20", {"enabled": False, "temp": 22}, False),
+ ("state.reported.on", {"state": {"reported": {"on": True}}}, True),
+ # isUndefined() — the one predicate a missing attribute satisfies
+ ("isUndefined(absent)", {"state": "on"}, True),
+ ("isUndefined(state)", {"state": "on"}, False),
+ ("isUndefined(state.reported)", {"state": {"reported": {}}}, False),
+ ("isUndefined(absent) OR state = 'on'", {"state": "off"}, True),
+ # a quote inside a string literal is escaped by doubling it
+ ("note = 'it''s on'", {"note": "it's on"}, True),
+ ("note = 'it''s on'", {"note": "its on"}, False),
+ ("note <> 'it''s on'", {"note": "off"}, True),
+ ("note IN ('it''s on', 'off')", {"note": "it's on"}, True),
+ # an escaped quote does not end the literal, so this AND is not one
+ ("note = 'it''s AND then'", {"note": "it's AND then"}, True),
+ # NOT inverts a predicate, and binds tighter than AND
+ ("NOT enabled", {"enabled": False}, True),
+ ("NOT enabled", {"enabled": True}, False),
+ ("NOT state = 'on'", {"state": "off"}, True),
+ ("NOT state = 'on'", {"state": "on"}, False),
+ ("NOT state IN ('on', 'idle')", {"state": "off"}, True),
+ ("NOT temp BETWEEN 20 AND 30", {"temp": 31}, True),
+ ("NOT isUndefined(x)", {"x": 1}, True),
+ ("NOT isUndefined(x)", {"y": 1}, False),
+ ("NOT(a = 1)", {"a": 2}, True), # abutting its operand's bracket
+ ("NOT (a = 1 OR b = 2)", {"a": 9, "b": 9}, True),
+ ("NOT (a = 1 OR b = 2)", {"a": 1, "b": 9}, False),
+ ("NOT NOT enabled", {"enabled": True}, True),
+ ("state = 'on' AND NOT temp > 20", {"state": "on", "temp": 5}, True),
+ ("state = 'on' AND NOT temp > 20", {"state": "on", "temp": 25}, False),
+ # NOT of Undefined is Undefined, not true: negating a clause over an
+ # absent attribute still fails closed, as on AWS.
+ ("NOT state = 'on'", {"other": 1}, False),
+ ("NOT enabled", {"state": "on"}, False),
+ ("state = 'on' AND NOT temp > 20", {"state": "on"}, False),
+ # arithmetic operands, multiplicative binding tighter and parentheses
+ # regrouping — all four of these deploy on AWS
+ ("(a + b) > 10", {"a": 6, "b": 5}, True),
+ ("(a + b) > 10", {"a": 6, "b": 3}, False),
+ ("temp * 2 > 10", {"temp": 6}, True),
+ ("temp * 2 > 10", {"temp": 4}, False),
+ ("temp - 2 > 10", {"temp": 13}, True),
+ ("temp / 2 > 10", {"temp": 30}, True),
+ ("temp % 3 = 1", {"temp": 7}, True),
+ ("temp % 3 = 1", {"temp": 6}, False),
+ ("a + b * c > 10", {"a": 1, "b": 3, "c": 4}, True), # 1 + 12, not 4 * 4
+ ("(a + b) * c > 10", {"a": 1, "b": 3, "c": 2}, False), # 8, not 1 + 6
+ ("a - b - c = 1", {"a": 5, "b": 3, "c": 1}, True), # left-associative
+ # a sign is not a binary operator
+ ("temp > -5", {"temp": 1}, True),
+ ("temp * -2 < 0", {"temp": 3}, True),
+ # an Undefined or unconvertible operand makes the whole expression
+ # Undefined, so the comparison over it fails closed
+ ("absent + 1 > 0", {"temp": 1}, False),
+ ("temp + 1 > 0", {"temp": "hot"}, False),
+ # "+" is overloaded: a String operand makes it concatenation
+ ("name + '!' = 'gw!'", {"name": "gw"}, True),
+ # ordering converts a numeric-looking string, as AWS does
+ ("temp > 10", {"temp": "22"}, True),
+ ("temp > 10", {"temp": "hot"}, False),
+ # ...but equality does not: a mismatched pair is simply unequal
+ ("temp = 22", {"temp": "22"}, False),
+ # a keyword may abut a bracket instead of whitespace
+ ("(a = 1)AND(b = 2)", {"a": 1, "b": 2}, True),
+ ("(a = 1)AND(b = 2)", {"a": 1, "b": 3}, False),
+ ("(a = 1)OR(b = 2)", {"a": 9, "b": 2}, True),
+ ("(a = 1)OR(b = 2)", {"a": 9, "b": 9}, False),
+ ("((a = 1)AND(b = 2))OR(c = 3)", {"a": 9, "b": 9, "c": 3}, True),
+ ],
+)
+def test_eval_where_truth_table(pred, payload, expected):
+ from ministack.services.iot import _eval_where, _rule_message
+
+ raw = json.dumps(payload).encode()
+ assert _eval_where(pred, "sensors/a1/telemetry", raw, _rule_message(raw)) is expected
+
+
+def test_eval_where_topic_function():
+ from ministack.services.iot import _eval_where, _rule_message
+
+ raw = b'{"x": 1}'
+ message = _rule_message(raw)
+ assert _eval_where("topic(2) = 'a1'", "sensors/a1/telemetry", raw, message) is True
+ assert _eval_where("topic(2) = 'b7'", "sensors/a1/telemetry", raw, message) is False
+
+
+ "sql",
+ [
+ "SELECT * FROM 'a/b'",
+ "SELECT temp AS t FROM 'a/+/b' WHERE temp > 20",
+ "SELECT * FROM 'a' WHERE state = 'on' AND regexp_matches(serial, '^d')",
+ "SELECT deviceId, temp WHERE temp >= 1.5", # FROM-less Basic Ingest form
+ "SELECT encode(*, 'base64') AS data FROM 'bin'",
+ # OR and parenthesised groups: real AWS accepts these, so a rule that
+ # deploys on AWS must not be rejected here.
+ "SELECT * FROM 'a' WHERE state = 'on' OR state = 'off'",
+ "SELECT * FROM 'a' WHERE (state = 'on')",
+ "SELECT * FROM 'a' WHERE (state = 'on' OR state = 'off') AND temp > 20",
+ "SELECT * FROM 'a' WHERE ((a = 1 OR b = 2) AND (c = 3 OR d = 4)) OR e = 5",
+ # ...and the rest of the WHERE grammar real AWS accepts. A working local
+ # setup must not turn into a hard CreateTopicRule 400 here.
+ "SELECT * FROM 'a' WHERE state IN ('on', 'idle')",
+ "SELECT * FROM 'a' WHERE state IN('on')",
+ "SELECT * FROM 'a' WHERE state NOT IN ('on')",
+ "SELECT * FROM 'a' WHERE state LIKE 'on%'",
+ "SELECT * FROM 'a' WHERE state NOT LIKE 'on%'",
+ "SELECT * FROM 'a' WHERE temp BETWEEN 1 AND 5",
+ "SELECT * FROM 'a' WHERE temp BETWEEN 1 AND 5 AND state = 'on'",
+ "SELECT * FROM 'a' WHERE nickname IS NULL",
+ "SELECT * FROM 'a' WHERE nickname IS NOT NULL",
+ "SELECT * FROM 'a' WHERE isUndefined(state)",
+ "SELECT * FROM 'a' WHERE enabled", # a bare boolean attribute
+ "SELECT * FROM 'a' WHERE note = 'it''s on'", # escaped quote
+ "SELECT * FROM 'a' WHERE (a = 1)AND(b = 2)", # no space around the keyword
+ # NOT and arithmetic: all of these create a working rule on real AWS, so
+ # rejecting them here would fail a stack that deploys.
+ "SELECT * FROM 'a' WHERE NOT enabled",
+ "SELECT * FROM 'a' WHERE NOT state = 'on'",
+ "SELECT * FROM 'a' WHERE NOT(state = 'on')",
+ "SELECT * FROM 'a' WHERE state = 'on' AND NOT temp > 20",
+ "SELECT * FROM 'a' WHERE NOT state IN ('on', 'idle')",
+ "SELECT * FROM 'a' WHERE (a + b) > 10",
+ "SELECT * FROM 'a' WHERE temp * 2 > 10",
+ "SELECT * FROM 'a' WHERE temp - 2 > 10",
+ "SELECT * FROM 'a' WHERE temp / 2 > 10",
+ "SELECT * FROM 'a' WHERE id % 2 = 0",
+ "SELECT * FROM 'a' WHERE a + b * c > 10",
+ "SELECT * FROM 'a' WHERE temp > -5",
+ # A call this evaluator does not implement is still accepted: AWS's
+ # function library is larger, and rejecting it would fail a stack that
+ # deploys on AWS. put_topic_rule warns instead.
+ "SELECT * FROM 'a' WHERE bogus_fn(x) = 1",
+ "SELECT get_thing_shadow('t') AS s FROM 'a'",
+ ],
+)
+def test_validate_rule_sql_accepts_supported_grammar(sql):
+ from ministack.services.iot import _validate_rule_sql
+
+ assert _validate_rule_sql(sql) is None
+
+
+ "sql",
+ [
+ "this is not sql",
+ "",
+ "SELECT * FROM topic_without_quotes",
+ "SELECT * FROM 'a' WHERE regexp_matches(serial, '[unbalanced')",
+ "SELECT * FROM 'a' WHERE 42", # a literal is not a predicate
+ "SELECT * FROM 'a' WHERE state LIKE on", # LIKE needs a quoted pattern
+ "SELECT * FROM 'a' WHERE state IN 'on'", # ...and IN a bracketed list
+ "SELECT * FROM 'a' WHERE state IN ()",
+ "SELECT * FROM 'a' WHERE temp BETWEEN 1", # BETWEEN needs both bounds
+ "SELECT * FROM 'a' WHERE nickname IS EMPTY",
+ "SELECT * FROM 'a' WHERE note = 'unterminated",
+ # unbalanced parentheses stay a parse error rather than being guessed at
+ "SELECT * FROM 'a' WHERE (state = 'on'",
+ "SELECT * FROM 'a' WHERE state = 'on')",
+ "SELECT * FROM 'a' WHERE (state = 'on' AND (temp > 20)",
+ "SELECT * FROM 'a' WHERE ()",
+ # an empty operand around a keyword is not a predicate
+ "SELECT * FROM 'a' WHERE state = 'on' OR",
+ "SELECT * FROM 'a' WHERE OR state = 'on'",
+ "SELECT * FROM 'a' WHERE state = 'on' AND",
+ "SELECT * FROM 'a' WHERE NOT", # NOT needs a predicate to invert
+ "SELECT * FROM 'a' WHERE temp * > 10", # ...and an operator two operands
+ "SELECT * FROM 'a' WHERE temp * 2 +",
+ ],
+)
+def test_validate_rule_sql_rejects_unparseable(sql):
+ from ministack.services.iot import _validate_rule_sql
+
+ assert _validate_rule_sql(sql) is not None
+
+
+def test_put_topic_rule_rejects_unevaluable_sql():
+ """Enforcement lives in `put_topic_rule`, so every door into the store — the
+ IoT API and the CloudFormation provisioner alike — is covered by one check."""
+ from ministack.services import iot as iot_module
+
+ reset()
+ iot_module._topic_rules.clear()
+ try:
+ with pytest.raises(iot_module.RuleSqlError):
+ iot_module.put_topic_rule(
+ "bad_rule", {"sql": "SELECT * FROM 'a' WHERE (state = 'on'"}
+ )
+ assert iot_module._topic_rules.get("bad_rule") is None
+ finally:
+ iot_module._topic_rules.clear()
+ reset()
+
+
+def test_put_topic_rule_warns_for_unimplemented_sql_function(caplog):
+ """AWS's function library is larger than this evaluator's, so a call it does
+ not implement is stored rather than failing a stack that deploys on AWS —
+ but it warns, because the rule will silently never match on it."""
+ from ministack.services import iot as iot_module
+
+ reset()
+ iot_module._topic_rules.clear()
+ try:
+ with caplog.at_level(logging.WARNING, logger="iot"):
+ iot_module.put_topic_rule(
+ "fn_rule", {"sql": "SELECT * FROM 'a' WHERE bogus_fn(x) = 1"}
+ )
+ assert iot_module._topic_rules.get("fn_rule") is not None
+ assert any("bogus_fn()" in r.message for r in caplog.records)
+ # A function it does implement says nothing.
+ caplog.clear()
+ with caplog.at_level(logging.WARNING, logger="iot"):
+ iot_module.put_topic_rule(
+ "ok_rule", {"sql": "SELECT * FROM 'a' WHERE topic(2) = 'x'"}
+ )
+ assert not caplog.records
+ finally:
+ iot_module._topic_rules.clear()
+ reset()
+
+
+ "sql",
+ [
+ "SELECT * FROM 'a' WHERE (state = 'on')",
+ "SELECT * FROM 'a' WHERE (a = 1) AND (b = 2)",
+ "SELECT * FROM 'a' WHERE state IN ('on', 'idle')",
+ "SELECT * FROM 'a' WHERE state NOT IN ('on')",
+ "SELECT * FROM 'a' WHERE NOT (a = 1)",
+ "SELECT * FROM 'a' WHERE temp BETWEEN 1 AND (2 + 3)",
+ ],
+)
+def test_put_topic_rule_does_not_mistake_a_keyword_for_a_function(caplog, sql):
+ """A SQL keyword may sit in front of a bracket without opening a call.
+
+ Scanning for `<name>(` alone read `WHERE (`, `IN (` and `AND (` as calls and
+ warned about a missing where()/in()/and() — noise on perfectly ordinary
+ rules, and exactly the kind that trains people to ignore the warning that
+ matters.
+ """
+ from ministack.services import iot as iot_module
+
+ reset()
+ iot_module._topic_rules.clear()
+ try:
+ with caplog.at_level(logging.WARNING, logger="iot"):
+ iot_module.put_topic_rule("kw_rule", {"sql": sql})
+ assert not caplog.records
+ finally:
+ iot_module._topic_rules.clear()
+ reset()
+
+
+def test_reset_clears_the_sql_function_warning_ledger():
+ """`_warned_sql_funcs` makes the unimplemented-function warning fire once
+ per name, so it is module state the service reset has to clear — otherwise
+ the second test to store the same rule silently gets no warning."""
+ from ministack.services import iot as iot_module
+
+ try:
+ iot_module._warn_unimplemented_sql_function("get_thing_shadow")
+ assert iot_module._warned_sql_funcs
+ iot_module.reset()
+ assert not iot_module._warned_sql_funcs
+ finally:
+ iot_module.reset()
+
+
+def test_like_and_regexp_matches_convert_operands_alike():
+ """The two string operators take the same operand policy.
+
+ They used to disagree — `regexp_matches` coerced with str() while LIKE
+ demanded a Python string — so the same Int payload matched one and not the
+ other. Both now run AWS's documented "to String" conversion, which renders
+ an Int and a Boolean (lowercase, as JSON does) and leaves Null Undefined.
+ """
+ from ministack.services.iot import _eval_where, _rule_message
+
+ def both(attr, payload):
+ raw = json.dumps(payload).encode()
+ message = _rule_message(raw)
+ return (
+ _eval_where(f"{attr} LIKE '2%'", "a/b", raw, message),
+ _eval_where(f"regexp_matches({attr}, '^2')", "a/b", raw, message),
+ )
+
+ assert both("temp", {"temp": 22}) == (True, True)
+ assert both("temp", {"temp": "22"}) == (True, True)
+ assert both("temp", {"temp": 22.5}) == (True, True)
+ assert both("temp", {"temp": 31}) == (False, False)
+ assert both("temp", {"temp": None}) == (False, False)
+ assert both("temp", {"other": 1}) == (False, False)
+
+
+def test_eval_where_warns_when_a_stored_predicate_cannot_be_parsed(caplog):
+ """Validation keeps these out of the store, but state restored from an older
+ MiniStack can carry one — it must be loud, not a silent non-match."""
+ from ministack.services.iot import _eval_where, _rule_message
+
+ raw = b'{"state": "on"}'
+ with caplog.at_level(logging.WARNING, logger="iot_broker"):
+ assert _eval_where("(state = 'on'", "a/b", raw, _rule_message(raw)) is False
+ assert any("cannot be parsed" in r.message for r in caplog.records)
+
+
+def test_run_rule_actions_where_gates_dispatch(monkeypatch):
+ """A WHERE-carrying rule dispatches only the matching publishes."""
+ from ministack.services import iot as iot_module
+
+ reset()
+ iot_module._topic_rules.clear()
+ account_id = "123456789012"
+ iot_module._topic_rules.set_scoped(
+ account_id,
+ _TEST_REGION,
+ "gated_rule",
+ {
+ "ruleName": "gated_rule",
+ "sql": "SELECT * FROM 'sensors/#' WHERE state = 'on'",
+ "ruleDisabled": False,
+ "actions": [{"lambda": {"functionArn": "arn:aws:lambda:us-east-1:123456789012:function:sink"}}],
+ },
+ )
+ dispatched = []
+ monkeypatch.setattr(
+ iot_module,
+ "_dispatch_rule_to_lambda",
+ lambda account, region, arn, event: dispatched.append(event),
+ )
+
+ async def _run():
+ await publish(account_id, "sensors/door", b'{"state": "on", "n": 1}')
+ await publish(account_id, "sensors/door", b'{"state": "off", "n": 2}')
+ await publish(account_id, "sensors/door", b'{"n": 3}') # attribute missing
+
+ try:
+ asyncio.run(_run())
+ assert dispatched == [{"state": "on", "n": 1}]
+ finally:
+ iot_module._topic_rules.clear()
+ reset()
+
+
+# ----------------------------------------------------------------------
+# Rule action dispatch: republish / dynamoDBv2 / sns (white-box).
+# ----------------------------------------------------------------------
+
+
+def _put_rule(account_id, name, sql, actions):
+ from ministack.services import iot as iot_module
+
+ iot_module._topic_rules.set_scoped(
+ account_id,
+ _TEST_REGION,
+ name,
+ {"ruleName": name, "sql": sql, "ruleDisabled": False, "actions": actions},
+ )
+
+
+def test_rule_republish_action_delivers_projected_event():
+ from ministack.services import iot as iot_module
+
+ reset()
+ iot_module._topic_rules.clear()
+ account_id = "123456789012"
+ _put_rule(
+ account_id,
+ "repub_rule",
+ "SELECT temp AS t FROM 'sensors/+/telemetry' WHERE temp > 20",
+ [{"republish": {"topic": "filtered/telemetry", "qos": 1}}],
+ )
+ received = []
+
+ async def _run():
+ async def _collect(topic, payload, qos):
+ received.append((topic, payload, qos))
+
+ await subscribe(account_id, "filtered/telemetry", _collect, granted_qos=1)
+ await publish(account_id, "sensors/a1/telemetry", b'{"temp": 22}')
+ await publish(account_id, "sensors/a1/telemetry", b'{"temp": 19}') # WHERE gates
+
+ try:
+ asyncio.run(_run())
+ assert len(received) == 1
+ topic, payload, _qos = received[0]
+ assert topic == "filtered/telemetry"
+ assert json.loads(payload) == {"t": 22}
+ finally:
+ iot_module._topic_rules.clear()
+ reset()
+
+
+def test_rule_republish_onto_own_topic_terminates():
+ """A rule republishing onto its own topic filter is user error, but the
+ broker must cut the chain instead of recursing forever."""
+ from ministack.services import iot as iot_module
+
+ reset()
+ iot_module._topic_rules.clear()
+ account_id = "123456789012"
+ _put_rule(
+ account_id,
+ "loop_rule",
+ "SELECT * FROM 'loop/topic'",
+ [{"republish": {"topic": "loop/topic"}}],
+ )
+ received = []
+
+ async def _run():
+ async def _collect(topic, payload, qos):
+ received.append(payload)
+
+ await subscribe(account_id, "loop/topic", _collect)
+ await publish(account_id, "loop/topic", b'{"n": 1}')
+
+ try:
+ asyncio.run(_run())
+ # The original publish plus one republish per allowed depth.
+ assert len(received) == 1 + iot_module._MAX_REPUBLISH_DEPTH
+ finally:
+ iot_module._topic_rules.clear()
+ reset()
+
+
+def test_rule_action_failure_does_not_kill_the_loop(monkeypatch):
+ """A failing action is logged and the remaining actions still dispatch."""
+ from ministack.services import iot as iot_module
+
+ reset()
+ iot_module._topic_rules.clear()
+ account_id = "123456789012"
+ _put_rule(
+ account_id,
+ "multi_rule",
+ "SELECT * FROM 'multi/topic'",
+ [
+ {"sns": {"targetArn": "arn:aws:sns:us-east-1:123456789012:absent-topic"}},
+ {"dynamoDBv2": {"putItem": {"tableName": "absent-table"}}},
+ {"lambda": {"functionArn": "arn:aws:lambda:us-east-1:123456789012:function:sink"}},
+ ],
+ )
+ dispatched = []
+ monkeypatch.setattr(
+ iot_module,
+ "_dispatch_rule_to_lambda",
+ lambda account, region, arn, event: dispatched.append(event),
+ )
+
+ def _boom(*args, **kwargs):
+ raise RuntimeError("dispatch blew up")
+
+ # First action targets a missing SNS topic (raises on its own), second one
+ # is made to raise outright — the lambda action after both must still
+ # dispatch.
+ monkeypatch.setattr(iot_module, "_dispatch_rule_dynamodb", _boom)
+
+ async def _run():
+ await publish(account_id, "multi/topic", b'{"ok": 1}')
+
+ try:
+ asyncio.run(_run())
+ assert dispatched == [{"ok": 1}]
+ finally:
+ iot_module._topic_rules.clear()
+ reset()
+
+
+def test_rule_sns_action_writes_a_full_sns_message_record():
+ """The dispatcher publishes through SNS's own internal path, so the stored
+ record carries every field an HTTP `Publish` writes — a hand-rolled append
+ here would quietly drop the ones a subscription filter policy reads."""
+ from ministack.services import iot as iot_module
+ from ministack.services import sns as sns_module
+
+ reset()
+ iot_module._topic_rules.clear()
+ account_id = "123456789012"
+ topic_arn = f"arn:aws:sns:{_TEST_REGION}:{account_id}:rule-sink"
+ sns_module._topics.set_scoped(
+ account_id,
+ _TEST_REGION,
+ topic_arn,
+ {"arn": topic_arn, "messages": [], "subscriptions": [], "attributes": {}},
+ )
+ _put_rule(
+ account_id,
+ "sns_rule",
+ "SELECT temp FROM 'sensors/+/telemetry'",
+ [{"sns": {"targetArn": topic_arn}}],
+ )
+
+ async def _run():
+ await publish(account_id, "sensors/a1/telemetry", b'{"temp": 22, "n": 1}')
+
+ try:
+ asyncio.run(_run())
+ stored = sns_module._topics.get_scoped(account_id, _TEST_REGION, topic_arn)
+ assert len(stored["messages"]) == 1
+ record = stored["messages"][0]
+ assert json.loads(record["message"]) == {"temp": 22}
+ assert set(record) == {
+ "id",
+ "message",
+ "subject",
+ "message_structure",
+ "message_attributes",
+ "timestamp",
+ }
+ finally:
+ sns_module._topics.clear()
+ iot_module._topic_rules.clear()
+ reset()
+
+
+def test_rule_error_action_runs_when_an_action_fails(monkeypatch):
+ """AWS invokes the rule's errorAction when an action fails, with the failure
+ document — without it the only trace of a broken pipeline is a local log
+ line nobody reads."""
+ from ministack.services import iot as iot_module
+
+ reset()
+ iot_module._topic_rules.clear()
+ account_id = "123456789012"
+ iot_module._topic_rules.set_scoped(
+ account_id,
+ _TEST_REGION,
+ "err_rule",
+ {
+ "ruleName": "err_rule",
+ "sql": "SELECT * FROM 'err/topic'",
+ "ruleDisabled": False,
+ "actions": [{"dynamoDBv2": {"putItem": {"tableName": "absent"}}}],
+ "errorAction": {"republish": {"topic": "err/dlq"}},
+ },
+ )
+
+ def _boom(*args, **kwargs):
+ raise RuntimeError("dispatch blew up")
+
+ monkeypatch.setattr(iot_module, "_dispatch_rule_dynamodb", _boom)
+ received = []
+
+ async def _run():
+ async def _collect(topic, payload, qos):
+ received.append(json.loads(payload))
+
+ await subscribe(account_id, "err/dlq", _collect)
+ await publish(account_id, "err/topic", b'{"n": 1}')
+
+ try:
+ asyncio.run(_run())
+ assert len(received) == 1
+ doc = received[0]
+ assert doc["ruleName"] == "err_rule"
+ assert doc["topic"] == "err/topic"
+ assert base64.b64decode(doc["base64OriginalPayload"]) == b'{"n": 1}'
+ assert doc["failures"] == [
+ {"action": "dynamoDBv2", "errorMessage": "RuntimeError: dispatch blew up"}
+ ]
+ finally:
+ iot_module._topic_rules.clear()
+ reset()
+
+
+ ("action", "action_type", "error_fragment"),
+ [
+ (
+ {"dynamoDBv2": {"putItem": {"tableName": "absent-table"}}},
+ "dynamoDBv2",
+ "absent-table",
+ ),
+ (
+ {"sns": {"targetArn": "arn:aws:sns:us-east-1:123456789012:absent-topic"}},
+ "sns",
+ "absent-topic",
+ ),
+ ],
+)
+def test_rule_error_action_runs_on_an_undeliverable_destination(
+ action, action_type, error_fragment
+):
+ """The failure that actually happens locally is a destination that is not
+ there, and it has to reach the errorAction.
+
+ Both dispatchers used to log-and-return for it, so the errorAction only ever
+ ran for a monkeypatched raise — the emulator reported a healthy pipeline
+ while dropping every message.
+ """
+ from ministack.services import iot as iot_module
+
+ reset()
+ iot_module._topic_rules.clear()
+ account_id = "123456789012"
+ iot_module._topic_rules.set_scoped(
+ account_id,
+ _TEST_REGION,
+ "undeliverable_rule",
+ {
+ "ruleName": "undeliverable_rule",
+ "sql": "SELECT * FROM 'err/topic'",
+ "ruleDisabled": False,
+ "actions": [action],
+ "errorAction": {"republish": {"topic": "err/dlq"}},
+ },
+ )
+ received = []
+
+ async def _run():
+ async def _collect(topic, payload, qos):
+ received.append(json.loads(payload))
+
+ await subscribe(account_id, "err/dlq", _collect)
+ await publish(account_id, "err/topic", b'{"n": 1}')
+
+ try:
+ asyncio.run(_run())
+ assert len(received) == 1
+ doc = received[0]
+ assert doc["ruleName"] == "undeliverable_rule"
+ assert base64.b64decode(doc["base64OriginalPayload"]) == b'{"n": 1}'
+ assert len(doc["failures"]) == 1
+ failure = doc["failures"][0]
+ assert failure["action"] == action_type
+ assert error_fragment in failure["errorMessage"]
+ finally:
+ iot_module._topic_rules.clear()
+ reset()
+
+
+def test_rule_error_action_absent_is_a_no_op(monkeypatch):
+ """A rule without an errorAction still just logs the failure."""
+ from ministack.services import iot as iot_module
+
+ reset()
+ iot_module._topic_rules.clear()
+ account_id = "123456789012"
+ _put_rule(
+ account_id,
+ "noerr_rule",
+ "SELECT * FROM 'noerr/topic'",
+ [{"dynamoDBv2": {"putItem": {"tableName": "absent"}}}],
+ )
+
+ def _boom(*args, **kwargs):
+ raise RuntimeError("dispatch blew up")
+
+ monkeypatch.setattr(iot_module, "_dispatch_rule_dynamodb", _boom)
+
+ async def _run():
+ await publish(account_id, "noerr/topic", b'{"n": 1}')
+
+ try:
+ asyncio.run(_run()) # no exception escapes
+ finally:
+ iot_module._topic_rules.clear()
+ reset()
+
+
+def test_ddb_attribute_value_mapping():
+ from ministack.services.iot import _ddb_attribute_value
+
+ assert _ddb_attribute_value(True) == {"BOOL": True}
+ assert _ddb_attribute_value(3) == {"N": "3"}
+ assert _ddb_attribute_value(2.5) == {"N": "2.5"}
+ assert _ddb_attribute_value(None) == {"NULL": True}
+ assert _ddb_attribute_value({"a": 1}) == {"S": '{"a": 1}'}
+ assert _ddb_attribute_value([1, 2]) == {"S": "[1, 2]"}
+ assert _ddb_attribute_value("x") == {"S": "x"}
diff --git a/tests/test_iot_data.py b/tests/test_iot_data.py
index 2c2b7c20..6c32f21b 100644
--- a/tests/test_iot_data.py
+++ b/tests/test_iot_data.py
@@ -872,4 +872,245 @@ def test_iot_rule_attribute_projection(iot_client, iot_data_client, lam, sqs):
)
assert _poll_sink(sqs, sink) == {"id": "d1", "device": "a1"}
+
+def test_iot_rule_where_clause_gates_dispatch(iot_client, iot_data_client, lam, sqs):
+ """Only publishes satisfying the WHERE predicate reach the rule's actions."""
+ sink = sqs.create_queue(QueueName=_unique("where-sink"))["QueueUrl"]
+ fn_arn = _make_sink_lambda(lam, sink)
+ rule = _unique("gated").replace("-", "_")
+ iot_client.create_topic_rule(
+ ruleName=rule,
+ topicRulePayload={
+ "sql": "SELECT * FROM 'alarms/+/state' WHERE severity = 'high' AND count > 1",
+ "actions": [{"lambda": {"functionArn": fn_arn}}],
+ },
+ )
+
+ # Non-matching: predicate false, then attribute missing entirely.
+ iot_data_client.publish(
+ topic="alarms/a1/state",
+ payload=json.dumps({"severity": "low", "count": 5}).encode(),
+ )
+ iot_data_client.publish(
+ topic="alarms/a1/state", payload=json.dumps({"count": 5}).encode()
+ )
+ # Matching.
+ iot_data_client.publish(
+ topic="alarms/a1/state",
+ payload=json.dumps({"severity": "high", "count": 2, "id": "x"}).encode(),
+ )
+
+ event = _poll_sink(sqs, sink)
+ assert event == {"severity": "high", "count": 2, "id": "x"}
+ # No further deliveries — the non-matching publishes never dispatched.
+ assert _poll_sink(sqs, sink, timeout=3) is None
+
+ iot_client.delete_topic_rule(ruleName=rule)
+
+
+def test_iot_rule_where_topic_function_under_basic_ingest(
+ iot_client, iot_data_client, lam, sqs
+):
+ """Under Basic Ingest a WHERE reading `topic(n)` sees the topic *after* the
+ `$aws/rules/<name>/` prefix, so the same predicate gates both publish paths."""
+ sink = sqs.create_queue(QueueName=_unique("bi-where-sink"))["QueueUrl"]
+ fn_arn = _make_sink_lambda(lam, sink)
+ rule = _unique("biwhere").replace("-", "_")
+ iot_client.create_topic_rule(
+ ruleName=rule,
+ topicRulePayload={
+ # The FROM filter is bypassed by Basic Ingest; the WHERE is not.
+ "sql": "SELECT * FROM 'unused' WHERE topic(2) = 'a1'",
+ "actions": [{"lambda": {"functionArn": fn_arn}}],
+ },
+ )
+
+ # topic() reports 'sensors/b7/telemetry' here — topic(2) is 'b7', so the
+ # predicate is false and nothing dispatches.
+ iot_data_client.publish(
+ topic=f"$aws/rules/{rule}/sensors/b7/telemetry",
+ payload=json.dumps({"temp": 1}).encode(),
+ )
+ # ...and 'a1' for this one, which matches. If the prefix were not stripped,
+ # topic(2) would be 'rules' for both and neither would dispatch.
+ iot_data_client.publish(
+ topic=f"$aws/rules/{rule}/sensors/a1/telemetry",
+ payload=json.dumps({"temp": 2}).encode(),
+ )
+
+ assert _poll_sink(sqs, sink) == {"temp": 2}
+ assert _poll_sink(sqs, sink, timeout=3) is None
+
+ iot_client.delete_topic_rule(ruleName=rule)
+
+
+def test_iot_rule_where_or_clause_dispatches_either_branch(
+ iot_client, iot_data_client, lam, sqs
+):
+ """An `OR` predicate fires for either branch and stays closed otherwise."""
+ sink = sqs.create_queue(QueueName=_unique("or-where-sink"))["QueueUrl"]
+ fn_arn = _make_sink_lambda(lam, sink)
+ rule = _unique("orwhere").replace("-", "_")
+ iot_client.create_topic_rule(
+ ruleName=rule,
+ topicRulePayload={
+ "sql": "SELECT * FROM 'alarms/+/state' "
+ "WHERE (severity = 'high' OR severity = 'critical') AND count > 1",
+ "actions": [{"lambda": {"functionArn": fn_arn}}],
+ },
+ )
+
+ # Neither OR branch holds.
+ iot_data_client.publish(
+ topic="alarms/a1/state",
+ payload=json.dumps({"severity": "low", "count": 5}).encode(),
+ )
+ # A branch holds but the AND-ed clause does not.
+ iot_data_client.publish(
+ topic="alarms/a1/state",
+ payload=json.dumps({"severity": "critical", "count": 1}).encode(),
+ )
+ # Second OR branch + the AND-ed clause: dispatches.
+ iot_data_client.publish(
+ topic="alarms/a1/state",
+ payload=json.dumps({"severity": "critical", "count": 4, "id": "y"}).encode(),
+ )
+
+ assert _poll_sink(sqs, sink) == {"severity": "critical", "count": 4, "id": "y"}
+ assert _poll_sink(sqs, sink, timeout=3) is None
+
+ iot_client.delete_topic_rule(ruleName=rule)
+
+
+def test_iot_rule_republish_where_gated_ws_subscriber(iot_client, iot_data_client):
+ """A WHERE-gated republish rule: a WebSocket subscriber on the republish
+ target observes only the matching publish."""
+ from conftest import patch_endpoint_dns
+
+ source = _unique("raw/alerts")
+ target = _unique("filtered/alerts")
+ rule = _unique("repub").replace("-", "_")
+ iot_client.create_topic_rule(
+ ruleName=rule,
+ topicRulePayload={
+ "sql": f"SELECT * FROM '{source}' WHERE severity = 'high'",
+ "actions": [
+ {"republish": {"topic": target, "qos": 0, "roleArn": "arn:aws:iam::000000000000:role/rule"}}
+ ],
+ },
+ )
+
+ parsed = urlparse(ENDPOINT)
+ ws_host = parsed.hostname or "localhost"
+ ws_port = parsed.port or 4566
+ ws_url = f"ws://prefix-ats.iot.us-east-1.{ws_host}:{ws_port}/mqtt"
+
+ ready = threading.Event()
+ stop = threading.Event()
+ received: list = []
+
+ with patch_endpoint_dns():
+ t = threading.Thread(
+ target=lambda: asyncio.run(
+ _ws_subscribe_and_collect(ws_url, target, ready, received, stop)
+ ),
+ daemon=True,
+ )
+ t.start()
+ assert ready.wait(timeout=5), "WebSocket subscriber did not become ready"
+
+ iot_data_client.publish(
+ topic=source, payload=json.dumps({"severity": "low", "n": 1}).encode()
+ )
+ iot_data_client.publish(
+ topic=source, payload=json.dumps({"severity": "high", "n": 2}).encode()
+ )
+
+ deadline = time.time() + 5
+ while time.time() < deadline and not received:
+ time.sleep(0.05)
+ time.sleep(0.5) # allow a (wrong) second delivery to surface
+ stop.set()
+ t.join(timeout=2)
+
+ assert len(received) == 1, f"expected exactly the matching publish, got {received}"
+ delivered_topic, delivered_payload = received[0]
+ assert delivered_topic == target
+ assert json.loads(delivered_payload) == {"severity": "high", "n": 2}
+
+ iot_client.delete_topic_rule(ruleName=rule)
+
+
+def test_iot_rule_dynamodbv2_action_puts_item(iot_client, iot_data_client, ddb):
+ table = _unique("rule-sink").replace("-", "")
+ ddb.create_table(
+ TableName=table,
+ AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
+ KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ rule = _unique("ddbrule").replace("-", "_")
+ iot_client.create_topic_rule(
+ ruleName=rule,
+ topicRulePayload={
+ "sql": "SELECT deviceId AS id, temp, active FROM 'ddb/+/telemetry'",
+ "actions": [{"dynamoDBv2": {"putItem": {"tableName": table}, "roleArn": "arn:aws:iam::000000000000:role/rule"}}],
+ },
+ )
+
+ iot_data_client.publish(
+ topic="ddb/a1/telemetry",
+ payload=json.dumps({"deviceId": "d1", "temp": 22.5, "active": True}).encode(),
+ )
+
+ items = []
+ deadline = time.time() + 10
+ while time.time() < deadline:
+ items = ddb.scan(TableName=table).get("Items", [])
+ if items:
+ break
+ time.sleep(0.2)
+ assert items == [
+ {"id": {"S": "d1"}, "temp": {"N": "22.5"}, "active": {"BOOL": True}}
+ ]
+
+ iot_client.delete_topic_rule(ruleName=rule)
+ ddb.delete_table(TableName=table)
+
+
+def test_iot_rule_sns_action_publishes_to_topic(iot_client, iot_data_client, sns, sqs):
+ topic_arn = sns.create_topic(Name=_unique("rule-sns"))["TopicArn"]
+ queue_url = sqs.create_queue(QueueName=_unique("sns-sink"))["QueueUrl"]
+ queue_arn = sqs.get_queue_attributes(
+ QueueUrl=queue_url, AttributeNames=["QueueArn"]
+ )["Attributes"]["QueueArn"]
+ sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=queue_arn)
+
+ rule = _unique("snsrule").replace("-", "_")
+ iot_client.create_topic_rule(
+ ruleName=rule,
+ topicRulePayload={
+ "sql": "SELECT * FROM 'notify/+/event'",
+ "actions": [{"sns": {"targetArn": topic_arn, "roleArn": "arn:aws:iam::000000000000:role/rule"}}],
+ },
+ )
+
+ iot_data_client.publish(
+ topic="notify/a1/event", payload=json.dumps({"kind": "boom"}).encode()
+ )
+
+ body = None
+ deadline = time.time() + 10
+ while time.time() < deadline:
+ msgs = sqs.receive_message(
+ QueueUrl=queue_url, MaxNumberOfMessages=1, WaitTimeSeconds=1
+ )
+ if msgs.get("Messages"):
+ body = json.loads(msgs["Messages"][0]["Body"])
+ break
+ assert body is not None, "SNS → SQS delivery did not arrive"
+ # Default (non-raw) delivery wraps the message in the SNS envelope.
+ message = json.loads(body["Message"]) if "Message" in body else body
+ assert message == {"kind": "boom"}
+
iot_client.delete_topic_rule(ruleName=rule)
diff --git a/tests/test_sns.py b/tests/test_sns.py
index 25f277e7..69033ed1 100644
--- a/tests/test_sns.py
+++ b/tests/test_sns.py
@@ -1839,3 +1839,218 @@ def test_sns_restore_legacy_account_scoped_state_adopts_arn_regions():
_sns._platform_endpoints._data.update(original_endpoints)
set_request_account_id(original_account)
set_request_region(original_region)
+
+
+# ---------------------------------------------------------------------------
+# publish_internal
+# ---------------------------------------------------------------------------
+#
+# The in-process seam cross-service producers (an IoT topic rule, an EventBridge
+# target) publish through. It is the only door that can see the FIFO duplicate
+# flag and the None a missing topic answers with — the HTTP `Publish` wrapper
+# folds both into its XML response — so it is exercised directly here.
+
+
+def sns_internal():
+ """An empty in-process SNS store pinned to one account and region."""
+ import ministack.services.sns as _sns
+ from ministack.core.responses import (
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+
+ original_account, original_region = get_account_id(), get_region()
+ original_topics = dict(_sns._topics._data)
+ _sns._topics.clear()
+ set_request_account_id("000000000000")
+ set_request_region("us-east-1")
+ try:
+ yield _sns
+ finally:
+ _sns._topics.clear()
+ _sns._topics._data.update(original_topics)
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+
+
+def _seed_internal_topic(_sns, name, *, attributes=None, subscriptions=()):
+ arn = f"arn:aws:sns:us-east-1:000000000000:{name}"
+ _sns._topics[arn] = {
+ "name": name,
+ "arn": arn,
+ "messages": [],
+ "subscriptions": list(subscriptions),
+ "attributes": attributes or {},
+ }
+ return arn
+
+
+def test_sns_publish_internal_stores_the_record_and_fans_out(sns_internal, monkeypatch):
+ """A publish through the seam gets everything an HTTP one gets.
+
+ The message_structure and message_attributes here are the two fields the
+ hand-rolled `topic["messages"].append(...)` this replaced used to drop, and
+ both are load-bearing: the first picks the per-protocol body, the second is
+ what a subscription filter policy reads.
+ """
+ delivered = []
+ monkeypatch.setattr(
+ sns_internal,
+ "_deliver_to_sqs",
+ lambda endpoint, envelope, raw, message, **kwargs: delivered.append(message),
+ )
+ arn = _seed_internal_topic(
+ sns_internal,
+ f"internal-{_uuid_mod.uuid4().hex[:8]}",
+ subscriptions=[{
+ "arn": f"sub-{_uuid_mod.uuid4()}",
+ "protocol": "sqs",
+ "endpoint": "arn:aws:sqs:us-east-1:000000000000:sink",
+ "confirmed": True,
+ "attributes": {},
+ }],
+ )
+ attrs = {"kind": {"DataType": "String", "StringValue": "telemetry"}}
+
+ result = sns_internal.publish_internal(
+ arn,
+ json.dumps({"default": "generic", "sqs": "for-sqs"}),
+ "a subject",
+ message_structure="json",
+ message_attributes=attrs,
+ )
+
+ assert result["duplicate"] is False
+ assert result["sequence_number"] is None
+ assert result["message_id"]
+
+ stored = sns_internal._topics[arn]["messages"]
+ assert len(stored) == 1
+ assert stored[0]["id"] == result["message_id"]
+ assert stored[0]["subject"] == "a subject"
+ assert stored[0]["message_structure"] == "json"
+ assert stored[0]["message_attributes"] == attrs
+ # message_structure picked the sqs body rather than the default one.
+ assert delivered == ["for-sqs"]
+
+
+def test_sns_publish_internal_applies_the_subscription_filter_policy(
+ sns_internal, monkeypatch
+):
+ """The message attributes reach the filter policy, so a non-matching
+ subscriber is skipped — the behaviour lost when the attributes were not
+ carried at all."""
+ delivered = []
+ monkeypatch.setattr(
+ sns_internal,
+ "_deliver_to_sqs",
+ lambda endpoint, envelope, raw, message, **kwargs: delivered.append(endpoint),
+ )
+
+ def _sub(endpoint, kind):
+ return {
+ "arn": f"sub-{_uuid_mod.uuid4()}",
+ "protocol": "sqs",
+ "endpoint": endpoint,
+ "confirmed": True,
+ "attributes": {"FilterPolicy": json.dumps({"kind": [kind]})},
+ }
+
+ arn = _seed_internal_topic(
+ sns_internal,
+ f"internal-{_uuid_mod.uuid4().hex[:8]}",
+ subscriptions=[_sub("queue-match", "telemetry"), _sub("queue-skip", "alarm")],
+ )
+
+ sns_internal.publish_internal(
+ arn,
+ "hello",
+ message_attributes={"kind": {"DataType": "String", "StringValue": "telemetry"}},
+ )
+
+ assert delivered == ["queue-match"]
+
+
+def test_sns_publish_internal_fifo_replays_a_duplicate_without_redelivering(
+ sns_internal, monkeypatch
+):
+ """The FIFO deduplication window is the one behaviour only this API can
+ observe: `Publish` returns the cached MessageId either way, so `duplicate`
+ is how a caller learns nothing was delivered the second time."""
+ delivered = []
+ monkeypatch.setattr(
+ sns_internal,
+ "_deliver_to_sqs",
+ lambda endpoint, envelope, raw, message, **kwargs: delivered.append(message),
+ )
+ arn = _seed_internal_topic(
+ sns_internal,
+ f"internal-{_uuid_mod.uuid4().hex[:8]}.fifo",
+ attributes={"FifoTopic": "true"},
+ subscriptions=[{
+ "arn": f"sub-{_uuid_mod.uuid4()}",
+ "protocol": "sqs",
+ "endpoint": "arn:aws:sqs:us-east-1:000000000000:sink.fifo",
+ "confirmed": True,
+ "attributes": {},
+ }],
+ )
+
+ first = sns_internal.publish_internal(
+ arn, "once", message_group_id="g1", message_deduplication_id="d1"
+ )
+ second = sns_internal.publish_internal(
+ arn, "once", message_group_id="g1", message_deduplication_id="d1"
+ )
+
+ assert first["duplicate"] is False
+ assert first["sequence_number"] == "1".zfill(20)
+ # The replay reports the original ids and sequence, as AWS does.
+ assert second["duplicate"] is True
+ assert second["message_id"] == first["message_id"]
+ assert second["sequence_number"] == first["sequence_number"]
+ # ...and neither the store nor the subscriber saw it twice.
+ assert len(sns_internal._topics[arn]["messages"]) == 1
+ assert delivered == ["once"]
+
+ # A different dedup id inside the same group is a new message.
+ third = sns_internal.publish_internal(
+ arn, "twice", message_group_id="g1", message_deduplication_id="d2"
+ )
+ assert third["duplicate"] is False
+ assert third["sequence_number"] == "2".zfill(20)
+ assert len(sns_internal._topics[arn]["messages"]) == 2
+
+
+def test_sns_publish_internal_rejections(sns_internal):
+ """The three answers a caller has to handle: no topic, a FIFO publish AWS
+ would reject, and a body over the size limit."""
+ assert (
+ sns_internal.publish_internal(
+ "arn:aws:sns:us-east-1:000000000000:absent", "hi"
+ )
+ is None
+ )
+
+ fifo = _seed_internal_topic(
+ sns_internal,
+ f"internal-{_uuid_mod.uuid4().hex[:8]}.fifo",
+ attributes={"FifoTopic": "true"},
+ )
+ with pytest.raises(sns_internal.SnsPublishError) as ei:
+ sns_internal.publish_internal(fifo, "hi", message_deduplication_id="d1")
+ assert ei.value.code == "InvalidParameterException"
+ assert "MessageGroupId" in str(ei.value)
+
+ # ...and with a group id but no way to derive a dedup id.
+ with pytest.raises(sns_internal.SnsPublishError) as ei:
+ sns_internal.publish_internal(fifo, "hi", message_group_id="g1")
+ assert "MessageDeduplicationId" in str(ei.value)
+
+ standard = _seed_internal_topic(sns_internal, f"internal-{_uuid_mod.uuid4().hex[:8]}")
+ with pytest.raises(sns_internal.SnsPublishError) as ei:
+ sns_internal.publish_internal(standard, "x" * (256 * 1024 + 1))
+ assert ei.value.code == "InvalidParameter"