Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(iot): refuse job documents nested more than 1000 levels deep (#2258)
iot-rocket4db1372b0fd1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3e0e3667..e39aa5ef 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,10 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **IoT — job documents nested too deep** — `CreateJob` and `CreateJobTemplate` accepted an inline document that is not JSON, and a document nested deeper than Python's JSON parser goes answered 500 (from `documentSource`, or inline once it headed a thing's queue, after which every later `CreateJob` for that thing answered 500 too); they now refuse a document that is not JSON or nests more than 1000 levels deep with AWS's `InvalidRequestException`, and a device gets a 1000-level document compact. Contributed by @iot-rocket.+- **IoT — job execution versions, `statusDetails`, execution numbers and timeouts** — `UpdateJobExecution` answered a stale `expectedVersion` with 409 `InvalidStateTransitionException` and now answers 400 `InvalidRequestException` (`VersionMismatch` over MQTT, as before); an execution has no `statusDetails` until a device reports some, and a reported empty map replaces the previous one; the MQTT `get` and `update` topics answer `ResourceNotFound` for an `executionNumber` other than the execution's; and `DescribeJobExecution`, `ListJobExecutionsForJob`, `ListJobExecutionsForThing` and `DescribeJob` time out an expired `IN_PROGRESS` execution as the device reads do. Contributed by @iot-rocket.+- **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 — job execution versions, `statusDetails`, execution numbers and timeouts** — `UpdateJobExecution` answered a stale `expectedVersion` with 409 `InvalidStateTransitionException` and now answers 400 `InvalidRequestException` (`VersionMismatch` over MQTT, as before); an execution has no `statusDetails` until a device reports some, and a reported empty map replaces the previous one; the MQTT `get` and `update` topics answer `ResourceNotFound` for an `executionNumber` other than the execution's; and `DescribeJobExecution`, `ListJobExecutionsForJob`, `ListJobExecutionsForThing` and `DescribeJob` time out an expired `IN_PROGRESS` execution as the device reads do. Contributed by @iot-rocket.- **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.diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex 5b2cf492..54d5b554 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -6703,6 +6703,7 @@ async def _handle_job(method: str, path: str, body: bytes, qp: dict) -> tuple:# An S3 host: path style without a bucket label, virtual-hosted with one._JOB_DOCUMENT_S3_HOST_RE = re.compile(r"(?:(?P<bucket>.+)\.)?s3(?:[.-][a-z0-9-]+)?\.amazonaws\.com")_JOB_DOCUMENT_MAX_BYTES = 32768+_JOB_DOCUMENT_MAX_DEPTH = 1000def _job_document_s3_location(source: str) -> tuple[str, str]:@@ -6724,6 +6725,27 @@ def _job_document_s3_location(source: str) -> tuple[str, str]:return bucket, key+def _job_document_is_json(document: str) -> bool:+ """Whether a job document is JSON nested no deeper than AWS accepts."""+ from ministack.services.apigateway_v1 import _json_depth++ try:+ value = json.loads(document)+ except (ValueError, RecursionError):+ return False+ return _json_depth(value) <= _JOB_DOCUMENT_MAX_DEPTH+++def _job_inline_document_error(document) -> tuple | None:+ """The refusal of a request's document that is not JSON AWS accepts, or None."""+ if isinstance(document, str) and document and not _job_document_is_json(document):+ return error_response_json(+ "InvalidRequestException",+ "Job document located at request input is an invalid JSON document.", 400,+ )+ return None++def _job_document_from_source(source: str) -> tuple[str | None, tuple | None]:"""The job document a documentSource names in this account's S3, or an error."""from ministack.services import s3 as _s3@@ -6756,8 +6778,9 @@ def _job_document_from_source(source: str) -> tuple[str | None, tuple | None]:)try:document = _s3._get_object_data(bucket, key).decode("utf-8")- json.loads(document)except ValueError:+ document = ""+ if not _job_document_is_json(document):return None, error_response_json("InvalidRequestException",f"Job document located at {source} is an invalid JSON document.",@@ -6886,6 +6909,8 @@ async def _create_job(job_id: str, payload: dict) -> tuple:"InvalidRequestException","document exceeds the maximum length of 32768", 400,)+ if err := _job_inline_document_error(document):+ return errsource = payload.get("documentSource")if isinstance(source, str) and not 1 <= len(source) <= 1350:return error_response_json(@@ -7451,6 +7476,8 @@ def _create_job_template(template_id: str, payload: dict) -> tuple:return _job_template_validation_error(document, "document", "Member must have length less than or equal to 32768")+ if err := _job_inline_document_error(document):+ return errminutes = (payload.get("timeoutConfig") or {}).get("inProgressTimeoutInMinutes")if minutes is not None and (err := _job_timeout_error(minutes)):return err@@ -8085,18 +8112,35 @@ def _jobs_device_float(value: float) -> str:def _jobs_device_json(value) -> str:"""Compact JSON of a job document as AWS sends it to a device: object members that are null are left out."""- if isinstance(value, dict):- return "{" + ",".join(- f"{_jobs_device_json(key)}:{_jobs_device_json(member)}"- for key, member in value.items() if member is not None- ) + "}"- if isinstance(value, list):- return "[" + ",".join(map(_jobs_device_json, value)) + "]"- if isinstance(value, str):- return '"' + value.translate(_JOBS_DEVICE_ESCAPES) + '"'- if isinstance(value, float):- return _jobs_device_float(value)- return json.dumps(value)+ parts: list[str] = []+ # Values still to write, last first; a tuple holds punctuation (json.loads makes none).+ pending = [value]+ while pending:+ value = pending.pop()+ if isinstance(value, tuple):+ parts.append(value[0])+ elif isinstance(value, dict):+ members = [(key, member) for key, member in value.items() if member is not None]+ parts.append("{")+ pending.append(("}",))+ for index in range(len(members) - 1, -1, -1):+ key, member = members[index]+ pending.append(member)+ pending.append(("," * bool(index) + '"' + key.translate(_JOBS_DEVICE_ESCAPES) + '":',))+ elif isinstance(value, list):+ parts.append("[")+ pending.append(("]",))+ for index in range(len(value) - 1, -1, -1):+ pending.append(value[index])+ if index:+ pending.append((",",))+ elif isinstance(value, str):+ parts.append('"' + value.translate(_JOBS_DEVICE_ESCAPES) + '"')+ elif isinstance(value, float):+ parts.append(_jobs_device_float(value))+ else:+ parts.append(json.dumps(value))+ return "".join(parts)# The host a device reached MiniStack on: its presigned URLs name it.@@ -8254,7 +8298,7 @@ def _jobs_job_document_object(job_id: str, escape_non_bmp: bool = False):document = jobs_job_document(job_id)try:json.loads(document)- except ValueError:+ except (ValueError, RecursionError):return documentif escape_non_bmp:document = _JOBS_NON_BMP_RE.sub(_jobs_utf16_escape, document)diff --git a/tests/test_iot_jobs_data.py b/tests/test_iot_jobs_data.pyindex d753f4bc..bd033324 100644--- a/tests/test_iot_jobs_data.py+++ b/tests/test_iot_jobs_data.py@@ -348,6 +348,94 @@ def test_iot_jobs_document_source_refusals(iot_client, s3):_delete_bucket(s3, bucket)+def test_iot_jobs_document_nesting_limit(iot_client, iot_jobs_data, s3):+ """A document nested deeper than 1000 levels, or not JSON, refuses the job or template."""+ thing, bucket = _unique("jobs-thing"), _unique("jobs-doc")+ jobs, templates = [], []+ deepest = {+ "array": "[ " * 1000 + "]" * 1000,+ "object": '{ "a": ' * 1000 + "1" + " }" * 1000,+ }+ compact = {"array": "[" * 1000 + "]" * 1000, "object": '{"a":' * 1000 + "1" + "}" * 1000}+ refused = {+ "array": "[" * 1001 + "]" * 1001,+ "object": '{"a":' * 1001 + "1" + "}" * 1001,+ "beyond the parser": "[" * 16000 + "]" * 16000,+ "not JSON": "not json",+ }+ try:+ thing_arn = _create_thing(iot_client, thing)+ s3.create_bucket(Bucket=bucket)+ for kind, document in refused.items():+ s3.put_object(Bucket=bucket, Key=f"{kind}.json", Body=document)+ source = f"s3://{bucket}/{kind}.json"+ for request, where in (({"document": document}, "request input"), ({"documentSource": source}, source)):+ message = f"Job document located at {where} is an invalid JSON document."+ job_id, template_id = _unique("job"), _unique("tmpl")+ with pytest.raises(ClientError) as ei:+ iot_client.create_job(jobId=job_id, targets=[thing_arn], **request)+ assert _error(ei) == (400, "InvalidRequestException", message), kind+ with pytest.raises(ClientError) as ei:+ iot_client.describe_job(jobId=job_id)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ with pytest.raises(ClientError) as ei:+ iot_client.create_job_template(jobTemplateId=template_id, description="d", **request)+ assert _error(ei) == (400, "InvalidRequestException", message), kind++ # Brackets inside a string are no nesting.+ jobs.append(_unique("job"))+ iot_client.create_job(+ jobId=jobs[-1], targets=[thing_arn], document=json.dumps({"s": "[" * 1001})+ )++ # 1000 levels are accepted; the device gets them compact.+ for kind, document in deepest.items():+ s3.put_object(Bucket=bucket, Key=f"{kind}.json", Body=document)+ for request in ({"document": document}, {"documentSource": f"s3://{bucket}/{kind}.json"}):+ 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+ execution = iot_jobs_data.describe_job_execution(+ jobId=jobs[-1], thingName=thing, includeJobDocument=True+ )["execution"]+ assert execution["jobDocument"] == compact[kind], kind+ templates.append(_unique("tmpl"))+ iot_client.create_job_template(jobTemplateId=templates[-1], description="d", **request)+ desc = iot_client.describe_job_template(jobTemplateId=templates[-1])+ assert desc["document"] == document+ finally:+ _delete_templates(iot_client, *templates)+ _cleanup(iot_client, jobs=jobs, things=[thing])+ _delete_bucket(s3, bucket)+++def test_iot_jobs_document_with_unterminated_strings_is_refused(iot_client):+ """A document of escaped quotes without a closing one is refused."""+ thing = _unique("jobs-thing")+ document = '"' + '\\"' * 16383+ try:+ thing_arn = _create_thing(iot_client, thing)+ with pytest.raises(ClientError) as ei:+ iot_client.create_job(jobId=_unique("job"), targets=[thing_arn], document=document)+ message = "Job document located at request input is an invalid JSON document."+ assert _error(ei) == (400, "InvalidRequestException", message)+ finally:+ _cleanup(iot_client, things=[thing])+++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++ job_id, document = _unique("job"), "[" * 16000 + "]" * 16000+ iot_module._jobs[job_id] = {"jobId": job_id, "document": document}+ try:+ assert iot_module.jobs_job_document(job_id) == document+ assert iot_module._jobs_job_document_object(job_id) == document+ finally:+ iot_module._jobs.pop(job_id, None)++def test_iot_jobs_document_source_is_read_in_the_callers_account():"""The bucket is looked up in the caller's account, in any of its regions."""owner_s3 = _account_client("s3", "111111111111")