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
feat(iot): read job documentSource objects from S3 (#2174)
iot-rocket027107ed5d1d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 580a401f..3e783cef 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,14 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added+- **IoT — job documents from S3** — `CreateJob` and `CreateJobTemplate` read a `documentSource` (`s3://` or an S3 object URL) from MiniStack's S3 once, at creation, where they stored a `{"documentSource": "<url>"}` placeholder. A missing bucket or object, an object that is not JSON or is over 32 KB and a URL that names no S3 host are refused with AWS's messages, and `CreateJob` refuses `document` together with `documentSource`. Devices get every job document re-serialized as AWS sends it, without spaces and without object members that are null, while `GetJobDocument` keeps the stored text. Contributed by @iot-rocket.+- **IoT — `SetDefaultPolicyVersion`** — the call was missing (`PATCH /policies/{policyName}/version/{policyVersionId}` answered `Unsupported policy path`), so only `CreatePolicyVersion` with `setAsDefault` could move a policy's default version; it now sets the default that `GetPolicy`, `GetPolicyVersion`, `ListPolicyVersions` and the MQTT policy evaluation under `AUTH=true` use, deleting the default version answers `DeleteConflictException` (409) instead of 400, and `ListPolicyVersions` lists the newest version first. Contributed by @iot-rocket.+- **IoT — `EnableTopicRule` and `DisableTopicRule`** — both calls were missing (`POST /rules/{ruleName}/enable` answered `Invalid ruleName`), so a rule could only be switched off by replacing it; they now set `ruleDisabled`, which `GetTopicRule` and `ListTopicRules` report and which stops the rule from acting on matching publishes and Basic Ingest until it is enabled again. Contributed by @iot-rocket.+- **IoT — MQTT publish, subscribe and receive evaluate IoT policies under `AUTH=true`** — after the CONNECT a certificate session could publish, subscribe and receive on any topic; it now needs `iot:Publish` on the topic (and `iot:RetainPublish` for a retained message or will), `iot:Subscribe` per topic filter and `iot:Receive` per delivered message. A refused PUBLISH or SUBSCRIBE closes an MQTT 3.1.1 connection (disconnect reason `CLIENT_ERROR`), MQTT 5 answers PUBACK 0x87, DISCONNECT 0x87 at QoS 0 (`AUTH_ERROR`) or 0x87 for the refused filter, which the `subscribed` event leaves out (no event when none is granted), a refused will refuses the CONNECT, and a message the subscriber may not receive is dropped. Contributed by @iot-rocket.+- **IoT — MQTT connections evaluate `iot:Connect` under `AUTH=true`** — a device certificate on the mTLS listener connected under any client id, with or without a policy; with `AUTH=true` the CONNECT now needs an attached policy that allows `iot:Connect` on `client/<client id>` and none that denies it, with `${iot:ClientId}`, `${iot:Connection.Thing.ThingName}`, `iot:Connection.Thing.IsAttached` and `${iot:Certificate.Subject.CommonName}` resolved. A refusal closes an MQTT 3.1.1 connection without a CONNACK, answers MQTT 5 with CONNACK 0x87 and publishes `$aws/events/presence/connect_failed/{clientId}`. Contributed by @iot-rocket.+### Fixed++- **IoT — republish inside the rule's own topic filter** — `CreateTopicRule` and `ReplaceTopicRule` accepted a `republish` action whose topic the rule's `FROM` filter matches, so the rule fed on its own output; they now refuse it with AWS's `InvalidRequestException`, and an `AWS::IoT::TopicRule` with such an action fails its stack. Contributed by @iot-rocket.- **IoT — `SetDefaultPolicyVersion`** — the call was missing (`PATCH /policies/{policyName}/version/{policyVersionId}` answered `Unsupported policy path`), so only `CreatePolicyVersion` with `setAsDefault` could move a policy's default version; it now sets the default that `GetPolicy`, `GetPolicyVersion`, `ListPolicyVersions` and the MQTT policy evaluation under `AUTH=true` use, deleting the default version answers `DeleteConflictException` (409) instead of 400, and `ListPolicyVersions` lists the newest version first. Contributed by @iot-rocket.### Added- **Auth — REST API resource policies are evaluated under `AUTH=true`** — an API Gateway resource policy took no part in the decision; for an `execute-api:Invoke` a statement naming the calling user or role now allows the call without an identity policy, a statement naming only the account still needs one, a Deny wins over an identity Allow, and a call without a SigV4 signature (none, or a bearer token) to a method without authorization passes only when the policy, if any, allows everyone, else it answers `ACCESS_DENIED` with API Gateway's message. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex 4b5ec030..0285e03b 100644--- a/README.md+++ b/README.md@@ -646,7 +646,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i| **CodeBuild** | CreateProject, BatchGetProjects, ListProjects, UpdateProject, DeleteProject, StartBuild, BatchGetBuilds, StopBuild, ListBuilds, ListBuildsForProject, BatchDeleteBuilds | 11 actions; project and build metadata stored in-memory; builds complete immediately with SUCCEEDED status by default. Set `MINISTACK_CODEBUILD_EXECUTE=1` and mount the Docker socket to **really run them**: the project's inline buildspec goes to the official AWS CodeBuild local agent, which runs the phases in `environment.image`, and `BatchGetBuilds` reports live `phases` with a real `SUCCEEDED`/`FAILED` outcome. Execution needs the workspace shared with the host at the **same path** (`-v /tmp/ministack-codebuild:/tmp/ministack-codebuild`), because the agent bind-mounts it into the build container; a build gets `AWS_ENDPOINT_URL` pointing back at MiniStack, honours `timeoutInMinutes`, and is stopped by `StopBuild`. An executed build streams the agent output into its `logs.groupName` / `logs.streamName`, so `aws logs tail` reads the build log back || **AppConfig** | CreateApplication, GetApplication, ListApplications, UpdateApplication, DeleteApplication, CreateEnvironment, GetEnvironment, ListEnvironments, UpdateEnvironment, DeleteEnvironment, CreateConfigurationProfile, GetConfigurationProfile, ListConfigurationProfiles, UpdateConfigurationProfile, DeleteConfigurationProfile, CreateHostedConfigurationVersion, GetHostedConfigurationVersion, ListHostedConfigurationVersions, DeleteHostedConfigurationVersion, CreateDeploymentStrategy, GetDeploymentStrategy, ListDeploymentStrategies, UpdateDeploymentStrategy, DeleteDeploymentStrategy, StartDeployment, GetDeployment, ListDeployments, StopDeployment, TagResource, UntagResource, ListTagsForResource, StartConfigurationSession, GetLatestConfiguration | 33 operations; control plane + data plane; hosted configuration versions; the AWS-predefined deployment strategies (4) are listed and immutable; deployments move through `DEPLOYING`, `BAKING` and `COMPLETE` on the strategy's schedule (`LINEAR` or `EXPONENTIAL` steps, then the bake time), with `PercentageComplete`, the event log and the environment `State` reported along the way; a `Monitors` alarm that goes to `ALARM` before the bake ends rolls the deployment back; one deployment per environment at a time (`ConflictException`, also for a stale `LatestDeploymentNumber`); `StopDeployment` rolls back a `DEPLOYING` deployment, and with `AllowRevert` also a `BAKING` one, or reverts a completed one within 72 hours; during a rollout a session gets the new version once the rollout reaches its fixed slot (MiniStack's choice, since AWS does not document how it picks targets); `GetLatestConfiguration` returns an empty body when the session already has the latest version, plus `Version-Label`, and uses `RequiredMinimumPollIntervalInSeconds` as the poll interval || **Transfer Family** | CreateServer, DescribeServer, DeleteServer, ListServers, StartServer, StopServer, CreateUser, DescribeUser, DeleteUser, ListUsers, ImportSshPublicKey, DeleteSshPublicKey | 12 operations; **real SFTP listener** on `:2222` (override with `SFTP_PORT`) backed by S3 — `ls`, `put`, `get`, `mkdir`, `rename` work end-to-end against the local S3 emulator; `SFTP_PORT_PER_SERVER=1` allocates one port per `CreateServer` from `SFTP_BASE_PORT` (default 2300); SSH key auth scans every user across every server and account; `LOGICAL` and `PATH` home-directory mappings; host key persists across restarts when `PERSIST_STATE=1` |-| **IoT Jobs** | Control plane (`iot`): CreateJob, UpdateJob, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, ListJobExecutionsForJob, DescribeJobExecution, CancelJobExecution, DeleteJobExecution, CreateJobTemplate, DescribeJobTemplate, ListJobTemplates, DeleteJobTemplate; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 16 control-plane + 4 device data-plane operations sharing one store. A job created with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a request member replaces the template's. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED, TIMED_OUT}`; an execution past its `timeoutConfig.inProgressTimeoutInMinutes`, or past the `stepTimeoutInMinutes` the device reported, becomes `TIMED_OUT`, and the device plane reports `approximateSecondsBeforeTimedOut` while it runs. `REMOVED` is counted in `jobProcessDetails`; a thing that leaves every target group of a `CONTINUOUS` job turns its `QUEUED` execution `REMOVED`, or gets a `REMOVED` execution 1 (without an event) if all its executions were deleted; deleting a thing DELETES its executions (freeing a job that was only waiting on that thing) rather than marking them `REMOVED`. `versionNumber` gives optimistic concurrency: every transition bumps it and a stale `expectedVersion` is rejected with a 409 whose message carries the current version — coded `VersionConflictException` on the control plane and `InvalidStateTransitionException` on the device plane, each as its own service model declares. `executionNumber` is 1 for a thing's first execution of a job and one more each time the thing rejoins a `CONTINUOUS` job's target group after its execution finished. Devices may only report `IN_PROGRESS` / `SUCCEEDED` / `FAILED` / `REJECTED` via `UpdateJobExecution`; targets are thing or thing-group ARNs — `SNAPSHOT` jobs resolve group membership once at creation, `CONTINUOUS` jobs also pick up things added to a target group later, and a target must name a thing or thing group in the caller's own account and region (anything else is `ResourceNotFoundException`, since it would resolve to no devices at all); a non-continuous job auto-`COMPLETED`s (with `jobProcessDetails` counts) once every execution is terminal. **`documentSource` is not fetched**: a job created with an S3 `documentSource` serves a `{"documentSource": "<url>"}` placeholder as its document rather than the object's content, so the lifecycle still runs — pass `document` when the content matters; a job template with a `documentSource` stores the same placeholder. **Timestamps are epoch seconds on every plane, as AWS documents**: control-plane responses use `timestamp` shapes (boto3 parses them to datetimes) while `iot-jobs-data` responses carry whole-second integer `long`s. **Jobs over MQTT**: the reserved `$aws/things/<thing>/jobs/#` request topics (`get`, `start-next`, `<jobId>/get` incl. `$next`, `<jobId>/update`) answer on their `accepted`/`rejected` topics from the same store as the HTTP plane (`jobDocument` as a JSON object over MQTT, a string over HTTP, as on AWS; rejections carry the string `ErrorCode` values and the execution's state on version and state-transition conflicts); `notify` fires when the pending set changes and `notify-next` when the queue front changes; `stepTimeoutInMinutes` and `executionNumber` are accepted but ignored. Job state persists with the IoT store when `PERSIST_STATE=1` |+| **IoT Jobs** | Control plane (`iot`): CreateJob, UpdateJob, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, ListJobExecutionsForJob, DescribeJobExecution, CancelJobExecution, DeleteJobExecution, CreateJobTemplate, DescribeJobTemplate, ListJobTemplates, DeleteJobTemplate; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 16 control-plane + 4 device data-plane operations sharing one store. A job created with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a request member replaces the template's. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED, TIMED_OUT}`; an execution past its `timeoutConfig.inProgressTimeoutInMinutes`, or past the `stepTimeoutInMinutes` the device reported, becomes `TIMED_OUT`, and the device plane reports `approximateSecondsBeforeTimedOut` while it runs. `REMOVED` is counted in `jobProcessDetails`; a thing that leaves every target group of a `CONTINUOUS` job turns its `QUEUED` execution `REMOVED`, or gets a `REMOVED` execution 1 (without an event) if all its executions were deleted; deleting a thing DELETES its executions (freeing a job that was only waiting on that thing) rather than marking them `REMOVED`. `versionNumber` gives optimistic concurrency: every transition bumps it and a stale `expectedVersion` is rejected with a 409 whose message carries the current version — coded `VersionConflictException` on the control plane and `InvalidStateTransitionException` on the device plane, each as its own service model declares. `executionNumber` is 1 for a thing's first execution of a job and one more each time the thing rejoins a `CONTINUOUS` job's target group after its execution finished. Devices may only report `IN_PROGRESS` / `SUCCEEDED` / `FAILED` / `REJECTED` via `UpdateJobExecution`; targets are thing or thing-group ARNs — `SNAPSHOT` jobs resolve group membership once at creation, `CONTINUOUS` jobs also pick up things added to a target group later, and a target must name a thing or thing group in the caller's own account and region (anything else is `ResourceNotFoundException`, since it would resolve to no devices at all); a non-continuous job auto-`COMPLETED`s (with `jobProcessDetails` counts) once every execution is terminal. **`documentSource` is read from MiniStack's S3**: a job or job template created with an `s3://` or S3 object URL keeps the object's content as its document, read once at creation; a missing bucket or object, a non-JSON object or one over 32 KB is refused, and so is a URL whose host is not S3. **Timestamps are epoch seconds on every plane, as AWS documents**: control-plane responses use `timestamp` shapes (boto3 parses them to datetimes) while `iot-jobs-data` responses carry whole-second integer `long`s. **Jobs over MQTT**: the reserved `$aws/things/<thing>/jobs/#` request topics (`get`, `start-next`, `<jobId>/get` incl. `$next`, `<jobId>/update`) answer on their `accepted`/`rejected` topics from the same store as the HTTP plane (`jobDocument` as a JSON object over MQTT, a string over HTTP, as on AWS; rejections carry the string `ErrorCode` values and the execution's state on version and state-transition conflicts); `notify` fires when the pending set changes and `notify-next` when the queue front changes; `stepTimeoutInMinutes` and `executionNumber` are accepted but ignored. Job state persists with the IoT store when `PERSIST_STATE=1` || **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, ListThingGroupsForThing, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, CreateCertificateFromCsr, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, ListCertificatesByCA, CreateProvisioningTemplate, DescribeProvisioningTemplate, ListProvisioningTemplates, UpdateProvisioningTemplate, DeleteProvisioningTemplate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, SetDefaultPolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, EnableTopicRule, DisableTopicRule, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), GetRetainedMessage, ListRetainedMessages, MQTT-over-WebSocket pub/sub, DescribeEventConfigurations, UpdateEventConfigurations, CreateDomainConfiguration, DescribeDomainConfiguration, ListDomainConfigurations, UpdateDomainConfiguration, DeleteDomainConfiguration, TagResource, UntagResource, ListTagsForResource | 71 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane, except on mTLS MQTT connections with `AUTH=true`; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `principal()`, `traceid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; a **provisioning-template registry** (`CreateProvisioningTemplate` and friends) — storage + CRUD only, so `provisioningRoleArn` is presence-checked but not resolved and the fleet-provisioning MQTT workflow (`$aws/provisioning-templates/...`) is not implemented; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry; the broker publishes the presence and subscription lifecycle events (`$aws/events/presence/connected\|disconnected/{clientId}`, `$aws/events/subscriptions/subscribed\|unsubscribed/{clientId}`) || **IoT Wireless** | GetPositionEstimate | Single operation (`POST /position-estimate`, SigV4 scope `iotwireless`, endpoint prefix `api.iotwireless`). **The response is the raw GeoJSON blob** — the output shape's `payload` trait — so boto3 hands back a `StreamingBody` under `GeoJsonPayload`, not a JSON envelope. Resolves from `Ip` only: `WiFiAccessPoints` / `CellTowers` / `Gnss` are accepted and ignored, `Timestamp` and `AdvancedConfiguration` only reach `properties`, and the estimate is synthetic + deterministic — the canonical IP (an IPv4-mapped IPv6 address counts as its IPv4 form) hashes onto lon [-180, 180) / lat [-60, 60), 4 decimals — so the same address always answers the same estimate and consumer tests can assert on it. `properties` carry `horizontalAccuracy` 1000000 (the value of one live call) and `horizontalConfidenceLevel` 0.68 (the default the AWS IoT Core Device Location guide documents — `AdvancedConfiguration.WiFiCellular.ConfidencePercent` overrides it, divided by 100, within the 50 to 99 the model allows) plus `timestamp`, which is always there: AWS documents the request's `Timestamp` as the resolve time and the receive time as its substitute when the caller sends none, so send a `Timestamp` and the whole blob is byte-identical. The real payload's `country` and city/state/postal properties are omitted for that determinism. An input with no resolver hint and an `IpAddress` that `ipaddress.ip_address()` refuses answer `ValidationException` (those two wordings are recorded from the live service; every other message in this service is MiniStack's own, since none is documented); a `Timestamp` that is not a Unix timestamp, and a `ConfidencePercent` outside the model's range, are `ValidationException` too; a valid address that is **not globally routable or is multicast** (private, loopback, TEST-NET, multicast groups, ...) answers `ResourceNotFoundException` `Cannot find position for the IP address <ip>`, mirroring the real service's refusal when its geo database has no entry. A well-formed request whose only measurements are WLAN/cell/GNSS is `ResourceNotFoundException` too — the developer guide documents 404 for exactly that ("no location information was found or solved ... The MAC address or cellular tower information is not sufficient ... The GNSS payload is not sufficient"), and 400 for measurement data formatted incorrectly. Stateless — nothing persists || **EventBridge Scheduler** | CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource | 12 actions; schedules **fire their targets** — a background sweep invokes each enabled schedule's target (Lambda, SQS, SNS, Step Functions) when due, honoring `State`, `StartDate`/`EndDate`, and `ActionAfterCompletion: DELETE`; schedule groups with cascading deletes; `rate()`, `cron()`, `at()` expressions; group/prefix/state filters on list; default group auto-created; CFN `AWS::Scheduler::Schedule` and `AWS::Scheduler::ScheduleGroup` supported |diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex e851131d..4a272204 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -76,6 +76,7 @@ import functoolsimport hashlibimport jsonimport logging+import mathimport osimport reimport secrets@@ -5715,6 +5716,66 @@ 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+++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 urllib.parse import unquote, urlsplit++ from ministack.services import s3 as _s3++ bucket = key = ""+ if isinstance(source, str) and source.startswith("s3://"):+ bucket, _, key = source[len("s3://"):].partition("/")+ elif isinstance(source, str) and source.startswith(("https://", "http://")):+ with contextlib.suppress(ValueError):+ parts = urlsplit(source)+ match = _JOB_DOCUMENT_S3_HOST_RE.fullmatch(parts.hostname or "")+ if match and match.group("bucket"):+ bucket, key = match.group("bucket"), unquote(parts.path[1:])+ elif match:+ bucket, _, key = parts.path[1:].partition("/")+ key = unquote(key)+ if not bucket:+ return None, error_response_json(+ "InvalidRequestException", f"Job document source {source} is invalid.", 400+ )+ if not key:+ return None, error_response_json(+ "InvalidRequestException",+ f"Provided S3 url is not valid: {source}. Error: Key cannot be null", 400,+ )+ bucket_record = _s3._ensure_bucket(bucket)+ if bucket_record is None:+ return None, error_response_json(+ "InvalidRequestException", f"Bucket specified by url: {source} is not found.", 400+ )+ obj = bucket_record["objects"].get(key)+ if obj is None:+ return None, error_response_json(+ "InvalidRequestException", f"Job document located at {source} is not found.", 400+ )+ if obj["size"] > _JOB_DOCUMENT_MAX_BYTES:+ return None, error_response_json(+ "LimitExceededException",+ f"Job document from {source} exceeds size limit {_JOB_DOCUMENT_MAX_BYTES} bytes.",+ 410,+ )+ try:+ document = _s3._get_object_data(bucket, key).decode("utf-8")+ json.loads(document)+ except ValueError:+ return None, error_response_json(+ "InvalidRequestException",+ f"Job document located at {source} is an invalid JSON document.",+ 400,+ )+ return document, None++async def _create_job(job_id: str, payload: dict) -> tuple:if not job_id or not _JOB_ID_RE.match(job_id):return error_response_json(@@ -5726,6 +5787,12 @@ async def _create_job(job_id: str, payload: dict) -> tuple:return error_response_json("ResourceAlreadyExistsException", f"Job {job_id} already exists", 409)+ if payload.get("document") and payload.get("documentSource"):+ return error_response_json(+ "InvalidRequestException",+ "Job document and job document source cannot be specified at the same time.",+ 400,+ )if payload.get("jobTemplateArn") is not None:payload, err = _job_payload_from_template(payload)if err:@@ -5806,13 +5873,10 @@ async def _create_job(job_id: str, payload: dict) -> tuple:400,)if not document and payload.get("documentSource"):- # DELIBERATE DIVERGENCE: AWS fetches the document from the S3 URL and- # serves its CONTENT to devices. MiniStack does not fetch it — it- # stands in a placeholder naming the source, so a `documentSource` job- # still creates, describes, and runs its whole execution lifecycle.- # A device that parses the document therefore sees the URL, not the- # payload; pass `document` when the content matters.- document = json.dumps({"documentSource": payload["documentSource"]})+ # The object is read once, here: a later overwrite changes no job.+ document, err = _job_document_from_source(payload["documentSource"])+ if err:+ return err# Captured BEFORE the job record exists: jobs_first_pending_job_id# materializes, and once the new job is in the store it would already# count as the front of the queue.@@ -6357,8 +6421,9 @@ def _create_job_template(template_id: str, payload: dict) -> tuple:record["document"] = documentrecord["documentSource"] = sourceif source and not document:- # Same stand-in as CreateJob's: the S3 object is not fetched.- record["document"] = json.dumps({"documentSource": source})+ record["document"], err = _job_document_from_source(source)+ if err:+ return errfor member in _JOB_TEMPLATE_CONFIG_MEMBERS + ("maintenanceWindows", "destinationPackageVersions",):@@ -6905,10 +6970,51 @@ def jobs_describe_execution(thing_name: str, job_id: str) -> dict | None:return dict(_jobs_apply_timeout(execution))+# Control characters as AWS escapes them in the document it sends a device; a lone+# surrogate stays escaped too, since UTF-8 cannot carry it.+_JOBS_DEVICE_ESCAPES = {+ **{code: f"\\u{code:04X}" for code in (*range(0x20), *range(0xD800, 0xE000))},+ 0x08: "\\b", 0x09: "\\t", 0x0A: "\\n", 0x0C: "\\f", 0x0D: "\\r", 0x22: '\\"', 0x5C: "\\\\",+}+++def _jobs_device_float(value: float) -> str:+ """A float spelled as Java's Double.toString, with a non-finite value as a string."""+ if not math.isfinite(value):+ return f'"{json.dumps(value)}"'+ if value == 0 or 1e-3 <= abs(value) < 1e7:+ return repr(value)+ from decimal import Decimal++ sign, digits, exponent = Decimal(repr(value)).normalize().as_tuple()+ text = "".join(map(str, digits))+ return f"{'-' * sign}{text[0]}.{text[1:] or '0'}E{len(text) - 1 + exponent}"+++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)++def jobs_job_document(job_id: str) -> str:- """The document a device should run for a job — ``{}`` if there is none."""+ """The document a device should run for a job, re-serialized as AWS sends it — ``{}`` if there is none."""job = _jobs.get(job_id)- return (job or {}).get("document") or "{}"+ document = (job or {}).get("document") or "{}"+ try:+ return _jobs_device_json(json.loads(document))+ except (ValueError, RecursionError):+ return documentdef _jobs_job_document_object(job_id: str):diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 7ed6f5a8..a5b16016 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -1632,6 +1632,36 @@ def test_cfn_iot_job_template_existing_id_fails_the_stack(cfn, iot_client):iot_client.delete_job_template(jobTemplateId=template_id)+def test_cfn_iot_job_template_document_source(cfn, iot_client, s3):+ """A DocumentSource is read from S3 at create; a missing object fails the stack."""+ uid = _uuid_mod.uuid4().hex[:8]+ bucket, stack, failing = f"cfn-jt-doc-{uid}", f"cfn-iot-jobtmpl-src-{uid}", f"cfn-jt-miss-{uid}"+ template_id = f"cfn-jt-src-{uid}"+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key="doc.json", Body='{"operation": "from s3"}')+ try:+ cfn.create_stack(StackName=stack, TemplateBody=_cfn_job_template(+ template_id, Document=None, DocumentSource=f"s3://{bucket}/doc.json"))+ assert _wait_stack(cfn, stack)["StackStatus"] == "CREATE_COMPLETE"+ desc = iot_client.describe_job_template(jobTemplateId=template_id)+ assert desc["document"] == '{"operation": "from s3"}'+ assert desc["documentSource"] == f"s3://{bucket}/doc.json"++ cfn.create_stack(StackName=failing, TemplateBody=_cfn_job_template(+ f"{template_id}-2", Document=None, DocumentSource=f"s3://{bucket}/missing.json"))+ assert _wait_stack(cfn, failing)["StackStatus"] == "ROLLBACK_COMPLETE"+ reasons = [e.get("ResourceStatusReason", "") for e in+ cfn.describe_stack_events(StackName=failing)["StackEvents"]+ if e["ResourceStatus"] == "CREATE_FAILED"]+ assert any(f"Job document located at s3://{bucket}/missing.json is not found."+ in reason for reason in reasons), reasons+ finally:+ _delete_cfn_test_stack(cfn, stack)+ _delete_cfn_test_stack(cfn, failing)+ s3.delete_object(Bucket=bucket, Key="doc.json")+ s3.delete_bucket(Bucket=bucket)++def test_cfn_iot_ca_certificate_lifecycle(cfn, iot_client):"""AWS::IoT::CACertificate provisions onto the real CA registry instead ofrolling the stack back: create registers the PEM (readable back throughdiff --git a/tests/test_iot_jobs_data.py b/tests/test_iot_jobs_data.pyindex 00112b4c..e2a99417 100644--- a/tests/test_iot_jobs_data.py+++ b/tests/test_iot_jobs_data.py@@ -27,6 +27,8 @@ from botocore.exceptions import ClientErrorENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")_DOCUMENT = json.dumps({"operation": "reboot", "when": "now"})+# Devices get the document re-serialized without spaces.+_DEVICE_DOCUMENT = '{"operation":"reboot","when":"now"}'# A syntactically plausible SigV4 header whose credential scope routes the# request to the iot-jobs-data service in the default account and region@@ -176,34 +178,199 @@ def test_iot_jobs_get_job_document(iot_client):_cleanup(iot_client, jobs=[job_id], things=[thing])-def test_iot_jobs_document_source_serves_a_placeholder_and_is_not_fetched(- iot_client, iot_jobs_data-):- """Documented divergence: AWS fetches `documentSource` from S3 and serves- its CONTENT to devices. MiniStack does not fetch it — it serves a- placeholder naming the source, so a `documentSource` job still creates,- describes, and runs its whole execution lifecycle locally. This test pins- that choice; changing it means changing README + CHANGELOG too."""- thing = _unique("jobs-thing")- job_id = _unique("job")- source = "https://ministack-jobs.s3.us-east-1.amazonaws.com/reboot.json"+def _delete_bucket(s3_client, bucket):+ try:+ for obj in s3_client.list_objects_v2(Bucket=bucket).get("Contents", []):+ s3_client.delete_object(Bucket=bucket, Key=obj["Key"])+ s3_client.delete_bucket(Bucket=bucket)+ except ClientError:+ pass+++def test_iot_jobs_document_source_reads_the_s3_object(iot_client, iot_jobs_data, s3):+ """CreateJob reads a documentSource object once, at creation, from any S3 URL form."""+ thing, bucket = _unique("jobs-thing"), _unique("jobs-doc")+ content = json.dumps({"operation": "reboot", "v": 1})+ jobs = []++ def create(source):+ jobs.append(_unique("job"))+ iot_client.create_job(jobId=jobs[-1], targets=[thing_arn], documentSource=source)+ return jobs[-1]+try:thing_arn = _create_thing(iot_client, thing)- iot_client.create_job(- jobId=job_id, targets=[thing_arn], documentSource=source- )- # The control plane echoes the source it was handed...+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key="doc.json", Body=content)+ source = f"https://s3.us-east-1.amazonaws.com/{bucket}/doc.json"+ job_id = create(source)assert iot_client.describe_job(jobId=job_id)["documentSource"] == source- # ...and both document reads serve the placeholder, never S3 content.- assert json.loads(iot_client.get_job_document(jobId=job_id)["document"]) == {- "documentSource": source- }+ assert iot_client.get_job_document(jobId=job_id)["document"] == contentexecution = iot_jobs_data.describe_job_execution(- jobId=job_id, thingName=thing+ jobId=job_id, thingName=thing, includeJobDocument=True)["execution"]- assert json.loads(execution["jobDocument"]) == {"documentSource": source}+ assert execution["jobDocument"] == '{"operation":"reboot","v":1}'++ # Overwriting the object changes no job made from it.+ s3.put_object(Bucket=bucket, Key="doc.json", Body='{"v": 2}')+ assert iot_client.get_job_document(jobId=job_id)["document"] == content+ for source in (+ f"s3://{bucket}/doc.json",+ f"https://{bucket}.s3.us-east-1.amazonaws.com/doc.json",+ f"https://{bucket}.s3.amazonaws.com/doc.json",+ f"https://s3.amazonaws.com/{bucket}/doc.json",+ f"https://s3-us-east-1.amazonaws.com/{bucket}/doc.json",+ f"http://s3.eu-west-1.amazonaws.com/{bucket}/doc.json",+ ):+ document = iot_client.get_job_document(jobId=create(source))["document"]+ assert document == '{"v": 2}', source++ # An http(s) path is percent-decoded; an s3:// key is taken as written.+ s3.put_object(Bucket=bucket, Key="dir/a b+c.json", Body="[1, 2]")+ for source in (+ f"https://s3.amazonaws.com/{bucket}/dir/a%20b%2Bc.json",+ f"https://s3.amazonaws.com/{bucket}/dir/a b+c.json",+ f"s3://{bucket}/dir/a b+c.json",+ ):+ assert iot_client.get_job_document(jobId=create(source))["document"] == "[1, 2]"+ limit = json.dumps({"pad": "x" * 32757})+ s3.put_object(Bucket=bucket, Key="limit.json", Body=limit)+ job_id = create(f"s3://{bucket}/limit.json")+ assert iot_client.get_job_document(jobId=job_id)["document"] == limitfinally:- _cleanup(iot_client, jobs=[job_id], things=[thing])+ _cleanup(iot_client, jobs=jobs, things=[thing])+ _delete_bucket(s3, bucket)+++def test_iot_jobs_device_gets_the_document_reserialized(iot_client, iot_jobs_data, s3):+ """Devices get the document compact, without null members; GetJobDocument keeps it as stored."""+ thing, bucket = _unique("jobs-thing"), _unique("jobs-doc")+ stored = (+ '{ "z": 1, "a": [ 1 , 2.50, 1E2, 1e-7, -0, 12345678901234567890, 12345678.9, 1E400 ],\n'+ ' "s": "caf\\u00e9 \\/ \\u001f\\u0041", "n": null, "o": {"n": null, "k": [null]}, "z": 2 }'+ )+ device = (+ '{"z":2,"a":[1,2.5,100.0,1.0E-7,0,12345678901234567890,1.23456789E7,"Infinity"],'+ '"s":"caf\u00e9 / \\u001FA","o":{"k":[null]}}'+ )+ jobs = []+ try:+ thing_arn = _create_thing(iot_client, thing)+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key="doc.json", Body=stored)+ for source in ({"document": stored}, {"documentSource": f"s3://{bucket}/doc.json"}):+ jobs.append(_unique("job"))+ iot_client.create_job(jobId=jobs[-1], targets=[thing_arn], **source)+ assert iot_client.get_job_document(jobId=jobs[-1])["document"] == stored+ execution = iot_jobs_data.describe_job_execution(+ jobId=jobs[-1], thingName=thing, includeJobDocument=True+ )["execution"]+ assert execution["jobDocument"] == device+ started = iot_jobs_data.start_next_pending_job_execution(thingName=thing)+ assert started["execution"]["jobDocument"] == device+ updated = iot_jobs_data.update_job_execution(+ jobId=jobs[-1], thingName=thing, status="SUCCEEDED", includeJobDocument=True+ )+ assert updated["jobDocument"] == device+ # UTF-8 cannot carry a lone surrogate: it stays escaped.+ jobs.append(_unique("job"))+ iot_client.create_job(jobId=jobs[-1], targets=[thing_arn], document='["\\ud83d"]')+ execution = iot_jobs_data.describe_job_execution(+ jobId=jobs[-1], thingName=thing, includeJobDocument=True+ )["execution"]+ assert execution["jobDocument"] == '["\\uD83D"]'+ finally:+ _cleanup(iot_client, jobs=jobs, things=[thing])+ _delete_bucket(s3, bucket)+++def test_iot_jobs_document_source_refusals(iot_client, s3):+ """A documentSource that names no readable JSON object refuses the job."""+ thing, bucket = _unique("jobs-thing"), _unique("jobs-doc")+ try:+ thing_arn = _create_thing(iot_client, thing)+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key="text.txt", Body="not json")+ s3.put_object(Bucket=bucket, Key="empty.json", Body="")+ s3.put_object(Bucket=bucket, Key="big.json", Body=json.dumps({"pad": "x" * 32758}))+ s3.put_object(Bucket=bucket, Key="dir/a b.json", Body="{}")+ invalid = "InvalidRequestException"+ cases = [+ (f"https://example.com/{bucket}/doc.json", 400, invalid,+ "Job document source {} is invalid."),+ (f"s3://{bucket}", 400, invalid,+ "Provided S3 url is not valid: {}. Error: Key cannot be null"),+ (f"s3://{bucket}/", 400, invalid,+ "Provided S3 url is not valid: {}. Error: Key cannot be null"),+ (f"https://s3.us-east-1.amazonaws.com/{bucket}", 400, invalid,+ "Provided S3 url is not valid: {}. Error: Key cannot be null"),+ (f"s3://{bucket}-none/doc.json", 400, invalid,+ "Bucket specified by url: {} is not found."),+ (f"https://s3.us-east-1.amazonaws.com/{bucket}/missing.json", 400, invalid,+ "Job document located at {} is not found."),+ (f"s3://{bucket}/dir/a%20b.json", 400, invalid,+ "Job document located at {} is not found."),+ (f"s3://{bucket}/text.txt", 400, invalid,+ "Job document located at {} is an invalid JSON document."),+ (f"s3://{bucket}/empty.json", 400, invalid,+ "Job document located at {} is an invalid JSON document."),+ (f"s3://{bucket}/big.json", 410, "LimitExceededException",+ "Job document from {} exceeds size limit 32768 bytes."),+ ]+ for source, status, code, message in cases:+ job_id = _unique("job")+ with pytest.raises(ClientError) as ei:+ iot_client.create_job(+ jobId=job_id, targets=[thing_arn], documentSource=source+ )+ assert _error(ei) == (status, code, message.format(source)), source+ with pytest.raises(ClientError) as ei:+ iot_client.describe_job(jobId=job_id)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"++ status, body = _raw(+ _IOT_AUTH, "PUT", f"/jobs/{_unique('job')}", {"targets": [thing_arn], "documentSource": 123}+ )+ assert (status, body.get("message")) == (400, "Job document source 123 is invalid.")++ with pytest.raises(ClientError) as ei:+ iot_client.create_job(+ jobId=_unique("job"), targets=[thing_arn], document=_DOCUMENT,+ documentSource=f"s3://{bucket}/missing.json",+ )+ assert _error(ei) == (+ 400, invalid,+ "Job document and job document source cannot be specified at the same time.",+ )+ finally:+ _cleanup(iot_client, things=[thing])+ _delete_bucket(s3, bucket)+++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")+ owner_eu = _account_client("iot", "111111111111", region="eu-west-1")+ stranger = _account_client("iot", "222222222222")+ thing, bucket, job_id = _unique("jobs-thing"), _unique("jobs-doc"), _unique("job")+ try:+ owner_s3.create_bucket(Bucket=bucket)+ owner_s3.put_object(Bucket=bucket, Key="doc.json", Body=_DOCUMENT)+ owner_eu.create_job(jobId=job_id, targets=[_create_thing(owner_eu, thing)],+ documentSource=f"s3://{bucket}/doc.json")+ assert owner_eu.get_job_document(jobId=job_id)["document"] == _DOCUMENT+ with pytest.raises(ClientError) as ei:+ stranger.create_job(jobId=_unique("job"),+ targets=[_create_thing(stranger, thing)],+ documentSource=f"s3://{bucket}/doc.json")+ assert _error(ei) == (+ 400, "InvalidRequestException",+ f"Bucket specified by url: s3://{bucket}/doc.json is not found.",+ )+ finally:+ _cleanup(owner_eu, jobs=[job_id], things=[thing])+ _cleanup(stranger, things=[thing])+ _delete_bucket(owner_s3, bucket)def test_iot_jobs_create_duplicate_and_unknown_target_rejected(iot_client):@@ -394,6 +561,55 @@ def test_iot_job_template_from_a_job(iot_client):_cleanup(iot_client, jobs=[job_id], things=[thing])+def test_iot_job_template_document_source_reads_the_s3_object(iot_client, s3):+ """CreateJobTemplate reads its documentSource once; jobs made from it keep that content."""+ thing, bucket = _unique("jobs-thing"), _unique("jobs-doc")+ template_id, from_job = _unique("tmpl"), _unique("tmpl-job")+ plain, own_source = _unique("job"), _unique("job")+ source = f"s3://{bucket}/tmpl.json"+ try:+ thing_arn = _create_thing(iot_client, thing)+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key="tmpl.json", Body='{"v": 1}')+ template_arn = iot_client.create_job_template(+ jobTemplateId=template_id, description="d", documentSource=source+ )["jobTemplateArn"]+ s3.put_object(Bucket=bucket, Key="tmpl.json", Body='{"v": 2}')+ desc = iot_client.describe_job_template(jobTemplateId=template_id)+ assert (desc["document"], desc["documentSource"]) == ('{"v": 1}', source)++ job_arn = iot_client.create_job(+ jobId=plain, targets=[thing_arn], jobTemplateArn=template_arn+ )["jobArn"]+ assert iot_client.describe_job(jobId=plain)["documentSource"] == source+ assert iot_client.get_job_document(jobId=plain)["document"] == '{"v": 1}'+ iot_client.create_job(jobId=own_source, targets=[thing_arn],+ jobTemplateArn=template_arn, documentSource=source)+ assert iot_client.get_job_document(jobId=own_source)["document"] == '{"v": 2}'+ iot_client.create_job_template(+ jobTemplateId=from_job, description="d", jobArn=job_arn+ )+ desc = iot_client.describe_job_template(jobTemplateId=from_job)+ assert (desc["document"], desc["documentSource"]) == ('{"v": 1}', source)++ for missing, message in (+ (f"s3://{bucket}/missing.json", "Job document located at {} is not found."),+ (f"s3://{bucket}-none/doc.json", "Bucket specified by url: {} is not found."),+ ):+ missing_id = _unique("tmpl")+ with pytest.raises(ClientError) as ei:+ iot_client.create_job_template(+ jobTemplateId=missing_id, description="d", documentSource=missing+ )+ assert _error(ei) == (400, "InvalidRequestException", message.format(missing))+ with pytest.raises(ClientError):+ iot_client.describe_job_template(jobTemplateId=missing_id)+ finally:+ _delete_templates(iot_client, template_id, from_job)+ _cleanup(iot_client, jobs=[plain, own_source], things=[thing])+ _delete_bucket(s3, bucket)++def test_iot_job_template_rejects_what_aws_rejects(iot_client):template_id = _unique("tmpl")try:@@ -591,7 +807,7 @@ def test_iot_jobs_start_next_update_and_auto_complete(iot_client, iot_jobs_data)assert execution["jobId"] == job_idassert execution["status"] == "IN_PROGRESS"assert execution["versionNumber"] == 2 # start bumped it from 1- assert execution["jobDocument"] == _DOCUMENT+ assert execution["jobDocument"] == _DEVICE_DOCUMENT_assert_epoch_seconds(execution["startedAt"])pending = iot_jobs_data.get_pending_job_executions(thingName=thing)@@ -942,7 +1158,7 @@ def test_iot_jobs_next_sentinel_peek_then_start(iot_client, iot_jobs_data):assert peeked["jobId"] == job_idassert peeked["status"] == "QUEUED"assert peeked["versionNumber"] == 1- assert peeked["jobDocument"] == _DOCUMENT+ assert peeked["jobDocument"] == _DEVICE_DOCUMENT# PUT $next starts it.started = iot_jobs_data.start_next_pending_job_execution(thingName=thing)@@ -3063,6 +3279,27 @@ def test_jobs_mqtt_next_sentinel_get(iot_client, iot_data_client):assert doc["inProgressJobs"] == []+def test_jobs_mqtt_job_document_leaves_out_null_members(iot_client, iot_data_client):+ """The jobDocument object over MQTT is the device's document: no null members, Infinity as a string."""+ thing = _unique("jobs-mqtt-doc")+ job_id = _unique("job")+ thing_arn = _create_thing(iot_client, thing)+ iot_client.create_job(+ jobId=job_id,+ targets=[thing_arn],+ document='{"n": null, "o": {"n": null, "k": [null]}, "f": [1E400, 2.50]}',+ )+ base = f"$aws/things/{thing}/jobs"++ received = _collect_shadow_frames(+ f"{base}/{job_id}/get/accepted",+ lambda: _mqtt_publish(topic=f"{base}/{job_id}/get", payload=b"{}"),+ want=1,+ )+ execution = _frames_by_topic(received)[f"{base}/{job_id}/get/accepted"]["execution"]+ assert execution["jobDocument"] == {"o": {"k": [None]}, "f": ["Infinity", 2.5]}++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) isrejected with the InvalidJson code instead of being coerced to {}."""