Skip to content

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

fix(iot): refuse NaN and Infinity in job documents and shadow requests (#2281)

iot-rocket6ae20f676de6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1078bb01..06c1d7a1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **IoT — `NaN` and `Infinity` in job documents and shadow updates** — `CreateJob` and `CreateJobTemplate` (inline and `documentSource`) and `UpdateThingShadow` (HTTP and the MQTT `update`, `get` and `delete` topics) accepted `NaN`, `Infinity` and `-Infinity`, and a shadow wrote them back as bare tokens, which is not JSON; they are now refused as invalid JSON with the messages AWS gives (`Payload contains invalid json` for shadows, also for any other invalid shadow payload), and a shadow number beyond a double's range, such as `1E400`, is stored as the string `"Infinity"` or `"-Infinity"` as on AWS. Contributed by @iot-rocket.
- **AppSync — GraphQL requests under `AUTH=true` follow the API's authentication type** — a GraphQL call to `/v1/apis/{apiId}/graphql` signed with an IAM key was authorized as `appsync:UpdateGraphqlApi` whatever the API's authentication type, and the API's own host served an `AWS_IAM` API to any signed call; an API key request now ignores its signature, and a SigV4 request to an `AWS_IAM` API is authorized on both endpoints as `appsync:GraphQL` on each top-level field, answering 401 `Permission denied` when no field is allowed, a field error for each denied one, and 400 `BadRequestException` for a wrong signature. Contributed by @iot-rocket.
- **Auth — a signed call to a REST API method without authorization is anonymous to the API policy** — under `AUTH=true` a SigV4-signed call to a method whose `authorizationType` is `NONE` was judged as its signer, so a user the API policy names, or one whose identity policy allows the invoke, got through; API Gateway evaluates every call to such a method as anonymous, signed or not, and now so does MiniStack, answering `ACCESS_DENIED` unless the policy allows everyone. Contributed by @iot-rocket.
- **API Gateway — methods without `AWS_IAM` authorization read no credentials under `AUTH=true`** — a REST method with `NONE` or `COGNITO_USER_POOLS` authorization, or an HTTP API route without authorization, refused a SigV4-signed caller whose policies did not allow `execute-api:Invoke` or whose signature failed; such a call now reaches the method, and its own authorizer if it has one, whatever it is signed with. Contributed by @iot-rocket.
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 25335e5e..901fe48a 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -6726,11 +6726,12 @@ def _job_document_s3_location(source: str) -> tuple[str, str]:
def _job_document_is_json(document: str) -> bool:
- """Whether a job document is JSON nested no deeper than AWS accepts."""
+ """Whether a job document is JSON (NaN and Infinity are not) nested no deeper than AWS accepts."""
from ministack.services.apigateway_v1 import _json_depth
+ from ministack.services.eventbridge import _reject_json_constant
try:
- value = json.loads(document)
+ value = json.loads(document, parse_constant=_reject_json_constant)
except (ValueError, RecursionError):
return False
return _json_depth(value) <= _JOB_DOCUMENT_MAX_DEPTH
@@ -8614,6 +8615,21 @@ def _shadow_error(status: int, message: str) -> tuple:
return status, {"message": message}
+def _shadow_number(text: str):
+ """A JSON number with a fraction or exponent; one beyond a double's range is stored as AWS stores it."""
+ value = float(text)
+ if math.isfinite(value):
+ return value
+ return "Infinity" if value > 0 else "-Infinity"
+
+
+def parse_shadow_request(payload):
+ """A shadow request payload as AWS reads it; ValueError when it is not JSON (NaN and Infinity are not)."""
+ from ministack.services.eventbridge import _reject_json_constant
+
+ return json.loads(payload, parse_constant=_reject_json_constant, parse_float=_shadow_number)
+
+
def update_thing_shadow(thing_name: str, shadow_name: str, request: dict) -> tuple:
"""Merge ``request`` into the shadow. Returns (status, response_doc)."""
if not isinstance(request, dict) or not isinstance(request.get("state"), dict):
@@ -9907,11 +9923,11 @@ async def _handle_shadow_publish(
)
try:
- request = json.loads(payload) if payload else {}
+ request = parse_shadow_request(payload) if payload else {}
except (ValueError, UnicodeDecodeError):
# All three request verbs reject malformed JSON, as on AWS — a `get`
# or `delete` payload is optional but must parse when present.
- await _respond(f"{verb}/rejected", _shadow_rejected(400, "invalid json"))
+ await _respond(f"{verb}/rejected", _shadow_rejected(400, "Payload contains invalid json"))
return
if not isinstance(request, dict):
request = {}
diff --git a/ministack/services/iot_data.py b/ministack/services/iot_data.py
index b842495c..078a960e 100644
--- a/ministack/services/iot_data.py
+++ b/ministack/services/iot_data.py
@@ -163,9 +163,9 @@ async def _shadow(method: str, path: str, body: bytes, qp: dict) -> tuple:
status, doc = _iot_module.get_thing_shadow(thing, shadow_name)
elif method == "POST":
try:
- request = json.loads(body) if body else {}
- except json.JSONDecodeError:
- return error_response_json("InvalidRequestException", "Invalid JSON", 400)
+ request = _iot_module.parse_shadow_request(body) if body else {}
+ except ValueError:
+ return error_response_json("InvalidRequestException", "Payload contains invalid json", 400)
# Snapshot around the mutation: the store hands back live dicts, and
# the documents notification needs the before/after pair (same
# discipline as the MQTT bridge).
diff --git a/tests/test_iot_data.py b/tests/test_iot_data.py
index 8afcc3ac..6e551714 100644
--- a/tests/test_iot_data.py
+++ b/tests/test_iot_data.py
@@ -1251,6 +1251,38 @@ def test_update_thing_shadow_version_conflict(iot_data_client):
assert ei.value.response["Error"]["Code"] == "ConflictException"
+def test_update_thing_shadow_refuses_nan_and_infinity(iot_data_client):
+ """NaN, Infinity and -Infinity are not JSON: the update is refused as any invalid payload is."""
+ thing = _unique("dev")
+ for payload in (
+ b'{"state": {"reported": {"a": NaN}}}',
+ b'{"state": {"reported": {"a": Infinity}}}',
+ b'{"state": {"reported": {"a": -Infinity}}}',
+ b"not json",
+ ):
+ with pytest.raises(ClientError) as ei:
+ iot_data_client.update_thing_shadow(thingName=thing, payload=payload)
+ err = ei.value.response
+ assert err["ResponseMetadata"]["HTTPStatusCode"] == 400, payload
+ assert err["Error"]["Code"] == "InvalidRequestException"
+ assert err["Error"]["Message"] == "Payload contains invalid json"
+ with pytest.raises(ClientError) as ei:
+ iot_data_client.get_thing_shadow(thingName=thing)
+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_update_thing_shadow_number_beyond_a_double_is_infinity_text(iot_data_client):
+ """A number beyond a double's range is stored and echoed as the string "Infinity" or "-Infinity"."""
+ thing = _unique("dev")
+ resp = iot_data_client.update_thing_shadow(
+ thingName=thing, payload=b'{"state": {"reported": {"a": 1E400, "b": -1E400, "c": 2.5}}}'
+ )
+ reported = {"a": "Infinity", "b": "-Infinity", "c": 2.5}
+ assert _read_shadow(resp)["state"]["reported"] == reported
+ got = _read_shadow(iot_data_client.get_thing_shadow(thingName=thing))
+ assert got["state"]["reported"] == reported
+
+
# ---------------------------------------------------------------------------
# Topic-rule routing (publish → rule → Lambda)
# ---------------------------------------------------------------------------
@@ -2549,6 +2581,33 @@ def test_shadow_get_missing_over_mqtt_rejected_404(iot_data_client):
assert thing in doc["message"]
+def test_shadow_requests_over_mqtt_refuse_nan_and_infinity(iot_data_client):
+ """NaN and Infinity reject every request verb; a number beyond a double's range becomes "Infinity"."""
+ thing = _unique("shadow-nan")
+ base = f"$aws/things/{thing}/shadow"
+ refused = [
+ ("update", b'{"state": {"reported": {"a": NaN}}}'),
+ ("update", b'{"state": {"reported": {"a": Infinity}}}'),
+ ("update", b'{"state": {"reported": {"a": -Infinity}}}'),
+ ("get", b'{"clientToken": "c", "a": NaN}'),
+ ("delete", b'{"clientToken": "c", "a": NaN}'),
+ ]
+
+ def _publish_all():
+ for verb, payload in [*refused, ("update", b'{"state": {"reported": {"a": 1E400}}}')]:
+ iot_data_client.publish(topic=f"{base}/{verb}", payload=payload)
+
+ # Five rejections, then update/accepted and update/documents.
+ received = _collect_shadow_frames(f"{base}/+/+", _publish_all, want=7)
+ frames = [(topic[len(base) + 1:], json.loads(payload)) for topic, payload in received]
+ rejected = [(topic, doc) for topic, doc in frames if topic.endswith("/rejected")]
+ assert sorted(topic for topic, _doc in rejected) == sorted(f"{verb}/rejected" for verb, _p in refused)
+ assert all(doc == {"code": 400, "message": "Payload contains invalid json"} for _t, doc in rejected)
+ assert dict(frames)["update/accepted"]["state"] == {"reported": {"a": "Infinity"}}
+ shadow = _read_shadow(iot_data_client.get_thing_shadow(thingName=thing))
+ assert shadow["state"]["reported"] == {"a": "Infinity"}
+
+
async def _ws_publish_shadow_and_collect(
ws_url, sub_filter, pub_topic, pub_payload, received, want
):
diff --git a/tests/test_iot_jobs_data.py b/tests/test_iot_jobs_data.py
index bd033324..dcd54916 100644
--- a/tests/test_iot_jobs_data.py
+++ b/tests/test_iot_jobs_data.py
@@ -423,6 +423,38 @@ def test_iot_jobs_document_with_unterminated_strings_is_refused(iot_client):
_cleanup(iot_client, things=[thing])
+def test_iot_jobs_document_nan_and_infinity_are_refused(iot_client, s3):
+ """NaN, Infinity and -Infinity refuse the job or template; a number beyond a double's range is JSON."""
+ thing, bucket = _unique("jobs-thing"), _unique("jobs-doc")
+ jobs, templates = [], []
+ try:
+ thing_arn = _create_thing(iot_client, thing)
+ s3.create_bucket(Bucket=bucket)
+ for index, value in enumerate(("NaN", "Infinity", "-Infinity", "1E400")):
+ document = '{"a": ' + value + "}"
+ s3.put_object(Bucket=bucket, Key=f"{index}.json", Body=document)
+ source = f"s3://{bucket}/{index}.json"
+ for request, where in (({"document": document}, "request input"), ({"documentSource": source}, source)):
+ if value == "1E400":
+ jobs.append(_unique("job"))
+ iot_client.create_job(jobId=jobs[-1], targets=[thing_arn], **request)
+ assert iot_client.get_job_document(jobId=jobs[-1])["document"] == document
+ templates.append(_unique("tmpl"))
+ iot_client.create_job_template(jobTemplateId=templates[-1], description="d", **request)
+ continue
+ message = f"Job document located at {where} is an invalid JSON document."
+ with pytest.raises(ClientError) as ei:
+ iot_client.create_job(jobId=_unique("job"), targets=[thing_arn], **request)
+ assert _error(ei) == (400, "InvalidRequestException", message), value
+ with pytest.raises(ClientError) as ei:
+ iot_client.create_job_template(jobTemplateId=_unique("tmpl"), description="d", **request)
+ assert _error(ei) == (400, "InvalidRequestException", message), value
+ finally:
+ _delete_templates(iot_client, *templates)
+ _cleanup(iot_client, jobs=jobs, things=[thing])
+ _delete_bucket(s3, bucket)
+
+
def test_iot_jobs_stored_document_too_deep_to_parse_stays_text():
"""A stored document too deep for the JSON parser reaches the device as its text."""
from ministack.services import iot as iot_module