Skip to content

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

fix(iot): refuse a status a device may not set before the lookup (#2255)

iot-rocketc595293bb065
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 173813d8..7c970023 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **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 573120fe..37eccde9 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -8254,24 +8254,11 @@ def jobs_update_execution(
"""Apply a device-reported status to an execution.
Returns ``(execution copy, None)``, or ``(None, error)`` for every
- rejection: unknown execution (404), stale or non-numeric
- `expectedVersion`, an already-terminal execution, an unknown status, the
- illegal walk back to QUEUED, and the service-side statuses a device may
- not set. A successful update may complete the job.
+ rejection, in this order: an unknown status or one a device may not set
+ (QUEUED and the service-side statuses), unknown execution (404), stale or
+ non-numeric `expectedVersion`, and an already-terminal execution. A
+ successful update may complete the job.
"""
- _jobs_materialize_executions(job_id)
- execution = _job_executions.get((thing_name, job_id))
- if execution is None:
- return None, error_response_json(
- "ResourceNotFoundException",
- f"Job {job_id} not found for {thing_name}",
- 404,
- )
- error = _jobs_check_expected_version(
- execution, expected_version, "InvalidStateTransitionException"
- )
- if error:
- return None, error
if not status or status not in _JOB_EXECUTION_STATUSES:
return None, error_response_json(
"InvalidRequestException",
@@ -8286,6 +8273,19 @@ def jobs_update_execution(
f"The status of job execution cannot be changed to be {status}",
409,
)
+ _jobs_materialize_executions(job_id)
+ execution = _job_executions.get((thing_name, job_id))
+ if execution is None:
+ return None, error_response_json(
+ "ResourceNotFoundException",
+ f"Job {job_id} not found for {thing_name}",
+ 404,
+ )
+ error = _jobs_check_expected_version(
+ execution, expected_version, "InvalidStateTransitionException"
+ )
+ if error:
+ return None, error
error = _jobs_reject_if_terminal(
execution,
f"Job {job_id} for {thing_name} has already finished with status {execution['status']}",
diff --git a/tests/test_iot_jobs_data.py b/tests/test_iot_jobs_data.py
index ce4d4291..02106096 100644
--- a/tests/test_iot_jobs_data.py
+++ b/tests/test_iot_jobs_data.py
@@ -1407,6 +1407,35 @@ def test_iot_jobs_update_rejects_service_side_statuses(
_cleanup(iot_client, jobs=[job_id], things=[thing])
+def test_iot_jobs_update_refuses_the_status_before_looking_up_the_execution(iot_client, iot_jobs_data):
+ """A status a device may not set is refused before the existence and version checks."""
+ thing = _unique("jobs-thing")
+ job_id = _unique("job")
+ try:
+ thing_arn = _create_thing(iot_client, thing)
+ iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)
+ cases = [(thing, job_id, {"expectedVersion": 99})]
+ cases += [(thing, _unique("no-job"), {}), (_unique("no-thing"), _unique("no-job"), {})]
+ for target_thing, target_job, extra in cases:
+ for status in ("QUEUED", "CANCELED", "TIMED_OUT"):
+ with pytest.raises(iot_jobs_data.exceptions.InvalidStateTransitionException) as ei:
+ iot_jobs_data.update_job_execution(
+ jobId=target_job, thingName=target_thing, status=status, **extra
+ )
+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409
+ assert ei.value.response["Error"]["Message"] == (
+ f"The status of job execution cannot be changed to be {status}"
+ )
+
+ # An unknown execution is reported before a stale expectedVersion.
+ with pytest.raises(iot_jobs_data.exceptions.ResourceNotFoundException):
+ iot_jobs_data.update_job_execution(
+ jobId=_unique("no-job"), thingName=thing, status="SUCCEEDED", expectedVersion=99
+ )
+ finally:
+ _cleanup(iot_client, jobs=[job_id], things=[thing])
+
+
def test_iot_jobs_update_non_numeric_expected_version_is_400(iot_client):
"""A non-numeric expectedVersion (only reachable outside boto3's client-
side typing) must be a clean InvalidRequestException, not a 500."""
@@ -4210,6 +4239,27 @@ def test_jobs_mqtt_version_mismatch_rejected(iot_client, iot_data_client):
_assert_epoch_seconds(doc["timestamp"])
+def test_jobs_mqtt_update_unknown_job_refused_status_rejected(iot_client, iot_data_client):
+ """A status a device may not set is refused before the job is looked up."""
+ thing = _unique("jobs-mqtt-rej")
+ _create_thing(iot_client, thing)
+ base = f"$aws/things/{thing}/jobs"
+
+ received = _collect_shadow_frames(
+ f"{base}/no-such-job/update/rejected",
+ lambda: _mqtt_publish(
+ topic=f"{base}/no-such-job/update",
+ payload=json.dumps({"status": "QUEUED", "clientToken": "tok-q"}).encode(),
+ ),
+ want=1,
+ )
+ doc = _frames_by_topic(received)[f"{base}/no-such-job/update/rejected"]
+ assert doc["code"] == "InvalidStateTransition"
+ assert doc["message"] == "The status of job execution cannot be changed to be QUEUED"
+ assert "executionState" not in doc
+ assert doc["clientToken"] == "tok-q"
+
+
def test_jobs_mqtt_update_unknown_job_rejected(iot_client, iot_data_client):
"""An update for a job that does not exist answers update/rejected with
the string ResourceNotFound code — never a silent drop."""