Skip to content

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

fix(iot): write Jobs MQTT messages as AWS does (#2256)

iot-rocketc03247812fbf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7c970023..adaf7d8a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **IoT — Jobs MQTT messages are written as AWS writes them** — the `$aws/things/<thing>/jobs` messages were spaced, ASCII-escaped JSON with `clientToken` last, a `thingName` and an empty `statusDetails` in the `get` and `start-next` executions and no `jobDocument` in an execution whose document is `null`; they are now compact UTF-8 in AWS's member order with `clientToken` first, the job document as the HTTP plane sends it, characters outside the BMP escaped in `statusDetails` and in the update and rejected responses, and `"jobDocument":null` kept. Contributed by @iot-rocket.
+- **IoT Jobs — a status a device may not set is refused first** — `UpdateJobExecution` (HTTP and the MQTT `update` topic) to QUEUED, CANCELED or TIMED_OUT answered `ResourceNotFoundException` for an unknown job or thing and the version error for a stale `expectedVersion`; it now refuses the status first with `InvalidStateTransitionException` (over MQTT `InvalidStateTransition` without `executionState`), as AWS does. Contributed by @iot-rocket.
- **IoT Jobs — a status a device may not set is refused first** — `UpdateJobExecution` (HTTP and the MQTT `update` topic) to QUEUED, CANCELED or TIMED_OUT answered `ResourceNotFoundException` for an unknown job or thing and the version error for a stale `expectedVersion`; it now refuses the status first with `InvalidStateTransitionException` (over MQTT `InvalidStateTransition` without `executionState`), as AWS does. Contributed by @iot-rocket.
- **IoT — unknown topic rules answer 401** — `GetTopicRule`, `ReplaceTopicRule`, `EnableTopicRule` and `DisableTopicRule` on a rule that does not exist answered 404 `ResourceNotFoundException` and `DeleteTopicRule` answered 200; they now answer 401 `UnauthorizedException` (`Access to topic rule '<name>' was denied`) as AWS does, and `GetTopicRule`, `ReplaceTopicRule` and `DeleteTopicRule` refuse a name outside the rule name pattern with the 400 `InvalidRequestException` that `EnableTopicRule` gives. Contributed by @iot-rocket.
- **S3 — bucket configuration validation** — `PutBucketVersioning` accepted any `Status` or `MfaDelete` and stored it, `PutBucketLifecycleConfiguration` accepted any rule `Status` or transition `StorageClass` and non-positive days, and `PutBucketEncryption` accepted any `SSEAlgorithm`. Out-of-enum values now return 400 `MalformedXML` (`The XML you provided was not well-formed or did not validate against our published schema`, now the message for every `MalformedXML`). A zero or negative `Expiration` `Days` or `NoncurrentVersionExpiration` `NoncurrentDays` returns 400 `InvalidArgument` (`'Days' for Expiration action must be a positive integer`).
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 37eccde9..02cad4ad 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -8230,16 +8230,75 @@ def jobs_job_document(job_id: str) -> str:
return document
-def _jobs_job_document_object(job_id: str):
- """The job document as a JSON object — the shape AWS serves over MQTT
- (over HTTP the same document stays a string; see jobs-mqtt-api vs the
- REST JobExecution shape). A stored document that is not valid JSON
- passes through as the raw string rather than being invented into one."""
+class _JobsDocumentText(str):
+ """A job document in its device spelling, written into a Jobs MQTT message as it is."""
+
+
+_JOBS_NON_BMP_RE = re.compile("[\\U00010000-\\U0010FFFF]")
+
+
+def _jobs_utf16_escape(match: re.Match) -> str:
+ """A character outside the BMP as the escapes of its UTF-16 surrogate pair."""
+ code = ord(match.group()) - 0x10000
+ return f"\\u{0xD800 + (code >> 10):04X}\\u{0xDC00 + (code & 0x3FF):04X}"
+
+
+def _jobs_job_document_object(job_id: str, escape_non_bmp: bool = False):
+ """The job document a Jobs MQTT message carries; a stored text that is not JSON goes out as a string."""
document = jobs_job_document(job_id)
try:
- return json.loads(document)
+ json.loads(document)
except ValueError:
return document
+ if escape_non_bmp:
+ document = _JOBS_NON_BMP_RE.sub(_jobs_utf16_escape, document)
+ return _JobsDocumentText(document)
+
+
+_JOBS_MQTT_EXECUTION_MEMBERS = (
+ "jobId", "status", "statusDetails", "queuedAt", "startedAt", "lastUpdatedAt",
+ "versionNumber", "executionNumber", "approximateSecondsBeforeTimedOut", "jobDocument",
+)
+
+
+def _jobs_mqtt_execution(execution: dict, document) -> dict:
+ """A JobExecution as Jobs MQTT messages carry it: AWS's member order, no thingName, no empty statusDetails."""
+ view = jobs_execution_view(execution, document)
+ return {
+ key: view[key] for key in _JOBS_MQTT_EXECUTION_MEMBERS
+ if key in view and (key != "statusDetails" or view[key])
+ }
+
+
+def _jobs_mqtt_head(client_token, timestamp: int) -> dict:
+ """The members a Jobs MQTT response starts with: the request's clientToken, if any, then timestamp."""
+ head = {} if client_token is None else {"clientToken": client_token}
+ head["timestamp"] = timestamp
+ return head
+
+
+def _jobs_execution_state(execution: dict) -> dict:
+ """The executionState of a Jobs MQTT response: statusDetails only when set."""
+ state = {"status": execution["status"]}
+ if execution.get("statusDetails"):
+ state["statusDetails"] = execution["statusDetails"]
+ state["versionNumber"] = execution["versionNumber"]
+ return state
+
+
+def _jobs_mqtt_json(value) -> str:
+ """Compact JSON of a Jobs MQTT message: characters outside the BMP escaped, a job document's text kept as it is."""
+ if isinstance(value, _JobsDocumentText):
+ return value
+ if isinstance(value, dict):
+ return "{" + ",".join(
+ f"{_jobs_mqtt_json(key)}:{_jobs_mqtt_json(member)}" for key, member in value.items()
+ ) + "}"
+ if isinstance(value, list):
+ return "[" + ",".join(map(_jobs_mqtt_json, value)) + "]"
+ if isinstance(value, str):
+ return _JOBS_NON_BMP_RE.sub(_jobs_utf16_escape, _jobs_device_json(value))
+ return _jobs_device_json(value)
def jobs_update_execution(
@@ -8325,7 +8384,7 @@ def jobs_execution_view(execution: dict, document: str | dict | None) -> dict:
reference words every stamp as "the time, in seconds since the epoch"),
flat statusDetails map. Shared by the iot-jobs-data HTTP plane (which
passes ``document`` as the string AWS serves there) and the
- jobs-over-MQTT bridge (which passes the parsed object) so both speak one
+ jobs-over-MQTT bridge (which passes the document as JSON) so both speak one
shape."""
view = {
"jobId": execution["jobId"],
@@ -8354,11 +8413,11 @@ def jobs_execution_summary(execution: dict) -> dict:
"jobId": execution["jobId"],
"queuedAt": _jobs_ms_to_long_s(execution["queuedAt"]),
"lastUpdatedAt": _jobs_ms_to_long_s(execution["lastUpdatedAt"]),
- "versionNumber": execution["versionNumber"],
- "executionNumber": execution["executionNumber"],
}
if execution.get("startedAt") is not None:
entry["startedAt"] = _jobs_ms_to_long_s(execution["startedAt"])
+ entry["executionNumber"] = execution["executionNumber"]
+ entry["versionNumber"] = execution["versionNumber"]
return entry
@@ -8396,16 +8455,10 @@ async def jobs_notify_thing(
pending = jobs_pending_for_thing(thing_name)
nxt = jobs_start_next_execution(thing_name, peek=True)
next_view = (
- jobs_execution_view(nxt, _jobs_job_document_object(nxt["jobId"]))
+ _jobs_mqtt_execution(nxt, _jobs_job_document_object(nxt["jobId"]))
if nxt is not None
else None
)
- if next_view is not None:
- # AWS sends no thingName and no empty statusDetails here (measured
- # eu-central-1 2026-10-05).
- del next_view["thingName"]
- if not next_view["statusDetails"]:
- del next_view["statusDetails"]
ts = int(time.time())
jobs_by_status: dict = {}
for execution in pending:
@@ -8415,7 +8468,7 @@ async def jobs_notify_thing(
base = f"$aws/things/{thing_name}/jobs"
await broker_publish(
account_id, region, f"{base}/notify",
- json.dumps({"timestamp": ts, "jobs": jobs_by_status}).encode("utf-8"), qos=1,
+ _jobs_mqtt_json({"timestamp": ts, "jobs": jobs_by_status}).encode("utf-8"), qos=1,
)
next_job_id = nxt["jobId"] if nxt is not None else None
if next_job_id == prev_next_job_id:
@@ -8425,7 +8478,7 @@ async def jobs_notify_thing(
notify_next["execution"] = next_view
await broker_publish(
account_id, region, f"{base}/notify-next",
- json.dumps(notify_next).encode("utf-8"), qos=1,
+ _jobs_mqtt_json(notify_next).encode("utf-8"), qos=1,
)
@@ -9478,11 +9531,11 @@ def _jobs_rejected(
enum (InvalidRequest, InvalidJson, ResourceNotFound, VersionMismatch,
InvalidStateTransition, TerminalStateReached), never a numeric HTTP
status."""
- doc = {"code": code, "message": message, "timestamp": int(time.time())}
+ doc = _jobs_mqtt_head(client_token, int(time.time()))
if execution_state is not None:
doc["executionState"] = execution_state
- if client_token is not None:
- doc["clientToken"] = client_token
+ doc["code"] = code
+ doc["message"] = message
return doc
@@ -9520,10 +9573,7 @@ def _jobs_error_tuple_to_rejected(
# A refused status carries no executionState.
refused_status = message.startswith("The status of job execution cannot be changed")
if code in ("VersionMismatch", "InvalidStateTransition") and execution is not None and not refused_status:
- execution_state = {
- "status": execution["status"],
- "versionNumber": execution["versionNumber"],
- }
+ execution_state = _jobs_execution_state(execution)
return _jobs_rejected(code, message, client_token, execution_state)
@@ -9554,7 +9604,7 @@ async def _handle_jobs_publish(
await broker_publish(
account_id, region,
f"{base}/{suffix_base}/{kind}",
- json.dumps(doc).encode("utf-8"), qos=1,
+ _jobs_mqtt_json(doc).encode("utf-8"), qos=1,
)
try:
@@ -9582,17 +9632,13 @@ async def _handle_jobs_publish(
if verb == "get" and job_id is None:
with request_scope(account_id, region):
pending = jobs_pending_for_thing(thing)
- doc = {
- "timestamp": ts,
- "inProgressJobs": [
- jobs_execution_summary(e) for e in pending if e["status"] == "IN_PROGRESS"
- ],
- "queuedJobs": [
- jobs_execution_summary(e) for e in pending if e["status"] == "QUEUED"
- ],
- }
- if client_token is not None:
- doc["clientToken"] = client_token
+ doc = _jobs_mqtt_head(client_token, ts)
+ doc["inProgressJobs"] = [
+ jobs_execution_summary(e) for e in pending if e["status"] == "IN_PROGRESS"
+ ]
+ doc["queuedJobs"] = [
+ jobs_execution_summary(e) for e in pending if e["status"] == "QUEUED"
+ ]
await _respond("accepted", doc)
return
@@ -9606,11 +9652,9 @@ async def _handle_jobs_publish(
if execution is not None
else None
)
- doc = {"timestamp": ts}
+ doc = _jobs_mqtt_head(client_token, ts)
if execution is not None:
- doc["execution"] = jobs_execution_view(execution, document)
- if client_token is not None:
- doc["clientToken"] = client_token
+ doc["execution"] = _jobs_mqtt_execution(execution, document)
await _respond("accepted", doc)
# No notify / notify-next here: QUEUED -> IN_PROGRESS keeps the
# execution both pending and at the front of the queue, and AWS stays
@@ -9647,11 +9691,9 @@ async def _handle_jobs_publish(
await _respond("rejected", _jobs_error_tuple_to_rejected(error, client_token))
return
# An idle thing's "$next" mirrors the HTTP plane's empty structure.
- doc = {"timestamp": ts}
+ doc = _jobs_mqtt_head(client_token, ts)
if execution is not None:
- doc["execution"] = jobs_execution_view(execution, document)
- if client_token is not None:
- doc["clientToken"] = client_token
+ doc["execution"] = _jobs_mqtt_execution(execution, document)
await _respond("accepted", doc)
return
@@ -9670,18 +9712,12 @@ async def _handle_jobs_publish(
"rejected", _jobs_error_tuple_to_rejected(error, client_token, current)
)
return
- doc = {"timestamp": ts}
+ doc = _jobs_mqtt_head(client_token, ts)
if request.get("includeJobExecutionState"):
- doc["executionState"] = {
- "status": execution["status"],
- "statusDetails": execution.get("statusDetails") or {},
- "versionNumber": execution["versionNumber"],
- }
+ doc["executionState"] = _jobs_execution_state(execution)
if request.get("includeJobDocument"):
with request_scope(account_id, region):
- doc["jobDocument"] = _jobs_job_document_object(job_id)
- if client_token is not None:
- doc["clientToken"] = client_token
+ doc["jobDocument"] = _jobs_job_document_object(job_id, escape_non_bmp=True)
await _respond("accepted", doc)
if execution["status"] in ("SUCCEEDED", "FAILED", "REJECTED"):
# A terminal report removed the execution from the pending set. AWS
diff --git a/tests/test_iot_jobs_data.py b/tests/test_iot_jobs_data.py
index 02106096..5435fd90 100644
--- a/tests/test_iot_jobs_data.py
+++ b/tests/test_iot_jobs_data.py
@@ -14,6 +14,7 @@ data-plane responses use raw `long` shapes carrying whole epoch seconds
import json
import os
+import re
import time
import urllib.error
import urllib.request
@@ -3825,6 +3826,11 @@ def _frames_by_topic(received):
return {topic: json.loads(payload) for topic, payload in received}
+def _unstamped(payload):
+ """A raw Jobs MQTT payload with each epoch-seconds stamp as 0, every other byte as sent."""
+ return re.sub(r'(?<=":)\d{10}(?=[,}])', "0", payload.decode("utf-8"))
+
+
def test_jobs_mqtt_create_job_notifies_and_get_lists(iot_client, iot_data_client):
"""CreateJob publishes notify (per-status aggregate) + notify-next (full
execution incl. the jobDocument as an object) to each target thing; a
@@ -3877,6 +3883,58 @@ def test_jobs_mqtt_create_job_notifies_and_get_lists(iot_client, iot_data_client
_assert_epoch_seconds(doc["queuedJobs"][0]["queuedAt"])
+def test_jobs_mqtt_messages_are_compact_in_aws_member_order(iot_client, iot_data_client):
+ """Jobs MQTT messages are compact UTF-8 in AWS's member order, clientToken first, without thingName."""
+ thing = _unique("jobs-mqtt-raw")
+ job_id = _unique("job")
+ thing_arn = _create_thing(iot_client, thing)
+ base = f"$aws/things/{thing}/jobs"
+ summary = (
+ f'{{"jobId":"{job_id}","queuedAt":0,"lastUpdatedAt":0,'
+ '"executionNumber":1,"versionNumber":1}'
+ )
+ execution = (
+ f'{{"jobId":"{job_id}","status":"QUEUED","queuedAt":0,"lastUpdatedAt":0,'
+ '"versionNumber":1,"executionNumber":1,"jobDocument":{"s":"\u00e9 \U0001f600","f":1.0E21}}'
+ )
+ try:
+ received = _collect_shadow_frames(
+ f"{base}/#",
+ lambda: iot_client.create_job(
+ jobId=job_id,
+ targets=[thing_arn],
+ document='{"s": "\\u00e9 \\ud83d\\ude00", "f": 1e21}',
+ ),
+ want=2,
+ )
+ frames = {topic: _unstamped(payload) for topic, payload in received}
+ assert frames[f"{base}/notify"] == f'{{"timestamp":0,"jobs":{{"QUEUED":[{summary}]}}}}'
+ assert frames[f"{base}/notify-next"] == f'{{"timestamp":0,"execution":{execution}}}'
+ for topic, request, accepted in (
+ (
+ "get",
+ {"clientToken": "tok"},
+ f'{{"clientToken":"tok","timestamp":0,"inProgressJobs":[],"queuedJobs":[{summary}]}}',
+ ),
+ (
+ f"{job_id}/get",
+ {"clientToken": "tok"},
+ f'{{"clientToken":"tok","timestamp":0,"execution":{execution}}}',
+ ),
+ (f"{job_id}/get", {}, f'{{"timestamp":0,"execution":{execution}}}'),
+ ):
+ received = _collect_shadow_frames(
+ f"{base}/{topic}/accepted",
+ lambda topic=topic, request=request: _mqtt_publish(
+ topic=f"{base}/{topic}", payload=json.dumps(request).encode()
+ ),
+ want=1,
+ )
+ assert [_unstamped(payload) for _, payload in received] == [accepted]
+ finally:
+ _cleanup(iot_client, jobs=[job_id], things=[thing])
+
+
def test_jobs_mqtt_create_behind_existing_job_no_notify_next(
iot_client, iot_data_client
):
@@ -4056,6 +4114,60 @@ def test_jobs_mqtt_update_include_flags_and_terminal_notify(
) < topics.index(f"{base}/notify-next")
+def test_jobs_mqtt_status_details_and_update_responses_escape_non_bmp(
+ iot_client, iot_data_client
+):
+ """statusDetails and update responses escape characters beyond the BMP; the job document elsewhere does not."""
+ thing = _unique("jobs-mqtt-bmp")
+ job_id = _unique("job")
+ thing_arn = _create_thing(iot_client, thing)
+ base = f"$aws/things/{thing}/jobs"
+ details = '"statusDetails":{"k":"\u00e9 \\uD83D\\uDE00"}'
+ try:
+ iot_client.create_job(
+ jobId=job_id, targets=[thing_arn], document='{"s": "\\u00e9 \\ud83d\\ude00"}'
+ )
+ for topic, request, answer, expected in (
+ (
+ "start-next",
+ {"statusDetails": {"k": "\u00e9 \U0001f600"}, "clientToken": "tok"},
+ "accepted",
+ f'{{"clientToken":"tok","timestamp":0,"execution":{{"jobId":"{job_id}",'
+ f'"status":"IN_PROGRESS",{details},"queuedAt":0,"startedAt":0,"lastUpdatedAt":0,'
+ '"versionNumber":2,"executionNumber":1,"jobDocument":{"s":"\u00e9 \U0001f600"}}}',
+ ),
+ (
+ f"{job_id}/update",
+ {
+ "status": "IN_PROGRESS",
+ "includeJobExecutionState": True,
+ "includeJobDocument": True,
+ "clientToken": "tok",
+ },
+ "accepted",
+ f'{{"clientToken":"tok","timestamp":0,"executionState":{{"status":"IN_PROGRESS",{details},'
+ '"versionNumber":3},"jobDocument":{"s":"\u00e9 \\uD83D\\uDE00"}}',
+ ),
+ (
+ f"{job_id}/update",
+ {"status": "IN_PROGRESS", "expectedVersion": 9},
+ "rejected",
+ f'{{"timestamp":0,"executionState":{{"status":"IN_PROGRESS",{details},"versionNumber":3}},'
+ '"code":"VersionMismatch","message":"Expected version 9 but found version 3"}',
+ ),
+ ):
+ received = _collect_shadow_frames(
+ f"{base}/{topic}/{answer}",
+ lambda topic=topic, request=request: _mqtt_publish(
+ topic=f"{base}/{topic}", payload=json.dumps(request).encode()
+ ),
+ want=1,
+ )
+ assert [_unstamped(payload) for _, payload in received] == [expected]
+ finally:
+ _cleanup(iot_client, jobs=[job_id], things=[thing])
+
+
def test_jobs_mqtt_presigned_urls(iot_client, iot_data_client, s3, iam):
"""Over MQTT the document carries presigned URLs too, on the broker host without its IoT labels."""
thing, bucket, job_id = _unique("jobs-mqtt-url"), _unique("jobs-presign"), _unique("job")
@@ -4378,6 +4490,38 @@ def test_jobs_mqtt_job_document_leaves_out_null_members(iot_client, iot_data_cli
assert execution["jobDocument"] == {"o": {"k": [None]}, "f": ["Infinity", 2.5]}
+def test_jobs_mqtt_null_job_document_is_sent_as_null(iot_client, iot_data_client):
+ """A job document that is JSON null reaches the device as "jobDocument":null on every MQTT path."""
+ thing = _unique("jobs-mqtt-null")
+ job_id = _unique("job")
+ thing_arn = _create_thing(iot_client, thing)
+ base = f"$aws/things/{thing}/jobs"
+ try:
+ received = _collect_shadow_frames(
+ f"{base}/notify-next",
+ lambda: iot_client.create_job(jobId=job_id, targets=[thing_arn], document="null"),
+ want=1,
+ )
+ documents = [json.loads(received[0][1])["execution"]]
+ for topic, request in (
+ (f"{job_id}/get", {}),
+ ("start-next", {}),
+ (f"{job_id}/update", {"status": "SUCCEEDED", "includeJobDocument": True}),
+ ):
+ received = _collect_shadow_frames(
+ f"{base}/{topic}/accepted",
+ lambda topic=topic, request=request: _mqtt_publish(
+ topic=f"{base}/{topic}", payload=json.dumps(request).encode()
+ ),
+ want=1,
+ )
+ accepted = json.loads(received[0][1])
+ documents.append(accepted.get("execution", accepted))
+ assert [document.get("jobDocument", "absent") for document in documents] == [None] * 4
+ finally:
+ _cleanup(iot_client, jobs=[job_id], things=[thing])
+
+
def test_jobs_mqtt_non_object_payload_rejected(iot_client, iot_data_client):
"""A payload that parses as JSON but is not an object (an array, say) is
rejected with the InvalidJson code instead of being coerced to {}."""