Skip to content

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

fix(iot): authorize thing-group membership on the group and the thing (#2371)

iot-rocket3cc7fd23539d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ce708707..a5d05a23 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **IoT — thing-group membership authorized on the group and the thing** — with `AUTH=true`, `AddThingToThingGroup` and `RemoveThingFromThingGroup` were authorized on `thinggroup/addThingToThingGroup` (the request path), so a policy granting exactly the thing group and the thing was denied; both calls are now checked on the thing group and then the thing named in the body (by name or ARN), and a denial names the resource that failed. Contributed by @iot-rocket.
- **API Gateway — `AWS_IAM` methods refuse an `Authorization` header that is not SigV4** — under `AUTH=true` a REST API method with `AWS_IAM` authorization served a bearer token or an algorithm in lower case, and answered the SigV4a algorithm name without a signed `x-amz-region-set` or an unknown `AWS4-` algorithm with `UnrecognizedClientException`; it now answers 403 `IncompleteSignatureException` with API Gateway's message for each, while a method without `AWS_IAM` still serves such calls. Contributed by @iot-rocket.
- **S3 — access point policies and unsigned requests** — an access point policy was stored but never applied, and an unsigned request through an access point was served. With `AUTH=true` a request through an access point alias or ARN is allowed on the access point by an identity policy or the access point policy (a Deny in either refuses it), and an unsigned one gets 400 `InvalidRequest`; S3 Control calls on the access point are unaffected. Contributed by @iot-rocket.
diff --git a/ministack/app.py b/ministack/app.py
index ffe43b95..0951d277 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -2885,6 +2885,7 @@ async def _dispatch_service_request(
eventbridge_resource_arns,
extract_iam_action,
extract_resource_arn,
+ iot_resource_arns,
logs_service_context,
request_tag_context,
s3_access_point_resources,
@@ -3009,6 +3010,16 @@ async def _dispatch_service_request(
)
if denied:
break
+ # A thing-group membership call is also checked on the thing it names.
+ if service == "iot" and not denied:
+ for extra_arn in iot_resource_arns(method, path, body, region, get_account_id())[1:]:
+ denied = enforce(
+ access_key, iam_action, service, region,
+ resource_arn=extra_arn, service_context=service_context,
+ )
+ if denied:
+ resource_arn = extra_arn # named in the AccessDenied message
+ break
if (
denied
and service == "bedrock-agentcore"
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index 2b9088ec..4223250b 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -1641,6 +1641,11 @@ def extract_resource_arn(service: str, method: str, path: str,
arn = (_safe_json_field(body, "resourceArn") if method == "POST"
else _query_param(query_params, "resourceArn"))
return arn if isinstance(arn, str) and arn else "*"
+ # A membership call is checked on the thing group and the thing its body
+ # names: the group here, the thing in iot_resource_arns()[1:].
+ membership = iot_resource_arns(method, path, body, region, account_id)
+ if membership:
+ return membership[0]
_IOT_RESOURCES = {
"things": "thing",
"thing-types": "thingtype",
@@ -1816,6 +1821,30 @@ def dynamodb_resource_arns(body: bytes, region: str, account_id: str) -> list[st
]
+_IOT_MEMBERSHIP_PATHS = ("/thing-groups/addThingToThingGroup", "/thing-groups/removeThingFromThingGroup")
+
+
+def iot_resource_arns(method: str, path: str, body: bytes, region: str, account_id: str) -> list[str]:
+ """The thing group and the thing a thing-group membership call names, in the order AWS checks them."""
+ if method not in ("PUT", "POST") or path not in _IOT_MEMBERSHIP_PATHS:
+ return []
+ try:
+ data = json.loads(body or b"{}")
+ except (json.JSONDecodeError, TypeError, UnicodeDecodeError):
+ data = {}
+ if not isinstance(data, dict):
+ data = {}
+ arns = []
+ for field, rtype in (("thingGroup", "thinggroup"), ("thing", "thing")):
+ # The handler acts on the name when the body carries both.
+ name, arn = data.get(f"{field}Name"), data.get(f"{field}Arn")
+ if isinstance(name, str) and name:
+ arns.append(f"arn:aws:iot:{region}:{account_id}:{rtype}/{name}")
+ else:
+ arns.append(arn if isinstance(arn, str) and arn else "*")
+ return arns
+
+
def logs_service_context(action: str, body: bytes, resource_arn: str,
region: str, account_id: str) -> dict:
"""Tag conditions from the Logs payload and the existing scoped resource.
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 64901ed2..fd6a058c 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -2441,6 +2441,25 @@ class TestResourceArn:
bad = json.dumps({"resourceArn": [group]}).encode()
assert extract_resource_arn("iot", "POST", "/untag", {}, bad, {}, "us-east-1", "123") == "*"
+ def test_iot_thing_group_membership_names_the_group_then_the_thing(self):
+ from ministack.core.iam_actions import extract_resource_arn, iot_resource_arns
+ head = "arn:aws:iot:us-east-1:123"
+ group, thing = f"{head}:thinggroup/fleet", f"{head}:thing/dev-1"
+ for path in ("/thing-groups/addThingToThingGroup", "/thing-groups/removeThingFromThingGroup"):
+ for body in ({"thingGroupName": "fleet", "thingName": "dev-1"},
+ {"thingGroupArn": group, "thingArn": thing},
+ {"thingGroupName": "fleet", "thingGroupArn": f"{head}:thinggroup/x", "thingName": "dev-1"}):
+ raw = json.dumps(body).encode()
+ assert iot_resource_arns("PUT", path, raw, "us-east-1", "123") == [group, thing]
+ assert extract_resource_arn("iot", "PUT", path, {}, raw, {}, "us-east-1", "123") == group
+ for raw in (b"{}", b"[]", b"not json", json.dumps({"thingGroupName": 1, "thingName": ["x"]}).encode()):
+ assert iot_resource_arns("PUT", path, raw, "us-east-1", "123") == ["*", "*"]
+ # DescribeThingGroup of a group with that name keeps its own resource.
+ assert iot_resource_arns("GET", "/thing-groups/addThingToThingGroup", b"", "us-east-1", "123") == []
+ assert extract_resource_arn(
+ "iot", "GET", "/thing-groups/addThingToThingGroup", {}, b"", {}, "us-east-1", "123"
+ ) == f"{head}:thinggroup/addThingToThingGroup"
+
def test_iot_job_policy_from_the_cdk_actually_allows_the_call(self):
"""The two halves together, which is where this showed up. The CDK's
AwsCustomResource emits exactly this policy for an IoT job, and every
diff --git a/tests/test_iot.py b/tests/test_iot.py
index d4e0b52a..a1bbb707 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -974,6 +974,47 @@ def test_iot_remove_thing_from_an_unknown_thing_group_succeeds(iot_client):
iot_client.delete_thing(thingName=tname)
+def test_iot_thing_group_membership_authorizes_on_the_group_and_the_thing(auth_enabled, iam_user, iot_client):
+ gname, tname = _unique("group"), _unique("thing")
+ group = iot_client.create_thing_group(thingGroupName=gname)["thingGroupArn"]
+ thing = iot_client.create_thing(thingName=tname)["thingArn"]
+ head = group.rsplit(":", 1)[0]
+ literals = [f"{head}:thinggroup/addThingToThingGroup", f"{head}:thinggroup/removeThingFromThingGroup"]
+
+ def client(*resources):
+ return iam_user(policy={"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Action": ["iot:AddThingToThingGroup", "iot:RemoveThingFromThingGroup"],
+ "Resource": list(resources),
+ }]}).client("iot")
+
+ try:
+ allowed = client(group, thing)
+ allowed.add_thing_to_thing_group(thingGroupName=gname, thingName=tname)
+ assert tname in iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]
+ allowed.remove_thing_from_thing_group(thingGroupName=gname, thingName=tname)
+ assert tname not in iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]
+
+ # The group is checked first, then the thing; a denial names the resource that failed.
+ for resources, denied_on in (([thing], group), ([group], thing), (literals, group)):
+ user = client(*resources)
+ for action, call in (("AddThingToThingGroup", user.add_thing_to_thing_group),
+ ("RemoveThingFromThingGroup", user.remove_thing_from_thing_group)):
+ if auth_enabled:
+ with pytest.raises(ClientError) as ei:
+ call(thingGroupName=gname, thingName=tname)
+ error = ei.value.response
+ assert error["ResponseMetadata"]["HTTPStatusCode"] == 403
+ assert error["Error"]["Code"] == "AccessDeniedException"
+ assert f" iot:{action} on resource: {denied_on} " in error["Error"]["Message"]
+ else:
+ assert call(thingGroupName=gname, thingName=tname)["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert tname not in iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]
+ finally:
+ iot_client.delete_thing_group(thingGroupName=gname)
+ iot_client.delete_thing(thingName=tname)
+
+
def test_iot_list_thing_groups_for_thing(iot_client):
tname = _unique("thing")
g1 = _unique("group")