Skip to content

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

fix(iot): answer iot-data denials with ForbiddenException under AUTH (#2268)

iot-rocket41dd9c569850
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1e9ac22d..066fb38e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **IoT Data — denials answer `ForbiddenException` under `AUTH=true`** — the data plane (Publish, retained messages, shadows) answered an IAM denial or a failed authentication with `AccessDeniedException`, `InvalidSignatureException` or `UnrecognizedClientException` and the principal and action in the message; it now answers 403 `ForbiddenException` as AWS does, with no message for a policy denial and `Forbidden` for a failed authentication. Contributed by @iot-rocket.
- **IoT — `aws:ResourceTag` conditions and the denied resource under `AUTH=true`** — a policy condition on `aws:ResourceTag/<key>` never matched for IoT, so a tag-scoped Allow denied every call and a tag-scoped Deny never applied; it now reads the tags of the thing group, policy, job or other IoT resource the call names, and an IoT denial names that resource (`on resource: <arn>`, `*` for a call that names none) as AWS does. Contributed by @iot-rocket.
- **IoT — tagging calls are authorized on the tagged resource under `AUTH=true`** — `TagResource`, `UntagResource` and `ListTagsForResource` were checked against resource `*`, so a policy scoped to a thing group, job or other IoT ARN denied them even on that resource, and only `Resource: "*"` let them through; they are now checked against the `resourceArn` the request names. Contributed by @iot-rocket.
- **IoT — tagging calls are authorized on the tagged resource under `AUTH=true`** — `TagResource`, `UntagResource` and `ListTagsForResource` were checked against resource `*`, so a policy scoped to a thing group, job or other IoT ARN denied them even on that resource, and only `Resource: "*"` let them through; they are now checked against the `resourceArn` the request names. Contributed by @iot-rocket.
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index 60df90f5..5fece287 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -12,6 +12,7 @@ import json
import logging
import os
import re
+import uuid
from urllib.parse import quote, unquote
from defusedxml.ElementTree import ParseError, fromstring
@@ -2100,6 +2101,13 @@ def access_denied_response(service: str, action: str, principal_arn: str,
400, {"Content-Type": "application/x-amz-json-1.1"},
json.dumps({"__type": "AccessDeniedException", "Message": message}).encode(),
)
+ if service == "iot-data":
+ # The IoT data plane answers every refusal ForbiddenException: "Forbidden"
+ # for a failed authentication, no message for a policy denial.
+ return (
+ 403, {"Content-Type": "application/json", "x-amzn-errortype": "ForbiddenException:"},
+ json.dumps({"message": "Forbidden" if error_code else None, "traceId": str(uuid.uuid4())}).encode(),
+ )
if not message and explicit_deny and resource_policy_arn:
message = _resource_policy_denial(service, action, principal_arn, resource_policy_arn)
if not message:
diff --git a/tests/test_iot_data.py b/tests/test_iot_data.py
index e1ed6b13..69b266aa 100644
--- a/tests/test_iot_data.py
+++ b/tests/test_iot_data.py
@@ -407,6 +407,66 @@ def test_iot_data_publish_refuses_invalid_mqtt5_properties(kwargs, user_properti
assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+# IAM contracts, run by CI with AUTH=false and AUTH=true.
+def auth_iot_shadow(iot_data_client):
+ """A classic shadow to read, removed after the test."""
+ thing = _unique("auth-thing")
+ iot_data_client.update_thing_shadow(thingName=thing, payload=b'{"state":{"reported":{"a":1}}}')
+ yield thing
+ iot_data_client.delete_thing_shadow(thingName=thing)
+
+
[email protected]("permission", ["none", "allow", "explicit-deny"])
+def test_iot_data_permission_contract(auth_enabled, iam_user, auth_iot_shadow, permission):
+ """A refused data plane call answers 403 ForbiddenException without a message."""
+ statements = []
+ if permission != "none":
+ statements.append({"Effect": "Allow", "Action": ["iot:Publish", "iot:GetThingShadow"], "Resource": "*"})
+ if permission == "explicit-deny":
+ statements.append({"Effect": "Deny", "Action": ["iot:Publish", "iot:GetThingShadow"], "Resource": "*"})
+ policy = {"Version": "2012-10-17", "Statement": statements} if statements else None
+ user = iam_user(policy=policy)
+ data = user.client("iot-data")
+ calls = (
+ lambda: data.publish(topic=_unique("auth/topic"), payload=b"{}"),
+ lambda: data.get_thing_shadow(thingName=auth_iot_shadow),
+ )
+ for call in calls:
+ if auth_enabled and permission != "allow":
+ with pytest.raises(ClientError) as exc:
+ call()
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
+ assert exc.value.response["Error"]["Code"] == "ForbiddenException"
+ assert exc.value.response["Error"]["Message"] is None
+ else:
+ assert call()["ResponseMetadata"]["HTTPStatusCode"] == 200
+ if auth_enabled and permission == "none":
+ # The control plane keeps its own denial.
+ with pytest.raises(ClientError) as exc:
+ user.client("iot").list_things()
+ assert exc.value.response["Error"]["Code"] == "AccessDeniedException"
+
+
+def test_iot_data_unknown_key_contract(auth_enabled):
+ """A key IAM does not know answers 403 ForbiddenException with the message Forbidden."""
+ data = boto3.client(
+ "iot-data", endpoint_url=ENDPOINT, region_name="us-east-1",
+ aws_access_key_id="AKIA" + uuid.uuid4().hex[:16].upper(), aws_secret_access_key="unknown-secret",
+ config=Config(retries={"total_max_attempts": 1}),
+ )
+ if auth_enabled:
+ with pytest.raises(ClientError) as exc:
+ data.publish(topic=_unique("auth/topic"), payload=b"{}")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
+ assert exc.value.response["Error"]["Code"] == "ForbiddenException"
+ assert exc.value.response["Error"]["Message"] == "Forbidden"
+ else:
+ assert data.publish(topic=_unique("auth/topic"), payload=b"{}")["ResponseMetadata"]["HTTPStatusCode"] == 200
+
+
# ---------------------------------------------------------------------------
# MQTT-over-WebSocket round-trip
# ---------------------------------------------------------------------------