Skip to content

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

release/v1.3.43 (#667)

Nahuel Nucera07bc7b99c1a6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5b409add..b876c135 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,21 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.3.43] — 2026-05-18
+
+### Added
+- **AWS IoT Core (Phase 1)** — new service covering the control plane and a WebSocket-only MQTT data plane. Control plane: `CreateThing` / `DescribeThing` / `ListThings` / `UpdateThing` / `DeleteThing`, `CreateThingType` and group, `CreateThingGroup` + `AddThingToThingGroup` / `RemoveThingFromThingGroup`, certificates via a new in-process Local CA (`CreateKeysAndCertificate`, `RegisterCertificate`, `UpdateCertificate`, `DeleteCertificate`, `ListCertificates`), `AttachThingPrincipal` / `DetachThingPrincipal` / `ListThingPrincipals` / `ListPrincipalThings`, policies with versioning (`CreatePolicy`, `CreatePolicyVersion`, `GetPolicyVersion`, `ListPolicyVersions`, `SetDefaultPolicyVersion`, `DeletePolicyVersion`), policy attachment (`AttachPolicy`, `DetachPolicy`, `ListAttachedPolicies`, `ListTargetsForPolicy`), and `DescribeEndpoint` returning a per-account hostname. Data plane: HTTP `iot-data Publish` at `POST /topics/{topic}` with QoS 0/1 and `?retain=true`, plus MQTT 3.1.1 over WebSocket multiplexed on the gateway port (clients use the `mqtt` Sec-WebSocket-Protocol value and connect to the address returned by `DescribeEndpoint`). Multi-tenancy enforced by transparent topic prefixing in the bridge layer — the account ID is resolved from the SigV4 credential at WebSocket upgrade and topics are prefixed before they hit the in-process pub/sub registry, so two accounts publishing to the same topic name never see each other's traffic. Persistent sessions (`cleanSession=0`), QoS 1 in-flight tracking + retransmit with DUP flag, Last Will and Testament on ungraceful disconnect, duplicate-client-id force-disconnect, and retained-message delivery on subscribe all implemented per MQTT 3.1.1. Local CA root certificate exposed at `GET /_ministack/iot/ca.pem` so test code can configure SDK trust; CA + broker state (retained messages, persistent sessions) persist across restarts when `PERSIST_STATE=1`. Deferred to later phases: Device Shadows, mTLS on 8883, `ListRetainedMessages` queries, Rules Engine, Jobs, Fleet Provisioning. IoT policy documents are stored but not enforced on the data plane. Plain TCP 1883 is intentionally not exposed (real AWS IoT requires TLS or SigV4 on every connection). Requires the `cryptography` package (declared in the `[full]` optional dependency); slim image users hit a clean `RuntimeError` on first IoT call. Contributed by @jgrumboe.
+- **Athena ↔ Glue catalog integration + S3 result persistence** — `StartQueryExecution` now resolves `database.table` references against Glue's `GetTable` to find the underlying S3 location, so queries against Glue-managed tables work without hand-written `read_csv('s3://...')` paths. Completed query results are written to the configured `OutputLocation` as `<id>.csv` plus a `<id>.csv.metadata` companion (column names + Athena-mapped types) — the CSV file includes the column-name header row as the first line, matching real Athena's output format. Mixed queries combining Glue tables with explicit `s3://` URIs in the same statement also resolve correctly. Contributed by @m7w.
+
+### Fixed
+- **EventBridge rule targets pointing at Step Functions state machines** — targets with an ARN of the form `arn:aws:states:<region>:<account>:stateMachine:<name>` previously fell through to the "unsupported target type" warning and silently dropped events. The dispatcher now calls into the existing `stepfunctions._start_execution`, which runs the execution on a daemon thread with a `contextvars.copy_context()` snapshot so the request's account context is preserved. The transformed payload (post `Input` / `InputPath` / `InputTransformer`) is passed verbatim as the execution input, so `Input*` features work for free. `RoleArn` on the target is accepted and ignored, matching how the existing Lambda/SQS/SNS dispatchers handle it. Contributed by @DaviReisVieira.
+- **Step Functions `StartExecution` accepts version and alias ARNs** — real AWS lets callers (and EventBridge targets) reference a state machine by its base ARN, a published-version ARN (`stateMachine:<name>:<version>`), or an alias ARN routed via `CreateStateMachineAlias`. Previously only the base ARN resolved — versions and aliases returned `StateMachineDoesNotExist`. A new resolver walks the base / version / alias stores; alias dispatch picks the highest-weighted version in the routing configuration (ties → first listed) for deterministic test behaviour. EventBridge → Step Functions dispatch leans on the same resolver, so EB rules pinning a target to a specific version or alias now actually fire.
+- **Athena DuckDB queries no longer stall the event loop** — `StartQueryExecution` previously scheduled the DuckDB run via `asyncio.create_task`, but DuckDB's `conn.execute()` is a blocking C call so the asyncio loop sat idle for the full query duration, stalling every other in-flight request on the single-process server. Wrapped in `asyncio.to_thread` so multiple concurrent Athena queries run on worker threads and the loop stays free.
+- **Step Functions `aws-sdk:lambda` integration** — `arn:aws:states:::aws-sdk:lambda:getAlias` and `getFunctionConfiguration` now dispatch through the Lambda REST emulator with JSONPath-resolved `FunctionName`, `Name`, and `Qualifier` parameters. Unblocks readiness workflows that verify a Lambda alias and its published version before invoking it. The dispatcher captures the caller's account ID from the request contextvar and embeds it in the synthetic Authorization header (instead of hardcoding `test`), so SFN executions running under a non-default 12-digit account correctly resolve Lambdas in their own account scope. Contributed by @jayjanssen.
+- **Lambda published-version readiness propagates from `$LATEST`** — published version snapshots created while `$LATEST` is still `Pending/InProgress` now transition to `Active/Successful` with the function, so `GetFunctionConfiguration --qualifier <version>` converges instead of staying stuck after the alias points at the version. Contributed by @jayjanssen.
+
+---
+
## [1.3.42] — 2026-05-16
### Added
@@ -18,10 +33,6 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Changed
- **Test harness — xdist session-startup reset coordination** — the per-worker `autouse` `reset_server` fixture previously had every xdist worker hit `/_ministack/reset` on session start, so a slower worker's reset could fire after a faster worker had already begun creating fixtures, wiping that state mid-test (most visibly as occasional `list_functions()` empty results in `test_lambda_create_invoke`). The first worker now wins an `O_EXCL` file lock and runs the reset; the others wait briefly for a marker file and skip. Single-process pytest (no xdist) keeps the original behaviour. Removes a class of CI flakes that only reproduced under parallel load.
-### Fixed
-- **Step Functions Lambda AWS SDK integrations** — `arn:aws:states:::aws-sdk:lambda:getAlias` and `getFunctionConfiguration` now dispatch through the Lambda REST emulator, including JSONPath-resolved `FunctionName`, `Name`, and `Qualifier` parameters. This unblocks readiness workflows that verify a Lambda alias and its published version before invoking it.
-- **Lambda published-version readiness** — published version snapshots created while `$LATEST` is still `Pending/InProgress` now transition to `Active/Successful` with the function, so `GetFunctionConfiguration --qualifier <version>` converges instead of staying stuck after the alias points at the version.
-
---
## [1.3.41] — 2026-05-16
diff --git a/README.md b/README.md
index 1a7fe9a5..4073d5a4 100644
--- a/README.md
+++ b/README.md
@@ -1005,7 +1005,7 @@ pip install boto3 pytest duckdb docker cbor2
# Start MiniStack
docker compose up -d
-# Run the full test suite (2,400+ tests across all services)
+# Run the full test suite (2,500+ tests across all services)
pytest tests/ -v
```
diff --git a/ministack/app.py b/ministack/app.py
index ea9b261b..cde6f013 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -41,9 +41,14 @@ _EXECUTE_API_RE = re.compile(
# AppSync Events realtime WebSocket: {apiId}.appsync-realtime-api.<anything>[:port].
_APPSYNC_REALTIME_RE = re.compile(r"^([a-z0-9]+)\.appsync-realtime-api\.")
# IoT data plane WebSocket: anything containing ".iot." in the host header.
-# Match all four AWS-shaped variants (data-ats.iot, data.iot, plain iot, plus
-# an account-prefixed iot endpoint as returned by DescribeEndpoint).
-_IOT_DATA_WS_RE = re.compile(r"\.iot\.")
+# Match AWS-shaped IoT hosts only — `iot.<region>.<host>`,
+# `data-ats.iot.<region>.<host>`, `data.iot.<region>.<host>`, and the
+# account-prefixed endpoint returned by DescribeEndpoint
+# (`<prefix>.iot.<region>.<host>`). Anchored at a host-segment boundary
+# (start-of-host or after a dot) so custom domains that happen to contain
+# `.iot.` as a substring (e.g. an S3 bucket `mybucket.iot.example.com`) are
+# not misrouted into the MQTT WebSocket handler.
+_IOT_DATA_WS_RE = re.compile(r"(^|\.)iot\.[a-z0-9-]+\.")
def _ws_has_mqtt_subprotocol(ws_headers: dict) -> bool:
diff --git a/ministack/services/athena.py b/ministack/services/athena.py
index 3ba16170..19a0e2fc 100644
--- a/ministack/services/athena.py
+++ b/ministack/services/athena.py
@@ -322,69 +322,83 @@ async def _execute_query(query_id, query, database):
async def _run_duckdb(query, database):
+ """Run a DuckDB query off the event loop.
+
+ DuckDB's ``conn.execute()`` is a blocking C-extension call — running it
+ directly on the asyncio loop stalls every other in-flight request for
+ the duration of the query. Offload to a worker thread via
+ ``asyncio.to_thread`` so multiple concurrent Athena queries on the
+ single-process server stay non-blocking.
+ """
import duckdb
- conn = duckdb.connect(":memory:")
rewritten = await _rewrite_data_paths(query, database)
- try:
- result = conn.execute(rewritten)
- columns = []
- column_types = []
- if result.description:
- for desc in result.description:
- columns.append(desc[0])
- raw_type = desc[1] if len(desc) > 1 else "VARCHAR"
- if isinstance(raw_type, str):
- type_key = raw_type.upper().split("(")[0].strip()
- else:
- type_key = str(raw_type).upper().split("(")[0].strip()
- athena_type = _DUCKDB_TYPE_MAP.get(type_key, "varchar")
- column_types.append(athena_type)
- rows = result.fetchall()
- conn.close()
- return {
- "columns": columns,
- "column_types": column_types,
- "rows": [list(r) for r in rows],
- }
- except Exception as e:
- conn.close()
- raise e
+ def _execute_blocking():
+ conn = duckdb.connect(":memory:")
+ try:
+ result = conn.execute(rewritten)
+ columns = []
+ column_types = []
+ if result.description:
+ for desc in result.description:
+ columns.append(desc[0])
+ raw_type = desc[1] if len(desc) > 1 else "VARCHAR"
+ if isinstance(raw_type, str):
+ type_key = raw_type.upper().split("(")[0].strip()
+ else:
+ type_key = str(raw_type).upper().split("(")[0].strip()
+ athena_type = _DUCKDB_TYPE_MAP.get(type_key, "varchar")
+ column_types.append(athena_type)
+ rows = result.fetchall()
+ return {
+ "columns": columns,
+ "column_types": column_types,
+ "rows": [list(r) for r in rows],
+ }
+ finally:
+ conn.close()
+
+ return await asyncio.to_thread(_execute_blocking)
async def _rewrite_data_paths(query, database):
from ministack.services import glue as glue_svc
- pattern = r'(?:FROM|JOIN)\s+([a-zA-Z0-9_".\-/]+(?:\(.*?\))?)'
+ # Skip identifiers that look like function calls (read_csv('s3://...'))
+ # or already contain a path separator. Restrict to bare table references
+ # — optional database qualifier, then table name — letters/digits/dots/
+ # underscores/hyphens. Quoted identifiers (e.g. "my-db"."my-table") are
+ # left to a future pass.
+ pattern = r'(?:FROM|JOIN)\s+([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)?)\b'
tables_to_resolve = re.findall(pattern, query, re.IGNORECASE)
for full_name in tables_to_resolve:
- if "/" in full_name or "(" in full_name:
- continue
-
parts = full_name.split(".")
db_name, table_name = (parts[0], parts[1]) if len(parts) > 1 else (database or "default", parts[0])
- body = json.dumps({"DatabaseName": db_name, "Name": table_name}).encode("utf-8")
- headers = {"x-amz-target": "AWSGlue.GetTable"}
- status, _, response_body = await glue_svc.handle_request("POST", "/", headers, body, {})
+ # Read directly from glue's internal store rather than going through
+ # the HTTP handler. The store is account-scoped via AccountScopedDict
+ # and reads the current request's contextvar, so multi-tenancy is
+ # preserved without crafting synthetic Authorization headers.
+ table_data = glue_svc._tables.get(f"{db_name}/{table_name}")
+ if not table_data:
+ continue
- if status == 200:
- table_data = json.loads(response_body).get("Table", {})
- sd = table_data.get('StorageDescriptor', {})
- s3_location = sd.get("Location")
+ sd = table_data.get("StorageDescriptor", {})
+ s3_location = sd.get("Location")
+ if not s3_location:
+ continue
- if s3_location:
- account_id = get_account_id()
- p = urlparse(s3_location)
- stripped = f"{p.netloc}{p.path}".rstrip("/")
- classification = table_data.get("Parameters", {}).get("classification", "csv")
+ account_id = get_account_id()
+ p = urlparse(s3_location)
+ stripped = f"{p.netloc}{p.path}".rstrip("/")
+ classification = table_data.get("Parameters", {}).get("classification", "csv")
- local_path = f"{ATHENA_DATA_DIR}/{account_id}/{stripped}"
- duck_path = f"{local_path}/**/*.{classification}"
+ local_path = f"{ATHENA_DATA_DIR}/{account_id}/{stripped}"
+ duck_path = f"{local_path}/**/*.{classification}"
- query = re.sub(rf"{re.escape(full_name)}", f"'{duck_path}'", query)
+ query = re.sub(rf"\b{re.escape(full_name)}\b", f"'{duck_path}'", query)
query = _rewrite_s3_paths(query)
return query
@@ -433,6 +447,10 @@ async def _save_query_results(query_id):
output = io.StringIO()
writer = csv.writer(output)
+ # Real Athena writes the column names as the first row of the result
+ # CSV; downstream consumers (Glue crawlers, csv readers using
+ # header=True, BI tools) rely on it.
+ writer.writerow(results['columns'])
writer.writerows(results['rows'])
csv_content = output.getvalue().encode("utf-8")
@@ -442,36 +460,44 @@ async def _save_query_results(query_id):
output_location = execution["ResultConfiguration"]["OutputLocation"]
p = urlparse(output_location)
- local_path = f"{p.netloc}{p.path}".rstrip("/")
-
- async def upload(path, data):
- account_id = get_account_id()
- aws_region = get_region()
- dt = date.today().strftime("%Y%m%d")
-
- credential = f"{account_id}/{dt}/{aws_region}/s3/aws4_request"
-
- headers = {
- "content-type": "application/octet-stream",
- "content-length": str(len(data)),
- "x-amz-account-id": account_id,
- "Authorization": f"AWS4-HMAC-SHA256 Credential={credential}"
- }
- status, _, body = await s3_svc.handle_request("PUT", path, headers, data, {})
- if status != 200:
+ bucket_name = p.netloc
+ key_prefix = p.path.lstrip("/").rstrip("/")
+ # Athena writes <id>.csv and <id>.csv.metadata under the OutputLocation
+ # prefix. If the prefix is empty (output_location == "s3://bucket/"),
+ # the files land at bucket root.
+ csv_key = f"{key_prefix}/{query_id}.csv" if key_prefix else f"{query_id}.csv"
+ meta_key = f"{csv_key}.metadata"
+
+ # Write directly to the S3 service's in-memory store via the public
+ # internal helper, which is account-scoped through the request's
+ # contextvar — no synthetic Authorization header needed and no
+ # round-trip through the HTTP handler.
+ def _upload(key, data, content_type):
+ resp = s3_svc._put_object(
+ bucket_name,
+ key,
+ data,
+ {"content-type": content_type, "content-length": str(len(data))},
+ )
+ # _put_object returns (status, headers, body) on error; a successful
+ # write returns the same tuple with status 200. Surface any failure
+ # onto the execution so callers see the cause via GetQueryExecution.
+ if isinstance(resp, tuple) and resp[0] >= 300:
try:
- root = ET.fromstring(body)
+ root = ET.fromstring(resp[2])
code = root.findtext("Code", "UnknownError")
message = root.findtext("Message", "An unexpected S3 error occurred")
except Exception:
code, message = "InternalError", "Failed to parse S3 error response"
execution["Status"]["State"] = "FAILED"
- execution["Status"]["StateChangeReason"] = f"An error occurred while writing to S3. {code}: {message}"
+ execution["Status"]["StateChangeReason"] = (
+ f"An error occurred while writing to S3. {code}: {message}"
+ )
return False
return True
- if await upload(local_path, csv_content):
- await upload(f"{local_path}.metadata", metadata_content)
+ if _upload(csv_key, csv_content, "text/csv"):
+ _upload(meta_key, metadata_content, "text/plain")
def _mock_query_results(query):
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index 50c4653a..99343c87 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -1098,7 +1098,11 @@ def _dispatch_to_sns(arn, payload):
def _dispatch_to_stepfunctions(arn, payload):
from ministack.services import stepfunctions as _sfn
- if arn not in _sfn._state_machines:
+ # Accept all three SFN target ARN shapes EventBridge supports in real
+ # AWS: base state machine, published version, and alias. The resolver
+ # walks all three stores; ``None`` means the target ARN doesn't match
+ # any state machine the caller's account can see.
+ if _sfn._resolve_state_machine_arn(arn) is None:
logger.warning("EventBridge → Step Functions: state machine %s not found", arn)
return
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index ef3550a1..c220f073 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -486,6 +486,41 @@ def _list_state_machines(data):
# Execution lifecycle
# ---------------------------------------------------------------------------
+def _resolve_state_machine_arn(arn):
+ """Resolve a state-machine, version, or alias ARN to the base state-machine
+ ARN. Returns None when the ARN doesn't match anything in any of the three
+ stores.
+
+ Real AWS accepts all three shapes wherever a ``stateMachineArn`` is taken
+ (StartExecution, DescribeExecution, EventBridge target Arn, …):
+
+ * ``arn:aws:states:<r>:<a>:stateMachine:<name>`` — base
+ * ``arn:aws:states:<r>:<a>:stateMachine:<name>:<version>`` — published version
+ * ``arn:aws:states:<r>:<a>:stateMachine:<name>:<alias>`` — alias
+
+ For an alias, we pick the highest-weighted version in the routing config
+ and resolve that version back to its base state machine.
+ """
+ if arn in _state_machines:
+ return arn
+ version = _state_machine_versions.get(arn)
+ if version:
+ return version.get("stateMachineArn")
+ alias = _state_machine_aliases.get(arn)
+ if alias:
+ routing = alias.get("routingConfiguration") or []
+ # AWS picks one of the configured versions by weight on each
+ # invocation. For determinism in test contexts we pick the
+ # highest-weighted entry (ties → first listed).
+ if routing:
+ chosen = max(routing, key=lambda r: r.get("weight", 0))
+ version_arn = chosen.get("stateMachineVersionArn", "")
+ ver = _state_machine_versions.get(version_arn)
+ if ver:
+ return ver.get("stateMachineArn")
+ return None
+
+
def _start_execution(data):
sm_arn_raw = data.get("stateMachineArn", "")
# Support #TestCaseName suffix for mock config
@@ -494,10 +529,12 @@ def _start_execution(data):
sm_arn, test_case = sm_arn_raw.rsplit("#", 1)
else:
sm_arn = sm_arn_raw
- if sm_arn not in _state_machines:
+ base_arn = _resolve_state_machine_arn(sm_arn)
+ if base_arn is None:
return error_response_json(
"StateMachineDoesNotExist",
f"State machine {sm_arn} not found", 400)
+ sm_arn = base_arn
sm = _state_machines[sm_arn]
name = data.get("name") or new_uuid()
@@ -3728,28 +3765,43 @@ def _dispatch_aws_sdk_lambda_rest(service_info, service_name, action, input_data
"(lambda REST dispatcher covers getAlias and getFunctionConfiguration)",
)
+ # Embed the current SFN execution's account ID as the access-key segment
+ # of the synthetic Authorization header so the called handler resolves to
+ # the same account the execution is running in. Hardcoding "test" here
+ # would force every aws-sdk:lambda call into the default account and break
+ # any non-default-account caller. ``app.py`` parses the credential scope
+ # and only treats a 12-digit access key as an account override, so a
+ # default-account caller still resolves correctly.
+ caller_account = get_account_id()
headers = {
"content-type": "application/json",
"host": f"{service_key}.{get_region()}.amazonaws.com",
"authorization": (
- f"AWS4-HMAC-SHA256 Credential=test/20260101/{get_region()}/{service_key}/aws4_request"
+ f"AWS4-HMAC-SHA256 Credential={caller_account}/20260101/"
+ f"{get_region()}/{service_key}/aws4_request"
),
}
+ # Drive the async handler synchronously. SFN state execution runs inside
+ # the request's event loop, so spawning a fresh loop here would raise
+ # "Cannot run the event loop while another loop is running". The Lambda
+ # REST handlers we dispatch to (GetAlias, GetFunctionConfiguration) only
+ # touch in-memory dicts and never await, so a single ``coro.send(None)``
+ # completes via ``StopIteration`` with the response tuple.
coro = handler("GET", path, headers, b"", query_params)
try:
coro.send(None)
except StopIteration as stop:
status, resp_headers, resp_body = stop.value
else:
+ # Fallback for an async handler that does await — extremely rare on
+ # this dispatch surface, but guard so we don't return None silently.
coro.close()
- loop = asyncio.new_event_loop()
- try:
- status, resp_headers, resp_body = loop.run_until_complete(
- handler("GET", path, headers, b"", query_params)
- )
- finally:
- loop.close()
+ raise _ExecutionError(
+ "States.Runtime",
+ f"aws-sdk:{service_name}:{action} handler awaited unexpectedly; "
+ "cannot drive from sync SFN executor",
+ )
decoded = resp_body.decode("utf-8") if isinstance(resp_body, bytes) else resp_body
if status >= 400:
diff --git a/pyproject.toml b/pyproject.toml
index f2d947b0..0c14e28d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.3.42"
+version = "1.3.43"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_eventbridge.py b/tests/test_eventbridge.py
index 74fd3bd0..16b1d126 100644
--- a/tests/test_eventbridge.py
+++ b/tests/test_eventbridge.py
@@ -296,6 +296,76 @@ def test_eventbridge_stepfunctions_target(eb, sfn):
sfn.delete_state_machine(stateMachineArn=sm_arn)
+def test_eventbridge_stepfunctions_version_and_alias_targets(eb, sfn):
+ """EventBridge accepts both published-version and alias ARNs as SFN targets.
+
+ Real AWS dispatches `PutEvents` to a `stateMachine:<name>:<version>` or
+ `stateMachine:<name>:<alias>` target. The resolver in stepfunctions walks
+ base / version / alias stores so both forms reach the right executor.
+ """
+ sm_name = f"intg-eb-sfn-vers-{_uuid_mod.uuid4().hex[:8]}"
+ bus_name = f"intg-eb-bus-{_uuid_mod.uuid4().hex[:8]}"
+
+ sm_arn = sfn.create_state_machine(
+ name=sm_name,
+ definition=json.dumps({
+ "StartAt": "Done",
+ "States": {"Done": {"Type": "Pass", "End": True}},
+ }),
+ roleArn="arn:aws:iam::000000000000:role/sfn-role",
+ )["stateMachineArn"]
+
+ pub = sfn.publish_state_machine_version(stateMachineArn=sm_arn)
+ version_arn = pub["stateMachineVersionArn"]
+ alias = sfn.create_state_machine_alias(
+ name="live",
+ routingConfiguration=[{
+ "stateMachineVersionArn": version_arn,
+ "weight": 100,
+ }],
+ )
+ alias_arn = alias["stateMachineAliasArn"]
+
+ eb.create_event_bus(Name=bus_name)
+
+ for target_arn, marker in [(version_arn, "vers"), (alias_arn, "alias")]:
+ rule_name = f"intg-eb-rule-{marker}-{_uuid_mod.uuid4().hex[:6]}"
+ eb.put_rule(
+ Name=rule_name,
+ EventBusName=bus_name,
+ EventPattern=json.dumps({"source": [f"myapp.{marker}"]}),
+ State="ENABLED",
+ )
+ eb.put_targets(
+ Rule=rule_name,
+ EventBusName=bus_name,
+ Targets=[{"Id": f"sfn-{marker}", "Arn": target_arn}],
+ )
+ eb.put_events(Entries=[{
+ "Source": f"myapp.{marker}",
+ "DetailType": "PingEvent",
+ "Detail": json.dumps({"marker": marker}),
+ "EventBusName": bus_name,
+ }])
+
+ # The base state machine should accumulate one execution per dispatch.
+ deadline = time.time() + 5
+ while time.time() < deadline:
+ execs = sfn.list_executions(stateMachineArn=sm_arn)["executions"]
+ if len(execs) >= 2:
+ break
+ time.sleep(0.1)
+ assert len(execs) >= 2, (
+ f"version+alias targets should each have dispatched an execution; got {len(execs)}"
+ )
+
+ # Cleanup
+ eb.delete_event_bus(Name=bus_name)
+ sfn.delete_state_machine_alias(stateMachineAliasArn=alias_arn)
+ sfn.delete_state_machine_version(stateMachineVersionArn=version_arn)
+ sfn.delete_state_machine(stateMachineArn=sm_arn)
+
+
# Migrated from test_eb.py
def test_eventbridge_create_event_bus_v2(eb):
resp = eb.create_event_bus(Name="eb-bus-v2")
diff --git a/tests/test_iot.py b/tests/test_iot.py
index afb40d48..d373efd7 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -425,3 +425,1311 @@ def test_iot_account_isolation():
b_things = {t["thingName"] for t in b.list_things().get("things", [])}
assert name not in b_things
a.delete_thing(thingName=name)
+
+
+# ----------------------------------------------------------------------
+# Broker unit-test helpers (white-box tests for the in-process MQTT
+# broker that lives in iot.py). Section headers below mark logical
+# groupings: LWT (Last Will and Testament), persistent sessions
+# (cleanSession=0), and QoS 1 delivery / retransmits.
+# ----------------------------------------------------------------------
+
+import asyncio
+import struct
+
+from ministack.services.iot import (
+ PKT_CONNACK,
+ PKT_CONNECT,
+ PKT_DISCONNECT,
+ PKT_PUBACK,
+ PKT_PUBLISH,
+ PKT_SUBSCRIBE,
+ _InFlightMessage,
+ _RETRANSMIT_INTERVAL_SECONDS,
+ _Subscription,
+ _WSSession,
+ _encode_remaining_length,
+ _encode_string,
+ _make_puback,
+ _make_suback,
+ _persistent_sessions,
+ broker_publish as publish,
+ broker_reset as reset,
+ broker_subscribe as subscribe,
+)
+
+
+def _build_connect_body(
+ client_id="test",
+ clean_session=True,
+ will_flag=False,
+ will_qos=0,
+ will_retain=False,
+ will_topic="",
+ will_message=b"",
+):
+ """Build a CONNECT packet body (variable header + payload)."""
+ body = bytearray()
+ body += _encode_string("MQTT") # Protocol Name
+ body.append(4) # Protocol Level (MQTT 3.1.1)
+ flags = 0
+ if clean_session:
+ flags |= 0x02
+ if will_flag:
+ flags |= 0x04
+ flags |= (will_qos & 0x03) << 3
+ if will_retain:
+ flags |= 0x20
+ body.append(flags)
+ body += struct.pack("!H", 60) # Keep Alive
+ body += _encode_string(client_id)
+ if will_flag:
+ body += _encode_string(will_topic)
+ msg = will_message if isinstance(will_message, bytes) else will_message.encode()
+ body += struct.pack("!H", len(msg)) + msg
+ return bytes(body)
+
+
+def _build_subscribe_body(packet_id, topics_qos):
+ """Build a SUBSCRIBE packet body. topics_qos is a list of (topic, qos)."""
+ body = struct.pack("!H", packet_id)
+ for topic, qos in topics_qos:
+ body += _encode_string(topic)
+ body += bytes([qos])
+ return body
+
+
+def _mock_send():
+ """Return (async send-callable, captured-message list)."""
+ sent = []
+
+ async def send(msg):
+ sent.append(msg)
+
+ return send, sent
+
+
+def _parse_connack(sent_messages):
+ """Extract (sessionPresent, return_code) from a CONNACK in sent messages."""
+ for msg in sent_messages:
+ data = msg.get("bytes")
+ if data and len(data) >= 4:
+ pkt_type = (data[0] >> 4) & 0x0F
+ if pkt_type == PKT_CONNACK:
+ session_present = bool(data[2] & 0x01)
+ return_code = data[3]
+ return session_present, return_code
+ return None, None
+
+
+def _extract_publish_frames(sent_messages):
+ """Return list of (topic, payload, qos, packet_id, dup) for every PUBLISH in sent messages."""
+ results = []
+ for msg in sent_messages:
+ data = msg.get("bytes")
+ if data is None or not data:
+ continue
+ first = data[0]
+ pkt_type = (first >> 4) & 0x0F
+ if pkt_type != 3: # 3 = PUBLISH
+ continue
+ qos = (first >> 1) & 0x03
+ dup = bool(first & 0x08)
+ offset = 1
+ multiplier = 1
+ remaining = 0
+ while True:
+ b = data[offset]
+ offset += 1
+ remaining += (b & 0x7F) * multiplier
+ if b & 0x80 == 0:
+ break
+ multiplier *= 128
+ topic_len = struct.unpack_from("!H", data, offset)[0]
+ offset += 2
+ topic = data[offset:offset + topic_len].decode("utf-8")
+ offset += topic_len
+ packet_id = None
+ if qos > 0:
+ packet_id = struct.unpack_from("!H", data, offset)[0]
+ offset += 2
+ payload = data[offset:]
+ results.append((topic, payload, qos, packet_id, dup))
+ return results
+
+
+# ----------------------------------------------------------------------
+# Broker — Last Will and Testament
+# ----------------------------------------------------------------------
+
+
+
+def test_will_fields_parsed_from_connect():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(
+ client_id="device1",
+ will_flag=True,
+ will_qos=1,
+ will_retain=True,
+ will_topic="devices/device1/status",
+ will_message=b"offline",
+ )
+ result = await session.handle_packet(PKT_CONNECT, 0, body)
+ assert result is True
+ assert session._will_topic == "devices/device1/status"
+ assert session._will_message == b"offline"
+ assert session._will_qos == 1
+ assert session._will_retain is True
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_no_will_when_flag_not_set():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(client_id="device2", will_flag=False)
+ await session.handle_packet(PKT_CONNECT, 0, body)
+ assert session._will_topic is None
+ assert session._will_message is None
+ assert session._will_qos == 0
+ assert session._will_retain is False
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_graceful_disconnect_does_not_publish_will():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(
+ client_id="device3",
+ will_flag=True,
+ will_qos=0,
+ will_retain=False,
+ will_topic="devices/device3/status",
+ will_message=b"offline",
+ )
+ await session.handle_packet(PKT_CONNECT, 0, body)
+
+ received = []
+
+ async def on_msg(topic, payload, qos):
+ received.append((topic, payload, qos))
+
+ await subscribe("123456789012", "devices/device3/status", on_msg)
+
+ # Graceful disconnect
+ result = await session.handle_packet(PKT_DISCONNECT, 0, b"")
+ assert result is False
+ assert session._graceful_disconnect is True
+ await session.cleanup()
+ assert len(received) == 0
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_ungraceful_disconnect_publishes_will():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(
+ client_id="device4",
+ will_flag=True,
+ will_qos=1,
+ will_retain=False,
+ will_topic="devices/device4/status",
+ will_message=b"gone",
+ )
+ await session.handle_packet(PKT_CONNECT, 0, body)
+
+ received = []
+
+ async def on_msg(topic, payload, qos):
+ received.append((topic, payload, qos))
+
+ # Subscribe at QoS 1 so effective QoS = min(publish_qos=1, granted_qos=1) = 1
+ await subscribe("123456789012", "devices/device4/status", on_msg, granted_qos=1)
+
+ # Ungraceful disconnect (no DISCONNECT packet)
+ await session.cleanup()
+ assert len(received) == 1
+ assert received[0] == ("devices/device4/status", b"gone", 1)
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_will_retain_stores_retained_message():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(
+ client_id="device5",
+ will_flag=True,
+ will_qos=0,
+ will_retain=True,
+ will_topic="devices/device5/status",
+ will_message=b"dead",
+ )
+ await session.handle_packet(PKT_CONNECT, 0, body)
+ # Ungraceful disconnect publishes Will with retain
+ await session.cleanup()
+
+ # New subscriber should get the retained message
+ received = []
+
+ async def on_msg(topic, payload, qos):
+ received.append((topic, payload, qos))
+
+ await subscribe("123456789012", "devices/device5/status", on_msg)
+ assert len(received) == 1
+ assert received[0] == ("devices/device5/status", b"dead", 0)
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_reconnect_replaces_will_fields():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body1 = _build_connect_body(
+ client_id="device6",
+ will_flag=True,
+ will_qos=0,
+ will_retain=False,
+ will_topic="old/topic",
+ will_message=b"old",
+ )
+ await session.handle_packet(PKT_CONNECT, 0, body1)
+ assert session._will_topic == "old/topic"
+
+ # Reconnect with new Will
+ body2 = _build_connect_body(
+ client_id="device6",
+ will_flag=True,
+ will_qos=1,
+ will_retain=True,
+ will_topic="new/topic",
+ will_message=b"new",
+ )
+ await session.handle_packet(PKT_CONNECT, 0, body2)
+ assert session._will_topic == "new/topic"
+ assert session._will_message == b"new"
+ assert session._will_qos == 1
+ assert session._will_retain is True
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_reconnect_clears_graceful_disconnect_flag():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(client_id="device7", will_flag=False)
+ await session.handle_packet(PKT_CONNECT, 0, body)
+
+ # Graceful disconnect
+ await session.handle_packet(PKT_DISCONNECT, 0, b"")
+ assert session._graceful_disconnect is True
+
+ # Reconnect resets the flag
+ await session.handle_packet(PKT_CONNECT, 0, body)
+ assert session._graceful_disconnect is False
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_reconnect_without_will_clears_previous_will():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ # First connect with Will
+ body1 = _build_connect_body(
+ client_id="device8",
+ will_flag=True,
+ will_qos=1,
+ will_retain=True,
+ will_topic="presence/device8",
+ will_message=b"offline",
+ )
+ await session.handle_packet(PKT_CONNECT, 0, body1)
+ assert session._will_topic == "presence/device8"
+
+ # Reconnect without Will
+ body2 = _build_connect_body(client_id="device8", will_flag=False)
+ await session.handle_packet(PKT_CONNECT, 0, body2)
+ assert session._will_topic is None
+ assert session._will_message is None
+
+ # Ungraceful disconnect should NOT publish anything
+ received = []
+
+ async def on_msg(topic, payload, qos):
+ received.append((topic, payload, qos))
+
+ await subscribe("123456789012", "presence/device8", on_msg)
+ await session.cleanup()
+ assert len(received) == 0
+
+ asyncio.run(_run())
+ reset()
+
+
+# ----------------------------------------------------------------------
+# Broker — Persistent sessions (cleanSession flag)
+# ----------------------------------------------------------------------
+
+
+
+def test_clean_session_1_sends_session_present_0():
+ """cleanSession=1 always sends sessionPresent=0."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(client_id="client1", clean_session=True)
+ await session.handle_packet(PKT_CONNECT, 0, body)
+
+ session_present, return_code = _parse_connack(sent)
+ assert session_present is False
+ assert return_code == 0
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_clean_session_0_no_prior_session_sends_session_present_0():
+ """cleanSession=0 with no prior session sends sessionPresent=0."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(client_id="client1", clean_session=False)
+ await session.handle_packet(PKT_CONNECT, 0, body)
+
+ session_present, return_code = _parse_connack(sent)
+ assert session_present is False
+ assert return_code == 0
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_persistent_session_subscribe_disconnect_reconnect_restores():
+ """Connect with cleanSession=0 → subscribe → disconnect → reconnect → sessionPresent=1 and subscriptions restored."""
+ reset()
+
+ async def _run():
+ # First connection: cleanSession=0, subscribe to a topic
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+
+ connect_body = _build_connect_body(client_id="device1", clean_session=False)
+ await session1.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ # Subscribe to "sensor/temp"
+ sub_body = _build_subscribe_body(1, [("sensor/temp", 1)])
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+
+ # Disconnect (graceful)
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ # Second connection: cleanSession=0, same client_id
+ send2, sent2 = _mock_send()
+ session2 = _WSSession(send2, "123456789012")
+
+ await session2.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ session_present, return_code = _parse_connack(sent2)
+ assert session_present is True
+ assert return_code == 0
+
+ # Verify subscriptions are restored by publishing a message
+ received = []
+
+ # The session should already be subscribed, so publish should deliver
+ await publish("123456789012", "sensor/temp", b"25C", qos=1)
+
+ # Check that session2 received the message
+ # The message should be in sent2 as a PUBLISH packet
+ publish_found = False
+ for msg in sent2:
+ data = msg.get("bytes")
+ if data and ((data[0] >> 4) & 0x0F) == PKT_PUBLISH:
+ publish_found = True
+ break
+ assert publish_found, "Restored subscription should receive published messages"
+
+ await session2.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_clean_session_1_discards_prior_state():
+ """cleanSession=1 discards any prior persistent session state."""
+ reset()
+
+ async def _run():
+ # First connection: cleanSession=0, subscribe
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+
+ connect_body_persistent = _build_connect_body(client_id="device2", clean_session=False)
+ await session1.handle_packet(PKT_CONNECT, 0, connect_body_persistent)
+
+ sub_body = _build_subscribe_body(1, [("alerts/#", 1)])
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+
+ # Disconnect
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ # Verify persistent session exists
+ assert ("123456789012", "device2") in _persistent_sessions
+
+ # Second connection: cleanSession=1 — should discard prior state
+ send2, sent2 = _mock_send()
+ session2 = _WSSession(send2, "123456789012")
+
+ connect_body_clean = _build_connect_body(client_id="device2", clean_session=True)
+ await session2.handle_packet(PKT_CONNECT, 0, connect_body_clean)
+
+ session_present, return_code = _parse_connack(sent2)
+ assert session_present is False
+ assert return_code == 0
+
+ # Verify persistent session was discarded
+ assert ("123456789012", "device2") not in _persistent_sessions
+
+ # Publish to the old subscription topic — should NOT be delivered
+ await publish("123456789012", "alerts/fire", b"alarm", qos=1)
+
+ publish_found = False
+ for msg in sent2:
+ data = msg.get("bytes")
+ if data and ((data[0] >> 4) & 0x0F) == PKT_PUBLISH:
+ publish_found = True
+ break
+ assert not publish_found, "cleanSession=1 should not restore prior subscriptions"
+
+ await session2.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_offline_qos1_messages_queued_and_delivered_on_reconnect():
+ """Persistent session disconnects; QoS 1 messages published; reconnect delivers queued messages."""
+ reset()
+
+ async def _run():
+ # First connection: cleanSession=0, subscribe
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+
+ connect_body = _build_connect_body(client_id="device3", clean_session=False)
+ await session1.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ sub_body = _build_subscribe_body(1, [("data/stream", 1)])
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+
+ # Disconnect
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ # Publish QoS 1 messages while client is offline
+ await publish("123456789012", "data/stream", b"msg1", qos=1)
+ await publish("123456789012", "data/stream", b"msg2", qos=1)
+ await publish("123456789012", "data/stream", b"msg3", qos=1)
+
+ # Verify messages are queued
+ ps = _persistent_sessions.get(("123456789012", "device3"))
+ assert ps is not None
+ assert len(ps.queued_messages) == 3
+
+ # Reconnect with cleanSession=0
+ send2, sent2 = _mock_send()
+ session2 = _WSSession(send2, "123456789012")
+
+ await session2.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ session_present, _ = _parse_connack(sent2)
+ assert session_present is True
+
+ # Verify queued messages were delivered
+ publish_messages = []
+ for msg in sent2:
+ data = msg.get("bytes")
+ if data and ((data[0] >> 4) & 0x0F) == PKT_PUBLISH:
+ publish_messages.append(data)
+
+ assert len(publish_messages) == 3, f"Expected 3 queued messages delivered, got {len(publish_messages)}"
+
+ # Verify queue is now empty
+ assert len(ps.queued_messages) == 0
+
+ await session2.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_qos0_messages_not_queued_for_offline_sessions():
+ """QoS 0 messages should NOT be queued for offline persistent sessions."""
+ reset()
+
+ async def _run():
+ # First connection: cleanSession=0, subscribe
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+
+ connect_body = _build_connect_body(client_id="device4", clean_session=False)
+ await session1.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ sub_body = _build_subscribe_body(1, [("events/log", 1)])
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+
+ # Disconnect
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ # Publish QoS 0 messages while client is offline
+ await publish("123456789012", "events/log", b"info1", qos=0)
+ await publish("123456789012", "events/log", b"info2", qos=0)
+
+ # Verify no messages queued (QoS 0 not queued)
+ ps = _persistent_sessions.get(("123456789012", "device4"))
+ assert ps is not None
+ assert len(ps.queued_messages) == 0
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_queue_bounded_to_1000_messages():
+ """Queue should be bounded to 1000 messages, dropping oldest on overflow."""
+ reset()
+
+ async def _run():
+ # First connection: cleanSession=0, subscribe
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+
+ connect_body = _build_connect_body(client_id="device5", clean_session=False)
+ await session1.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ sub_body = _build_subscribe_body(1, [("bulk/data", 1)])
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+
+ # Disconnect
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ # Publish 1050 QoS 1 messages while client is offline
+ for i in range(1050):
+ await publish("123456789012", "bulk/data", f"msg{i}".encode(), qos=1)
+
+ # Verify queue is bounded to 1000
+ ps = _persistent_sessions.get(("123456789012", "device5"))
+ assert ps is not None
+ assert len(ps.queued_messages) == 1000
+
+ # Verify oldest messages were dropped (first 50 should be gone)
+ first_topic, first_payload, first_qos = ps.queued_messages[0]
+ assert first_payload == b"msg50"
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_expired_session_not_restored():
+ """An expired persistent session should not be restored."""
+ reset()
+
+ async def _run():
+ import time
+
+ # First connection: cleanSession=0, subscribe
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+
+ connect_body = _build_connect_body(client_id="device6", clean_session=False)
+ await session1.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ sub_body = _build_subscribe_body(1, [("temp/data", 1)])
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+
+ # Disconnect
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ # Manually expire the session by setting created_at far in the past
+ ps = _persistent_sessions.get(("123456789012", "device6"))
+ assert ps is not None
+ ps.created_at = time.time() - 7200 # 2 hours ago (default expiry is 1 hour)
+
+ # Reconnect with cleanSession=0
+ send2, sent2 = _mock_send()
+ session2 = _WSSession(send2, "123456789012")
+
+ await session2.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ session_present, return_code = _parse_connack(sent2)
+ assert session_present is False # Expired session not restored
+ assert return_code == 0
+
+ await session2.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_wildcard_subscription_persisted_and_restored():
+ """Wildcard subscriptions should be persisted and restored correctly."""
+ reset()
+
+ async def _run():
+ # First connection: cleanSession=0, subscribe with wildcard
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+
+ connect_body = _build_connect_body(client_id="device7", clean_session=False)
+ await session1.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ sub_body = _build_subscribe_body(1, [("sensors/+/temp", 1)])
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+
+ # Disconnect
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ # Reconnect
+ send2, sent2 = _mock_send()
+ session2 = _WSSession(send2, "123456789012")
+
+ await session2.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ session_present, _ = _parse_connack(sent2)
+ assert session_present is True
+
+ # Publish to a topic matching the wildcard
+ await publish("123456789012", "sensors/room1/temp", b"22C", qos=1)
+
+ publish_found = False
+ for msg in sent2:
+ data = msg.get("bytes")
+ if data and ((data[0] >> 4) & 0x0F) == PKT_PUBLISH:
+ publish_found = True
+ break
+ assert publish_found, "Restored wildcard subscription should receive matching messages"
+
+ await session2.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_different_accounts_sessions_isolated():
+ """Persistent sessions are scoped by (account_id, client_id)."""
+ reset()
+
+ async def _run():
+ # Account A: connect, subscribe, disconnect
+ send_a, sent_a = _mock_send()
+ session_a = _WSSession(send_a, "account_A")
+
+ connect_body = _build_connect_body(client_id="shared_id", clean_session=False)
+ await session_a.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ sub_body = _build_subscribe_body(1, [("topic/a", 1)])
+ await session_a.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+ await session_a.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session_a.cleanup()
+
+ # Account B: connect with same client_id — should NOT see account A's session
+ send_b, sent_b = _mock_send()
+ session_b = _WSSession(send_b, "account_B")
+
+ await session_b.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ session_present, _ = _parse_connack(sent_b)
+ assert session_present is False # No prior session for account_B
+
+ await session_b.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+# ----------------------------------------------------------------------
+# Broker — QoS 1 + retransmits
+# ----------------------------------------------------------------------
+
+
+
+def test_subscription_has_granted_qos_field():
+ """_Subscription stores granted_qos."""
+ async def deliver(t, p, q):
+ pass
+
+ sub = _Subscription("acct/topic", "acct", deliver, granted_qos=1)
+ assert sub.granted_qos == 1
+
+ sub0 = _Subscription("acct/topic", "acct", deliver, granted_qos=0)
+ assert sub0.granted_qos == 0
+
+
+def test_subscribe_handler_caps_qos_at_1():
+ """PKT_SUBSCRIBE grants min(requested, 1) — QoS 2 is capped to 1."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("sub-client"))
+
+ # Subscribe with QoS 0, 1, and 2
+ body = _build_subscribe_body(1, [
+ ("topic/a", 0),
+ ("topic/b", 1),
+ ("topic/c", 2), # Should be capped to 1
+ ])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+
+ # Find SUBACK in sent messages
+ suback_frames = [m for m in sent if m.get("bytes") and (m["bytes"][0] >> 4) == 9]
+ assert len(suback_frames) == 1
+ suback_data = suback_frames[0]["bytes"]
+ # SUBACK: fixed header (1 byte) + remaining length (1 byte) + packet_id (2 bytes) + return codes
+ offset = 1
+ # Decode remaining length
+ multiplier = 1
+ remaining = 0
+ while True:
+ b = suback_data[offset]
+ offset += 1
+ remaining += (b & 0x7F) * multiplier
+ if b & 0x80 == 0:
+ break
+ multiplier *= 128
+ # Skip packet ID
+ offset += 2
+ # Return codes
+ return_codes = list(suback_data[offset:])
+ assert return_codes == [0, 1, 1] # QoS 2 capped to 1
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_subscribe_stores_granted_qos_on_session():
+ """Session tracks granted QoS per subscription ID."""
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("qos-track"))
+
+ body = _build_subscribe_body(1, [("sensor/temp", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+
+ # Session should have one subscription with granted_qos=1
+ assert len(session._sub_ids) == 1
+ sid = session._sub_ids[0]
+ assert session._sub_granted_qos[sid] == 1
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+# ---------------------------------------------------------------------------
+# Task 18.2: QoS 1 delivery with packet ID tracking
+# ---------------------------------------------------------------------------
+
+
+def test_qos1_publish_delivers_with_packet_id():
+ """QoS 1 publish to QoS 1 subscriber delivers at QoS 1 with packet ID."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("qos1-sub"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/qos1", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+
+ # Clear sent to isolate publish frames
+ sent.clear()
+
+ # Publish at QoS 1 from external source
+ await publish("123456789012", "test/qos1", b"hello-qos1", qos=1)
+
+ # Check delivered message
+ publishes = _extract_publish_frames(sent)
+ assert len(publishes) == 1
+ topic, payload, qos, packet_id, dup = publishes[0]
+ assert topic == "test/qos1"
+ assert payload == b"hello-qos1"
+ assert qos == 1
+ assert packet_id is not None
+ assert packet_id >= 1
+ assert dup is False
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_qos0_publish_to_qos1_subscriber_delivers_at_qos0():
+ """QoS 0 publish to QoS 1 subscriber delivers at QoS 0 (effective = min)."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("qos-min"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/minqos", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 0
+ await publish("123456789012", "test/minqos", b"qos0-msg", qos=0)
+
+ publishes = _extract_publish_frames(sent)
+ assert len(publishes) == 1
+ topic, payload, qos, packet_id, dup = publishes[0]
+ assert qos == 0
+ assert packet_id is None # No packet ID for QoS 0
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_qos1_publish_to_qos0_subscriber_delivers_at_qos0():
+ """QoS 1 publish to QoS 0 subscriber delivers at QoS 0 (effective = min)."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("qos0-sub"))
+
+ # Subscribe at QoS 0
+ body = _build_subscribe_body(1, [("test/downgrade", 0)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 1
+ await publish("123456789012", "test/downgrade", b"downgraded", qos=1)
+
+ publishes = _extract_publish_frames(sent)
+ assert len(publishes) == 1
+ topic, payload, qos, packet_id, dup = publishes[0]
+ assert qos == 0
+ assert packet_id is None
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_qos1_delivery_tracks_in_flight():
+ """QoS 1 delivery stores message in _in_flight dict."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("inflight"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/inflight", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 1
+ await publish("123456789012", "test/inflight", b"tracked", qos=1)
+
+ # Should have one in-flight message
+ assert len(session._in_flight) == 1
+ pid = list(session._in_flight.keys())[0]
+ msg = session._in_flight[pid]
+ assert msg.topic == "test/inflight"
+ assert msg.payload == b"tracked"
+ assert msg.retransmit_count == 0
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_packet_ids_are_monotonically_increasing():
+ """Packet IDs increment monotonically."""
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ ids = [session._alloc_packet_id() for _ in range(5)]
+ assert ids == [1, 2, 3, 4, 5]
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_packet_ids_wrap_at_65535():
+ """Packet IDs wrap from 65535 back to 1."""
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+ session._next_pid = 65535
+
+ pid1 = session._alloc_packet_id()
+ pid2 = session._alloc_packet_id()
+ assert pid1 == 65535
+ assert pid2 == 1 # Wraps back to 1
+
+ asyncio.run(_run())
+ reset()
+
+
+# ---------------------------------------------------------------------------
+# Task 18.3: PUBACK handling and retransmission
+# ---------------------------------------------------------------------------
+
+
+def test_puback_removes_from_in_flight():
+ """PUBACK with matching packet ID removes message from _in_flight."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("puback-test"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/puback", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 1
+ await publish("123456789012", "test/puback", b"ack-me", qos=1)
+
+ assert len(session._in_flight) == 1
+ pid = list(session._in_flight.keys())[0]
+
+ # Send PUBACK
+ puback_body = struct.pack("!H", pid)
+ result = await session.handle_packet(PKT_PUBACK, 0, puback_body)
+ assert result is True
+ assert len(session._in_flight) == 0
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_puback_unknown_packet_id_is_ignored():
+ """PUBACK for unknown packet ID does not crash."""
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("puback-unknown"))
+
+ # Send PUBACK for non-existent packet ID
+ puback_body = struct.pack("!H", 999)
+ result = await session.handle_packet(PKT_PUBACK, 0, puback_body)
+ assert result is True
+ assert len(session._in_flight) == 0
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_retransmit_task_started_on_qos1_delivery():
+ """Retransmit background task is started when QoS 1 message is delivered."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("retransmit"))
+
+ assert session._retransmit_task is None
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/retransmit", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 1
+ await publish("123456789012", "test/retransmit", b"retry-me", qos=1)
+
+ # Retransmit task should be started
+ assert session._retransmit_task is not None
+ assert not session._retransmit_task.done()
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_cleanup_cancels_retransmit_task():
+ """cleanup() cancels the retransmit background task."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("cleanup-rt"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/cleanup", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 1 to start retransmit task
+ await publish("123456789012", "test/cleanup", b"clean", qos=1)
+ task = session._retransmit_task
+ assert task is not None
+
+ await session.cleanup()
+ assert session._retransmit_task is None
+ assert task.done() or task.cancelled()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_cleanup_clears_in_flight():
+ """cleanup() clears the _in_flight dict."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("cleanup-if"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/clear", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 1
+ await publish("123456789012", "test/clear", b"clear-me", qos=1)
+ assert len(session._in_flight) == 1
+
+ await session.cleanup()
+ assert len(session._in_flight) == 0
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_retransmit_sends_dup_flag():
+ """Retransmission sends PUBLISH with DUP flag set."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("dup-test"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/dup", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 1
+ await publish("123456789012", "test/dup", b"dup-payload", qos=1)
+
+ # Verify initial publish has DUP=False
+ publishes = _extract_publish_frames(sent)
+ assert len(publishes) == 1
+ assert publishes[0][4] is False # dup flag
+
+ # Manually trigger retransmission by manipulating sent_at
+ pid = list(session._in_flight.keys())[0]
+ msg = session._in_flight[pid]
+ # Set sent_at far in the past to trigger retransmit
+ msg.sent_at = 0
+
+ sent.clear()
+
+ # Run one iteration of retransmit logic manually
+ import asyncio as _asyncio
+ now = _asyncio.get_event_loop().time()
+ for p, m in list(session._in_flight.items()):
+ if now - m.sent_at >= _RETRANSMIT_INTERVAL_SECONDS:
+ m.retransmit_count += 1
+ m.sent_at = now
+ from ministack.services.iot import _make_publish
+ await session.send_bytes(
+ _make_publish(m.topic, m.payload, qos=1, packet_id=p, dup=True)
+ )
+
+ # Verify retransmitted publish has DUP=True
+ publishes = _extract_publish_frames(sent)
+ assert len(publishes) == 1
+ topic, payload, qos, packet_id, dup = publishes[0]
+ assert topic == "test/dup"
+ assert payload == b"dup-payload"
+ assert qos == 1
+ assert packet_id == pid
+ assert dup is True
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_in_flight_message_fields():
+ """_InFlightMessage stores all required fields."""
+ reset()
+
+ async def _run():
+ msg = _InFlightMessage(packet_id=42, topic="sensor/data", payload=b"temp=22")
+ assert msg.packet_id == 42
+ assert msg.topic == "sensor/data"
+ assert msg.payload == b"temp=22"
+ assert msg.sent_at > 0
+ assert msg.retransmit_count == 0
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_multiple_qos1_messages_get_unique_packet_ids():
+ """Multiple QoS 1 deliveries get unique, incrementing packet IDs."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("multi-pid"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/multi", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish 3 messages at QoS 1
+ await publish("123456789012", "test/multi", b"msg1", qos=1)
+ await publish("123456789012", "test/multi", b"msg2", qos=1)
+ await publish("123456789012", "test/multi", b"msg3", qos=1)
+
+ publishes = _extract_publish_frames(sent)
+ assert len(publishes) == 3
+ pids = [p[3] for p in publishes]
+ # All unique
+ assert len(set(pids)) == 3
+ # Monotonically increasing
+ assert pids == sorted(pids)
+
+ # All tracked in-flight
+ assert len(session._in_flight) == 3
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_puback_for_first_of_multiple_in_flight():
+ """PUBACK removes only the specific packet ID from in-flight."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("selective-ack"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/selective", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish 3 messages
+ await publish("123456789012", "test/selective", b"a", qos=1)
+ await publish("123456789012", "test/selective", b"b", qos=1)
+ await publish("123456789012", "test/selective", b"c", qos=1)
+
+ assert len(session._in_flight) == 3
+ pids = sorted(session._in_flight.keys())
+
+ # ACK the middle one
+ puback_body = struct.pack("!H", pids[1])
+ await session.handle_packet(PKT_PUBACK, 0, puback_body)
+
+ assert len(session._in_flight) == 2
+ assert pids[1] not in session._in_flight
+ assert pids[0] in session._in_flight
+ assert pids[2] in session._in_flight
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
diff --git a/tests/test_iot_lwt.py b/tests/test_iot_lwt.py
deleted file mode 100644
index 9e4cd82f..00000000
--- a/tests/test_iot_lwt.py
+++ /dev/null
@@ -1,300 +0,0 @@
-"""Unit tests for Last Will and Testament (LWT) support in iot_broker.py."""
-
-import asyncio
-import struct
-
-from ministack.services.iot import (
- PKT_CONNECT,
- PKT_DISCONNECT,
- _WSSession,
- _encode_string,
- broker_reset as reset,
- broker_subscribe as subscribe,
-)
-
-
-def _build_connect_body(
- client_id="test",
- will_flag=False,
- will_qos=0,
- will_retain=False,
- will_topic="",
- will_message=b"",
-):
- """Build a CONNECT packet body (variable header + payload)."""
- body = bytearray()
- # Protocol Name
- body += _encode_string("MQTT")
- # Protocol Level (4 for MQTT 3.1.1)
- body.append(4)
- # Connect Flags
- flags = 0
- if will_flag:
- flags |= 0x04
- flags |= (will_qos & 0x03) << 3
- if will_retain:
- flags |= 0x20
- body.append(flags)
- # Keep Alive (60 seconds)
- body += struct.pack("!H", 60)
- # Payload: Client ID
- body += _encode_string(client_id)
- # Will Topic + Will Message (if Will Flag set)
- if will_flag:
- body += _encode_string(will_topic)
- msg = will_message if isinstance(will_message, bytes) else will_message.encode()
- body += struct.pack("!H", len(msg)) + msg
- return bytes(body)
-
-
-def _mock_send():
- sent = []
-
- async def send(msg):
- sent.append(msg)
-
- return send, sent
-
-
-def test_will_fields_parsed_from_connect():
- reset()
-
- async def _run():
- send, _ = _mock_send()
- session = _WSSession(send, "123456789012")
-
- body = _build_connect_body(
- client_id="device1",
- will_flag=True,
- will_qos=1,
- will_retain=True,
- will_topic="devices/device1/status",
- will_message=b"offline",
- )
- result = await session.handle_packet(PKT_CONNECT, 0, body)
- assert result is True
- assert session._will_topic == "devices/device1/status"
- assert session._will_message == b"offline"
- assert session._will_qos == 1
- assert session._will_retain is True
-
- asyncio.run(_run())
- reset()
-
-
-def test_no_will_when_flag_not_set():
- reset()
-
- async def _run():
- send, _ = _mock_send()
- session = _WSSession(send, "123456789012")
-
- body = _build_connect_body(client_id="device2", will_flag=False)
- await session.handle_packet(PKT_CONNECT, 0, body)
- assert session._will_topic is None
- assert session._will_message is None
- assert session._will_qos == 0
- assert session._will_retain is False
-
- asyncio.run(_run())
- reset()
-
-
-def test_graceful_disconnect_does_not_publish_will():
- reset()
-
- async def _run():
- send, _ = _mock_send()
- session = _WSSession(send, "123456789012")
-
- body = _build_connect_body(
- client_id="device3",
- will_flag=True,
- will_qos=0,
- will_retain=False,
- will_topic="devices/device3/status",
- will_message=b"offline",
- )
- await session.handle_packet(PKT_CONNECT, 0, body)
-
- received = []
-
- async def on_msg(topic, payload, qos):
- received.append((topic, payload, qos))
-
- await subscribe("123456789012", "devices/device3/status", on_msg)
-
- # Graceful disconnect
- result = await session.handle_packet(PKT_DISCONNECT, 0, b"")
- assert result is False
- assert session._graceful_disconnect is True
- await session.cleanup()
- assert len(received) == 0
-
- asyncio.run(_run())
- reset()
-
-
-def test_ungraceful_disconnect_publishes_will():
- reset()
-
- async def _run():
- send, _ = _mock_send()
- session = _WSSession(send, "123456789012")
-
- body = _build_connect_body(
- client_id="device4",
- will_flag=True,
- will_qos=1,
- will_retain=False,
- will_topic="devices/device4/status",
- will_message=b"gone",
- )
- await session.handle_packet(PKT_CONNECT, 0, body)
-
- received = []
-
- async def on_msg(topic, payload, qos):
- received.append((topic, payload, qos))
-
- # Subscribe at QoS 1 so effective QoS = min(publish_qos=1, granted_qos=1) = 1
- await subscribe("123456789012", "devices/device4/status", on_msg, granted_qos=1)
-
- # Ungraceful disconnect (no DISCONNECT packet)
- await session.cleanup()
- assert len(received) == 1
- assert received[0] == ("devices/device4/status", b"gone", 1)
-
- asyncio.run(_run())
- reset()
-
-
-def test_will_retain_stores_retained_message():
- reset()
-
- async def _run():
- send, _ = _mock_send()
- session = _WSSession(send, "123456789012")
-
- body = _build_connect_body(
- client_id="device5",
- will_flag=True,
- will_qos=0,
- will_retain=True,
- will_topic="devices/device5/status",
- will_message=b"dead",
- )
- await session.handle_packet(PKT_CONNECT, 0, body)
- # Ungraceful disconnect publishes Will with retain
- await session.cleanup()
-
- # New subscriber should get the retained message
- received = []
-
- async def on_msg(topic, payload, qos):
- received.append((topic, payload, qos))
-
- await subscribe("123456789012", "devices/device5/status", on_msg)
- assert len(received) == 1
- assert received[0] == ("devices/device5/status", b"dead", 0)
-
- asyncio.run(_run())
- reset()
-
-
-def test_reconnect_replaces_will_fields():
- reset()
-
- async def _run():
- send, _ = _mock_send()
- session = _WSSession(send, "123456789012")
-
- body1 = _build_connect_body(
- client_id="device6",
- will_flag=True,
- will_qos=0,
- will_retain=False,
- will_topic="old/topic",
- will_message=b"old",
- )
- await session.handle_packet(PKT_CONNECT, 0, body1)
- assert session._will_topic == "old/topic"
-
- # Reconnect with new Will
- body2 = _build_connect_body(
- client_id="device6",
- will_flag=True,
- will_qos=1,
- will_retain=True,
- will_topic="new/topic",
- will_message=b"new",
- )
- await session.handle_packet(PKT_CONNECT, 0, body2)
- assert session._will_topic == "new/topic"
- assert session._will_message == b"new"
- assert session._will_qos == 1
- assert session._will_retain is True
-
- asyncio.run(_run())
- reset()
-
-
-def test_reconnect_clears_graceful_disconnect_flag():
- reset()
-
- async def _run():
- send, _ = _mock_send()
- session = _WSSession(send, "123456789012")
-
- body = _build_connect_body(client_id="device7", will_flag=False)
- await session.handle_packet(PKT_CONNECT, 0, body)
-
- # Graceful disconnect
- await session.handle_packet(PKT_DISCONNECT, 0, b"")
- assert session._graceful_disconnect is True
-
- # Reconnect resets the flag
- await session.handle_packet(PKT_CONNECT, 0, body)
- assert session._graceful_disconnect is False
-
- asyncio.run(_run())
- reset()
-
-
-def test_reconnect_without_will_clears_previous_will():
- reset()
-
- async def _run():
- send, _ = _mock_send()
- session = _WSSession(send, "123456789012")
-
- # First connect with Will
- body1 = _build_connect_body(
- client_id="device8",
- will_flag=True,
- will_qos=1,
- will_retain=True,
- will_topic="presence/device8",
- will_message=b"offline",
- )
- await session.handle_packet(PKT_CONNECT, 0, body1)
- assert session._will_topic == "presence/device8"
-
- # Reconnect without Will
- body2 = _build_connect_body(client_id="device8", will_flag=False)
- await session.handle_packet(PKT_CONNECT, 0, body2)
- assert session._will_topic is None
- assert session._will_message is None
-
- # Ungraceful disconnect should NOT publish anything
- received = []
-
- async def on_msg(topic, payload, qos):
- received.append((topic, payload, qos))
-
- await subscribe("123456789012", "presence/device8", on_msg)
- await session.cleanup()
- assert len(received) == 0
-
- asyncio.run(_run())
- reset()
diff --git a/tests/test_iot_persistent_sessions.py b/tests/test_iot_persistent_sessions.py
deleted file mode 100644
index 0a394eef..00000000
--- a/tests/test_iot_persistent_sessions.py
+++ /dev/null
@@ -1,473 +0,0 @@
-"""Unit tests for persistent sessions (cleanSession flag) in iot_broker.py."""
-
-import asyncio
-import struct
-
-from ministack.services.iot import (
- PKT_CONNECT,
- PKT_CONNACK,
- PKT_DISCONNECT,
- PKT_PUBLISH,
- PKT_SUBSCRIBE,
- _WSSession,
- _encode_string,
- _persistent_sessions,
- broker_publish as publish,
- broker_reset as reset,
- broker_subscribe as subscribe,
-)
-
-
-def _build_connect_body(
- client_id="test",
- clean_session=True,
- will_flag=False,
- will_qos=0,
- will_retain=False,
- will_topic="",
- will_message=b"",
-):
- """Build a CONNECT packet body (variable header + payload)."""
- body = bytearray()
- # Protocol Name
- body += _encode_string("MQTT")
- # Protocol Level (4 for MQTT 3.1.1)
- body.append(4)
- # Connect Flags
- flags = 0
- if clean_session:
- flags |= 0x02
- if will_flag:
- flags |= 0x04
- flags |= (will_qos & 0x03) << 3
- if will_retain:
- flags |= 0x20
- body.append(flags)
- # Keep Alive (60 seconds)
- body += struct.pack("!H", 60)
- # Payload: Client ID
- body += _encode_string(client_id)
- # Will Topic + Will Message (if Will Flag set)
- if will_flag:
- body += _encode_string(will_topic)
- msg = will_message if isinstance(will_message, bytes) else will_message.encode()
- body += struct.pack("!H", len(msg)) + msg
- return bytes(body)
-
-
-def _build_subscribe_body(packet_id, topics_qos):
- """Build a SUBSCRIBE packet body. topics_qos is list of (topic, qos)."""
- body = struct.pack("!H", packet_id)
- for topic, qos in topics_qos:
- body += _encode_string(topic)
- body += bytes([qos])
- return body
-
-
-def _mock_send():
- sent = []
-
- async def send(msg):
- sent.append(msg)
-
- return send, sent
-
-
-def _parse_connack(sent_messages):
- """Extract sessionPresent flag from CONNACK in sent messages."""
- for msg in sent_messages:
- data = msg.get("bytes")
- if data and len(data) >= 4:
- pkt_type = (data[0] >> 4) & 0x0F
- if pkt_type == PKT_CONNACK:
- # CONNACK: fixed header (1 byte) + remaining length (1 byte) + flags (1 byte) + return code (1 byte)
- session_present = bool(data[2] & 0x01)
- return_code = data[3]
- return session_present, return_code
- return None, None
-
-
-def test_clean_session_1_sends_session_present_0():
- """cleanSession=1 always sends sessionPresent=0."""
- reset()
-
- async def _run():
- send, sent = _mock_send()
- session = _WSSession(send, "123456789012")
-
- body = _build_connect_body(client_id="client1", clean_session=True)
- await session.handle_packet(PKT_CONNECT, 0, body)
-
- session_present, return_code = _parse_connack(sent)
- assert session_present is False
- assert return_code == 0
-
- asyncio.run(_run())
- reset()
-
-
-def test_clean_session_0_no_prior_session_sends_session_present_0():
- """cleanSession=0 with no prior session sends sessionPresent=0."""
- reset()
-
- async def _run():
- send, sent = _mock_send()
- session = _WSSession(send, "123456789012")
-
- body = _build_connect_body(client_id="client1", clean_session=False)
- await session.handle_packet(PKT_CONNECT, 0, body)
-
- session_present, return_code = _parse_connack(sent)
- assert session_present is False
- assert return_code == 0
-
- asyncio.run(_run())
- reset()
-
-
-def test_persistent_session_subscribe_disconnect_reconnect_restores():
- """Connect with cleanSession=0 → subscribe → disconnect → reconnect → sessionPresent=1 and subscriptions restored."""
- reset()
-
- async def _run():
- # First connection: cleanSession=0, subscribe to a topic
- send1, sent1 = _mock_send()
- session1 = _WSSession(send1, "123456789012")
-
- connect_body = _build_connect_body(client_id="device1", clean_session=False)
- await session1.handle_packet(PKT_CONNECT, 0, connect_body)
-
- # Subscribe to "sensor/temp"
- sub_body = _build_subscribe_body(1, [("sensor/temp", 1)])
- await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
-
- # Disconnect (graceful)
- await session1.handle_packet(PKT_DISCONNECT, 0, b"")
- await session1.cleanup()
-
- # Second connection: cleanSession=0, same client_id
- send2, sent2 = _mock_send()
- session2 = _WSSession(send2, "123456789012")
-
- await session2.handle_packet(PKT_CONNECT, 0, connect_body)
-
- session_present, return_code = _parse_connack(sent2)
- assert session_present is True
- assert return_code == 0
-
- # Verify subscriptions are restored by publishing a message
- received = []
-
- # The session should already be subscribed, so publish should deliver
- await publish("123456789012", "sensor/temp", b"25C", qos=1)
-
- # Check that session2 received the message
- # The message should be in sent2 as a PUBLISH packet
- publish_found = False
- for msg in sent2:
- data = msg.get("bytes")
- if data and ((data[0] >> 4) & 0x0F) == PKT_PUBLISH:
- publish_found = True
- break
- assert publish_found, "Restored subscription should receive published messages"
-
- await session2.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_clean_session_1_discards_prior_state():
- """cleanSession=1 discards any prior persistent session state."""
- reset()
-
- async def _run():
- # First connection: cleanSession=0, subscribe
- send1, sent1 = _mock_send()
- session1 = _WSSession(send1, "123456789012")
-
- connect_body_persistent = _build_connect_body(client_id="device2", clean_session=False)
- await session1.handle_packet(PKT_CONNECT, 0, connect_body_persistent)
-
- sub_body = _build_subscribe_body(1, [("alerts/#", 1)])
- await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
-
- # Disconnect
- await session1.handle_packet(PKT_DISCONNECT, 0, b"")
- await session1.cleanup()
-
- # Verify persistent session exists
- assert ("123456789012", "device2") in _persistent_sessions
-
- # Second connection: cleanSession=1 — should discard prior state
- send2, sent2 = _mock_send()
- session2 = _WSSession(send2, "123456789012")
-
- connect_body_clean = _build_connect_body(client_id="device2", clean_session=True)
- await session2.handle_packet(PKT_CONNECT, 0, connect_body_clean)
-
- session_present, return_code = _parse_connack(sent2)
- assert session_present is False
- assert return_code == 0
-
- # Verify persistent session was discarded
- assert ("123456789012", "device2") not in _persistent_sessions
-
- # Publish to the old subscription topic — should NOT be delivered
- await publish("123456789012", "alerts/fire", b"alarm", qos=1)
-
- publish_found = False
- for msg in sent2:
- data = msg.get("bytes")
- if data and ((data[0] >> 4) & 0x0F) == PKT_PUBLISH:
- publish_found = True
- break
- assert not publish_found, "cleanSession=1 should not restore prior subscriptions"
-
- await session2.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_offline_qos1_messages_queued_and_delivered_on_reconnect():
- """Persistent session disconnects; QoS 1 messages published; reconnect delivers queued messages."""
- reset()
-
- async def _run():
- # First connection: cleanSession=0, subscribe
- send1, sent1 = _mock_send()
- session1 = _WSSession(send1, "123456789012")
-
- connect_body = _build_connect_body(client_id="device3", clean_session=False)
- await session1.handle_packet(PKT_CONNECT, 0, connect_body)
-
- sub_body = _build_subscribe_body(1, [("data/stream", 1)])
- await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
-
- # Disconnect
- await session1.handle_packet(PKT_DISCONNECT, 0, b"")
- await session1.cleanup()
-
- # Publish QoS 1 messages while client is offline
- await publish("123456789012", "data/stream", b"msg1", qos=1)
- await publish("123456789012", "data/stream", b"msg2", qos=1)
- await publish("123456789012", "data/stream", b"msg3", qos=1)
-
- # Verify messages are queued
- ps = _persistent_sessions.get(("123456789012", "device3"))
- assert ps is not None
- assert len(ps.queued_messages) == 3
-
- # Reconnect with cleanSession=0
- send2, sent2 = _mock_send()
- session2 = _WSSession(send2, "123456789012")
-
- await session2.handle_packet(PKT_CONNECT, 0, connect_body)
-
- session_present, _ = _parse_connack(sent2)
- assert session_present is True
-
- # Verify queued messages were delivered
- publish_messages = []
- for msg in sent2:
- data = msg.get("bytes")
- if data and ((data[0] >> 4) & 0x0F) == PKT_PUBLISH:
- publish_messages.append(data)
-
- assert len(publish_messages) == 3, f"Expected 3 queued messages delivered, got {len(publish_messages)}"
-
- # Verify queue is now empty
- assert len(ps.queued_messages) == 0
-
- await session2.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_qos0_messages_not_queued_for_offline_sessions():
- """QoS 0 messages should NOT be queued for offline persistent sessions."""
- reset()
-
- async def _run():
- # First connection: cleanSession=0, subscribe
- send1, sent1 = _mock_send()
- session1 = _WSSession(send1, "123456789012")
-
- connect_body = _build_connect_body(client_id="device4", clean_session=False)
- await session1.handle_packet(PKT_CONNECT, 0, connect_body)
-
- sub_body = _build_subscribe_body(1, [("events/log", 1)])
- await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
-
- # Disconnect
- await session1.handle_packet(PKT_DISCONNECT, 0, b"")
- await session1.cleanup()
-
- # Publish QoS 0 messages while client is offline
- await publish("123456789012", "events/log", b"info1", qos=0)
- await publish("123456789012", "events/log", b"info2", qos=0)
-
- # Verify no messages queued (QoS 0 not queued)
- ps = _persistent_sessions.get(("123456789012", "device4"))
- assert ps is not None
- assert len(ps.queued_messages) == 0
-
- asyncio.run(_run())
- reset()
-
-
-def test_queue_bounded_to_1000_messages():
- """Queue should be bounded to 1000 messages, dropping oldest on overflow."""
- reset()
-
- async def _run():
- # First connection: cleanSession=0, subscribe
- send1, sent1 = _mock_send()
- session1 = _WSSession(send1, "123456789012")
-
- connect_body = _build_connect_body(client_id="device5", clean_session=False)
- await session1.handle_packet(PKT_CONNECT, 0, connect_body)
-
- sub_body = _build_subscribe_body(1, [("bulk/data", 1)])
- await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
-
- # Disconnect
- await session1.handle_packet(PKT_DISCONNECT, 0, b"")
- await session1.cleanup()
-
- # Publish 1050 QoS 1 messages while client is offline
- for i in range(1050):
- await publish("123456789012", "bulk/data", f"msg{i}".encode(), qos=1)
-
- # Verify queue is bounded to 1000
- ps = _persistent_sessions.get(("123456789012", "device5"))
- assert ps is not None
- assert len(ps.queued_messages) == 1000
-
- # Verify oldest messages were dropped (first 50 should be gone)
- first_topic, first_payload, first_qos = ps.queued_messages[0]
- assert first_payload == b"msg50"
-
- asyncio.run(_run())
- reset()
-
-
-def test_expired_session_not_restored():
- """An expired persistent session should not be restored."""
- reset()
-
- async def _run():
- import time
-
- # First connection: cleanSession=0, subscribe
- send1, sent1 = _mock_send()
- session1 = _WSSession(send1, "123456789012")
-
- connect_body = _build_connect_body(client_id="device6", clean_session=False)
- await session1.handle_packet(PKT_CONNECT, 0, connect_body)
-
- sub_body = _build_subscribe_body(1, [("temp/data", 1)])
- await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
-
- # Disconnect
- await session1.handle_packet(PKT_DISCONNECT, 0, b"")
- await session1.cleanup()
-
- # Manually expire the session by setting created_at far in the past
- ps = _persistent_sessions.get(("123456789012", "device6"))
- assert ps is not None
- ps.created_at = time.time() - 7200 # 2 hours ago (default expiry is 1 hour)
-
- # Reconnect with cleanSession=0
- send2, sent2 = _mock_send()
- session2 = _WSSession(send2, "123456789012")
-
- await session2.handle_packet(PKT_CONNECT, 0, connect_body)
-
- session_present, return_code = _parse_connack(sent2)
- assert session_present is False # Expired session not restored
- assert return_code == 0
-
- await session2.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_wildcard_subscription_persisted_and_restored():
- """Wildcard subscriptions should be persisted and restored correctly."""
- reset()
-
- async def _run():
- # First connection: cleanSession=0, subscribe with wildcard
- send1, sent1 = _mock_send()
- session1 = _WSSession(send1, "123456789012")
-
- connect_body = _build_connect_body(client_id="device7", clean_session=False)
- await session1.handle_packet(PKT_CONNECT, 0, connect_body)
-
- sub_body = _build_subscribe_body(1, [("sensors/+/temp", 1)])
- await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
-
- # Disconnect
- await session1.handle_packet(PKT_DISCONNECT, 0, b"")
- await session1.cleanup()
-
- # Reconnect
- send2, sent2 = _mock_send()
- session2 = _WSSession(send2, "123456789012")
-
- await session2.handle_packet(PKT_CONNECT, 0, connect_body)
-
- session_present, _ = _parse_connack(sent2)
- assert session_present is True
-
- # Publish to a topic matching the wildcard
- await publish("123456789012", "sensors/room1/temp", b"22C", qos=1)
-
- publish_found = False
- for msg in sent2:
- data = msg.get("bytes")
- if data and ((data[0] >> 4) & 0x0F) == PKT_PUBLISH:
- publish_found = True
- break
- assert publish_found, "Restored wildcard subscription should receive matching messages"
-
- await session2.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_different_accounts_sessions_isolated():
- """Persistent sessions are scoped by (account_id, client_id)."""
- reset()
-
- async def _run():
- # Account A: connect, subscribe, disconnect
- send_a, sent_a = _mock_send()
- session_a = _WSSession(send_a, "account_A")
-
- connect_body = _build_connect_body(client_id="shared_id", clean_session=False)
- await session_a.handle_packet(PKT_CONNECT, 0, connect_body)
-
- sub_body = _build_subscribe_body(1, [("topic/a", 1)])
- await session_a.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
- await session_a.handle_packet(PKT_DISCONNECT, 0, b"")
- await session_a.cleanup()
-
- # Account B: connect with same client_id — should NOT see account A's session
- send_b, sent_b = _mock_send()
- session_b = _WSSession(send_b, "account_B")
-
- await session_b.handle_packet(PKT_CONNECT, 0, connect_body)
-
- session_present, _ = _parse_connack(sent_b)
- assert session_present is False # No prior session for account_B
-
- await session_b.cleanup()
-
- asyncio.run(_run())
- reset()
diff --git a/tests/test_iot_qos1.py b/tests/test_iot_qos1.py
deleted file mode 100644
index b8bff051..00000000
--- a/tests/test_iot_qos1.py
+++ /dev/null
@@ -1,631 +0,0 @@
-"""Unit tests for QoS 1 end-to-end delivery in iot_broker.py.
-
-Covers tasks 18.1 (granted QoS per subscription), 18.2 (QoS 1 delivery with
-packet ID tracking), and 18.3 (PUBACK handling and retransmission).
-"""
-
-import asyncio
-import struct
-
-from ministack.services.iot import (
- PKT_CONNECT,
- PKT_PUBACK,
- PKT_PUBLISH,
- PKT_SUBSCRIBE,
- _InFlightMessage,
- _RETRANSMIT_INTERVAL_SECONDS,
- _Subscription,
- _WSSession,
- _encode_remaining_length,
- _encode_string,
- _make_puback,
- _make_suback,
- broker_publish as publish,
- broker_reset as reset,
- broker_subscribe as subscribe,
-)
-
-
-def _build_connect_body(client_id="test", clean_session=True):
- """Build a minimal CONNECT packet body."""
- body = bytearray()
- body += _encode_string("MQTT")
- body.append(4) # Protocol Level
- flags = 0x02 if clean_session else 0x00
- body.append(flags)
- body += struct.pack("!H", 60) # Keep Alive
- body += _encode_string(client_id)
- return bytes(body)
-
-
-def _build_subscribe_body(packet_id: int, topics: list[tuple[str, int]]):
- """Build a SUBSCRIBE packet body with topic filters and requested QoS."""
- body = struct.pack("!H", packet_id)
- for topic, qos in topics:
- body += _encode_string(topic)
- body += bytes([qos])
- return body
-
-
-def _mock_send():
- sent = []
-
- async def send(msg):
- sent.append(msg)
-
- return send, sent
-
-
-def _extract_publish_frames(sent_messages):
- """Extract PUBLISH frames from sent WebSocket messages, returning (topic, payload, qos, packet_id, dup)."""
- results = []
- for msg in sent_messages:
- data = msg.get("bytes")
- if data is None:
- continue
- if not data:
- continue
- first = data[0]
- pkt_type = (first >> 4) & 0x0F
- if pkt_type != 3: # Not PUBLISH
- continue
- qos = (first >> 1) & 0x03
- dup = bool(first & 0x08)
- # Decode remaining length
- offset = 1
- multiplier = 1
- remaining = 0
- while True:
- b = data[offset]
- offset += 1
- remaining += (b & 0x7F) * multiplier
- if b & 0x80 == 0:
- break
- multiplier *= 128
- # Read topic
- topic_len = struct.unpack_from("!H", data, offset)[0]
- offset += 2
- topic = data[offset:offset + topic_len].decode("utf-8")
- offset += topic_len
- # Read packet ID if QoS > 0
- packet_id = None
- if qos > 0:
- packet_id = struct.unpack_from("!H", data, offset)[0]
- offset += 2
- payload = data[offset:]
- results.append((topic, payload, qos, packet_id, dup))
- return results
-
-
-# ---------------------------------------------------------------------------
-# Task 18.1: Track granted QoS per subscription
-# ---------------------------------------------------------------------------
-
-
-def test_subscription_has_granted_qos_field():
- """_Subscription stores granted_qos."""
- async def deliver(t, p, q):
- pass
-
- sub = _Subscription("acct/topic", "acct", deliver, granted_qos=1)
- assert sub.granted_qos == 1
-
- sub0 = _Subscription("acct/topic", "acct", deliver, granted_qos=0)
- assert sub0.granted_qos == 0
-
-
-def test_subscribe_handler_caps_qos_at_1():
- """PKT_SUBSCRIBE grants min(requested, 1) — QoS 2 is capped to 1."""
- reset()
-
- async def _run():
- send, sent = _mock_send()
- session = _WSSession(send, "123456789012")
- await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("sub-client"))
-
- # Subscribe with QoS 0, 1, and 2
- body = _build_subscribe_body(1, [
- ("topic/a", 0),
- ("topic/b", 1),
- ("topic/c", 2), # Should be capped to 1
- ])
- await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
-
- # Find SUBACK in sent messages
- suback_frames = [m for m in sent if m.get("bytes") and (m["bytes"][0] >> 4) == 9]
- assert len(suback_frames) == 1
- suback_data = suback_frames[0]["bytes"]
- # SUBACK: fixed header (1 byte) + remaining length (1 byte) + packet_id (2 bytes) + return codes
- offset = 1
- # Decode remaining length
- multiplier = 1
- remaining = 0
- while True:
- b = suback_data[offset]
- offset += 1
- remaining += (b & 0x7F) * multiplier
- if b & 0x80 == 0:
- break
- multiplier *= 128
- # Skip packet ID
- offset += 2
- # Return codes
- return_codes = list(suback_data[offset:])
- assert return_codes == [0, 1, 1] # QoS 2 capped to 1
-
- await session.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_subscribe_stores_granted_qos_on_session():
- """Session tracks granted QoS per subscription ID."""
- reset()
-
- async def _run():
- send, _ = _mock_send()
- session = _WSSession(send, "123456789012")
- await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("qos-track"))
-
- body = _build_subscribe_body(1, [("sensor/temp", 1)])
- await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
-
- # Session should have one subscription with granted_qos=1
- assert len(session._sub_ids) == 1
- sid = session._sub_ids[0]
- assert session._sub_granted_qos[sid] == 1
-
- await session.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-# ---------------------------------------------------------------------------
-# Task 18.2: QoS 1 delivery with packet ID tracking
-# ---------------------------------------------------------------------------
-
-
-def test_qos1_publish_delivers_with_packet_id():
- """QoS 1 publish to QoS 1 subscriber delivers at QoS 1 with packet ID."""
- reset()
-
- async def _run():
- send, sent = _mock_send()
- session = _WSSession(send, "123456789012")
- await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("qos1-sub"))
-
- # Subscribe at QoS 1
- body = _build_subscribe_body(1, [("test/qos1", 1)])
- await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
-
- # Clear sent to isolate publish frames
- sent.clear()
-
- # Publish at QoS 1 from external source
- await publish("123456789012", "test/qos1", b"hello-qos1", qos=1)
-
- # Check delivered message
- publishes = _extract_publish_frames(sent)
- assert len(publishes) == 1
- topic, payload, qos, packet_id, dup = publishes[0]
- assert topic == "test/qos1"
- assert payload == b"hello-qos1"
- assert qos == 1
- assert packet_id is not None
- assert packet_id >= 1
- assert dup is False
-
- await session.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_qos0_publish_to_qos1_subscriber_delivers_at_qos0():
- """QoS 0 publish to QoS 1 subscriber delivers at QoS 0 (effective = min)."""
- reset()
-
- async def _run():
- send, sent = _mock_send()
- session = _WSSession(send, "123456789012")
- await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("qos-min"))
-
- # Subscribe at QoS 1
- body = _build_subscribe_body(1, [("test/minqos", 1)])
- await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
- sent.clear()
-
- # Publish at QoS 0
- await publish("123456789012", "test/minqos", b"qos0-msg", qos=0)
-
- publishes = _extract_publish_frames(sent)
- assert len(publishes) == 1
- topic, payload, qos, packet_id, dup = publishes[0]
- assert qos == 0
- assert packet_id is None # No packet ID for QoS 0
-
- await session.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_qos1_publish_to_qos0_subscriber_delivers_at_qos0():
- """QoS 1 publish to QoS 0 subscriber delivers at QoS 0 (effective = min)."""
- reset()
-
- async def _run():
- send, sent = _mock_send()
- session = _WSSession(send, "123456789012")
- await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("qos0-sub"))
-
- # Subscribe at QoS 0
- body = _build_subscribe_body(1, [("test/downgrade", 0)])
- await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
- sent.clear()
-
- # Publish at QoS 1
- await publish("123456789012", "test/downgrade", b"downgraded", qos=1)
-
- publishes = _extract_publish_frames(sent)
- assert len(publishes) == 1
- topic, payload, qos, packet_id, dup = publishes[0]
- assert qos == 0
- assert packet_id is None
-
- await session.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_qos1_delivery_tracks_in_flight():
- """QoS 1 delivery stores message in _in_flight dict."""
- reset()
-
- async def _run():
- send, sent = _mock_send()
- session = _WSSession(send, "123456789012")
- await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("inflight"))
-
- # Subscribe at QoS 1
- body = _build_subscribe_body(1, [("test/inflight", 1)])
- await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
- sent.clear()
-
- # Publish at QoS 1
- await publish("123456789012", "test/inflight", b"tracked", qos=1)
-
- # Should have one in-flight message
- assert len(session._in_flight) == 1
- pid = list(session._in_flight.keys())[0]
- msg = session._in_flight[pid]
- assert msg.topic == "test/inflight"
- assert msg.payload == b"tracked"
- assert msg.retransmit_count == 0
-
- await session.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_packet_ids_are_monotonically_increasing():
- """Packet IDs increment monotonically."""
- reset()
-
- async def _run():
- send, _ = _mock_send()
- session = _WSSession(send, "123456789012")
-
- ids = [session._alloc_packet_id() for _ in range(5)]
- assert ids == [1, 2, 3, 4, 5]
-
- asyncio.run(_run())
- reset()
-
-
-def test_packet_ids_wrap_at_65535():
- """Packet IDs wrap from 65535 back to 1."""
- reset()
-
- async def _run():
- send, _ = _mock_send()
- session = _WSSession(send, "123456789012")
- session._next_pid = 65535
-
- pid1 = session._alloc_packet_id()
- pid2 = session._alloc_packet_id()
- assert pid1 == 65535
- assert pid2 == 1 # Wraps back to 1
-
- asyncio.run(_run())
- reset()
-
-
-# ---------------------------------------------------------------------------
-# Task 18.3: PUBACK handling and retransmission
-# ---------------------------------------------------------------------------
-
-
-def test_puback_removes_from_in_flight():
- """PUBACK with matching packet ID removes message from _in_flight."""
- reset()
-
- async def _run():
- send, sent = _mock_send()
- session = _WSSession(send, "123456789012")
- await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("puback-test"))
-
- # Subscribe at QoS 1
- body = _build_subscribe_body(1, [("test/puback", 1)])
- await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
- sent.clear()
-
- # Publish at QoS 1
- await publish("123456789012", "test/puback", b"ack-me", qos=1)
-
- assert len(session._in_flight) == 1
- pid = list(session._in_flight.keys())[0]
-
- # Send PUBACK
- puback_body = struct.pack("!H", pid)
- result = await session.handle_packet(PKT_PUBACK, 0, puback_body)
- assert result is True
- assert len(session._in_flight) == 0
-
- await session.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_puback_unknown_packet_id_is_ignored():
- """PUBACK for unknown packet ID does not crash."""
- reset()
-
- async def _run():
- send, _ = _mock_send()
- session = _WSSession(send, "123456789012")
- await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("puback-unknown"))
-
- # Send PUBACK for non-existent packet ID
- puback_body = struct.pack("!H", 999)
- result = await session.handle_packet(PKT_PUBACK, 0, puback_body)
- assert result is True
- assert len(session._in_flight) == 0
-
- await session.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_retransmit_task_started_on_qos1_delivery():
- """Retransmit background task is started when QoS 1 message is delivered."""
- reset()
-
- async def _run():
- send, sent = _mock_send()
- session = _WSSession(send, "123456789012")
- await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("retransmit"))
-
- assert session._retransmit_task is None
-
- # Subscribe at QoS 1
- body = _build_subscribe_body(1, [("test/retransmit", 1)])
- await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
- sent.clear()
-
- # Publish at QoS 1
- await publish("123456789012", "test/retransmit", b"retry-me", qos=1)
-
- # Retransmit task should be started
- assert session._retransmit_task is not None
- assert not session._retransmit_task.done()
-
- await session.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_cleanup_cancels_retransmit_task():
- """cleanup() cancels the retransmit background task."""
- reset()
-
- async def _run():
- send, sent = _mock_send()
- session = _WSSession(send, "123456789012")
- await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("cleanup-rt"))
-
- # Subscribe at QoS 1
- body = _build_subscribe_body(1, [("test/cleanup", 1)])
- await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
- sent.clear()
-
- # Publish at QoS 1 to start retransmit task
- await publish("123456789012", "test/cleanup", b"clean", qos=1)
- task = session._retransmit_task
- assert task is not None
-
- await session.cleanup()
- assert session._retransmit_task is None
- assert task.done() or task.cancelled()
-
- asyncio.run(_run())
- reset()
-
-
-def test_cleanup_clears_in_flight():
- """cleanup() clears the _in_flight dict."""
- reset()
-
- async def _run():
- send, sent = _mock_send()
- session = _WSSession(send, "123456789012")
- await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("cleanup-if"))
-
- # Subscribe at QoS 1
- body = _build_subscribe_body(1, [("test/clear", 1)])
- await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
- sent.clear()
-
- # Publish at QoS 1
- await publish("123456789012", "test/clear", b"clear-me", qos=1)
- assert len(session._in_flight) == 1
-
- await session.cleanup()
- assert len(session._in_flight) == 0
-
- asyncio.run(_run())
- reset()
-
-
-def test_retransmit_sends_dup_flag():
- """Retransmission sends PUBLISH with DUP flag set."""
- reset()
-
- async def _run():
- send, sent = _mock_send()
- session = _WSSession(send, "123456789012")
- await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("dup-test"))
-
- # Subscribe at QoS 1
- body = _build_subscribe_body(1, [("test/dup", 1)])
- await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
- sent.clear()
-
- # Publish at QoS 1
- await publish("123456789012", "test/dup", b"dup-payload", qos=1)
-
- # Verify initial publish has DUP=False
- publishes = _extract_publish_frames(sent)
- assert len(publishes) == 1
- assert publishes[0][4] is False # dup flag
-
- # Manually trigger retransmission by manipulating sent_at
- pid = list(session._in_flight.keys())[0]
- msg = session._in_flight[pid]
- # Set sent_at far in the past to trigger retransmit
- msg.sent_at = 0
-
- sent.clear()
-
- # Run one iteration of retransmit logic manually
- import asyncio as _asyncio
- now = _asyncio.get_event_loop().time()
- for p, m in list(session._in_flight.items()):
- if now - m.sent_at >= _RETRANSMIT_INTERVAL_SECONDS:
- m.retransmit_count += 1
- m.sent_at = now
- from ministack.services.iot import _make_publish
- await session.send_bytes(
- _make_publish(m.topic, m.payload, qos=1, packet_id=p, dup=True)
- )
-
- # Verify retransmitted publish has DUP=True
- publishes = _extract_publish_frames(sent)
- assert len(publishes) == 1
- topic, payload, qos, packet_id, dup = publishes[0]
- assert topic == "test/dup"
- assert payload == b"dup-payload"
- assert qos == 1
- assert packet_id == pid
- assert dup is True
-
- await session.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_in_flight_message_fields():
- """_InFlightMessage stores all required fields."""
- reset()
-
- async def _run():
- msg = _InFlightMessage(packet_id=42, topic="sensor/data", payload=b"temp=22")
- assert msg.packet_id == 42
- assert msg.topic == "sensor/data"
- assert msg.payload == b"temp=22"
- assert msg.sent_at > 0
- assert msg.retransmit_count == 0
-
- asyncio.run(_run())
- reset()
-
-
-def test_multiple_qos1_messages_get_unique_packet_ids():
- """Multiple QoS 1 deliveries get unique, incrementing packet IDs."""
- reset()
-
- async def _run():
- send, sent = _mock_send()
- session = _WSSession(send, "123456789012")
- await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("multi-pid"))
-
- # Subscribe at QoS 1
- body = _build_subscribe_body(1, [("test/multi", 1)])
- await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
- sent.clear()
-
- # Publish 3 messages at QoS 1
- await publish("123456789012", "test/multi", b"msg1", qos=1)
- await publish("123456789012", "test/multi", b"msg2", qos=1)
- await publish("123456789012", "test/multi", b"msg3", qos=1)
-
- publishes = _extract_publish_frames(sent)
- assert len(publishes) == 3
- pids = [p[3] for p in publishes]
- # All unique
- assert len(set(pids)) == 3
- # Monotonically increasing
- assert pids == sorted(pids)
-
- # All tracked in-flight
- assert len(session._in_flight) == 3
-
- await session.cleanup()
-
- asyncio.run(_run())
- reset()
-
-
-def test_puback_for_first_of_multiple_in_flight():
- """PUBACK removes only the specific packet ID from in-flight."""
- reset()
-
- async def _run():
- send, sent = _mock_send()
- session = _WSSession(send, "123456789012")
- await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("selective-ack"))
-
- # Subscribe at QoS 1
- body = _build_subscribe_body(1, [("test/selective", 1)])
- await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
- sent.clear()
-
- # Publish 3 messages
- await publish("123456789012", "test/selective", b"a", qos=1)
- await publish("123456789012", "test/selective", b"b", qos=1)
- await publish("123456789012", "test/selective", b"c", qos=1)
-
- assert len(session._in_flight) == 3
- pids = sorted(session._in_flight.keys())
-
- # ACK the middle one
- puback_body = struct.pack("!H", pids[1])
- await session.handle_packet(PKT_PUBACK, 0, puback_body)
-
- assert len(session._in_flight) == 2
- assert pids[1] not in session._in_flight
- assert pids[0] in session._in_flight
- assert pids[2] in session._in_flight
-
- await session.cleanup()
-
- asyncio.run(_run())
- reset()
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index d2ce6827..bc631632 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -801,7 +801,81 @@ def test_sfn_aws_sdk_lambda_get_alias_and_configuration(sfn_sync, lam):
assert output["config"]["FunctionName"] == fn
assert output["config"]["Version"] == version
- sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+
+def test_sfn_aws_sdk_lambda_respects_caller_account():
+ """aws-sdk:lambda dispatch threads the caller's account through to the
+ Lambda lookup. Previously the dispatcher hardcoded ``Credential=test/...``
+ in its synthetic Authorization header, so an SFN execution running under
+ a non-default 12-digit account would resolve into the default account
+ and fail to find Lambdas created in the caller's own account.
+ """
+ import boto3
+ from botocore.config import Config as _Config
+
+ ACCOUNT = "987654321098"
+ suffix = _uuid_mod.uuid4().hex[:8]
+ fn = f"sfn-acct-{suffix}"
+ sm_name = f"sfn-acct-{suffix}"
+
+ def _client(service):
+ return boto3.client(
+ service,
+ endpoint_url="http://localhost:4566",
+ aws_access_key_id=ACCOUNT,
+ aws_secret_access_key="secret",
+ region_name="us-east-1",
+ config=_Config(
+ retries={"mode": "standard"},
+ # SFN's start_sync_execution prepends `sync-` to the host; the
+ # default sfn_sync fixture disables that, we need the same.
+ inject_host_prefix=False,
+ ),
+ )
+
+ lam_a = _client("lambda")
+ sfn_a = _client("stepfunctions")
+
+ lam_a.create_function(
+ FunctionName=fn,
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip("def handler(e, c): return {'ok': True}")},
+ )
+
+ function_arn = f"arn:aws:lambda:us-east-1:{ACCOUNT}:function:{fn}"
+ definition = json.dumps({
+ "StartAt": "ReadConfig",
+ "States": {
+ "ReadConfig": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::aws-sdk:lambda:getFunctionConfiguration",
+ "Parameters": {"FunctionName.$": "$.functionName"},
+ "End": True,
+ },
+ },
+ })
+ sm_arn = sfn_a.create_state_machine(
+ name=sm_name,
+ definition=definition,
+ roleArn=f"arn:aws:iam::{ACCOUNT}:role/sfn-role",
+ )["stateMachineArn"]
+
+ resp = sfn_a.start_sync_execution(
+ stateMachineArn=sm_arn,
+ input=json.dumps({"functionName": function_arn}),
+ )
+ assert resp["status"] == "SUCCEEDED", (
+ f"Execution failed under non-default account: "
+ f"{resp.get('error')} — {resp.get('cause')}"
+ )
+ output = json.loads(resp["output"])
+ assert output["FunctionName"] == fn
+ # FunctionArn must come back scoped to OUR account, not the default
+ assert output["FunctionArn"] == function_arn
+
+ lam_a.delete_function(FunctionName=fn)
+ sfn_a.delete_state_machine(stateMachineArn=sm_arn)
def test_sfn_optimized_start_execution_returns_execution_arn(sfn, sfn_sync):