Skip to content

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

fix(iot): resolve thing-group membership ARNs in the request body (#2389)

iot-rocket64ab6437772d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0f4d314f..de64bc97 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **Auth — SigV4a signatures are verified under `AUTH=true`** — requests signed with `AWS4-ECDSA-P256-SHA256`, which SDKs use for Multi-Region Access Points, were refused for every IAM user. Header and presigned S3 signatures are now checked with the P-256 key SigV4a derives from the secret, with their date or expiry, and an `X-Amz-Region-Set` that leaves out the serving region is refused (`RegionSetMismatch` on S3, the unknown-key error elsewhere). Contributed by @iot-rocket.
### Fixed
+- **IoT — thing-group membership by ARN** — `AddThingToThingGroup` and `RemoveThingFromThingGroup` ignored `thingGroupArn` and `thingArn`, so a body with ARNs answered 400 or 404; both calls now act on the thing group and thing the ARNs name (in the request's region, as on AWS), refuse a name and ARN that differ, an ARN of another type or account and a body without the group or the thing with 400 `InvalidRequestException` and AWS's messages, and removing a thing from a group that does not exist answers 200 also when the group is given by ARN. Under `AUTH=true` such an ARN is authorized as that resource. Contributed by @iot-rocket.
- **Reset — `/_ministack/reset` no longer removes another MiniStack's containers** — the OpenSearch, OpenSearch Serverless, DSQL, ECS and EKS resets removed every container carrying the service's label on the Docker daemon, including those of other MiniStack instances sharing it. They now remove only this instance's (`ministack.instance`), as the EC2, Lambda microVM and Flink resets and the boot and shutdown sweeps already do. Contributed by @jeffreyheller.
- **S3 — Multi-Region Access Point requests are authorized** — under `AUTH=true`, requests through an MRAP hostname were served without an IAM check. They are now authorized on the member bucket and then on the MRAP, whose policy is evaluated like a bucket policy, and answer `AccessDenied` naming the resource that refused them. Contributed by @iot-rocket.
- **Cognito — signing keys, managed login and federated users** — every user pool signed with one shared key (`kid` `ministack-key-1`); each pool now has two keys of its own, one for access tokens and one for ID tokens, both published at its JWKS URI, and a token verifies only against its own pool. Managed login refuses PKCE `plain` and a `code_challenge` without `S256` (`error=invalid_request`), any `redirect_uri` the client didn't register, also for a client with no callback URLs, and a `grant_type` other than `authorization_code`, `refresh_token` or `client_credentials` (400 `unsupported_grant_type`). Adding an identity provider creates the group `<user pool id>_<provider name>`, and a federated user's new profile joins it and carries its `identities`, so the ID token has both claims. Reported by @cupidchan.
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index 8d1b507a..54bc73b4 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -17,6 +17,8 @@ from urllib.parse import quote, unquote
from defusedxml.ElementTree import ParseError, fromstring
+from ministack.core.arn import ArnParseError, parse_arn
+
logger = logging.getLogger("ministack")
# ---------------------------------------------------------------------------
@@ -1836,10 +1838,17 @@ def iot_resource_arns(method: str, path: str, body: bytes, region: str, account_
data = {}
arns = []
for field, rtype in (("thingGroup", "thinggroup"), ("thing", "thing")):
- # The handler acts on the name when the body carries both.
+ # The handler refuses a body whose name and ARN differ, and an ARN of
+ # another region names the resource of the request's region.
name, arn = data.get(f"{field}Name"), data.get(f"{field}Arn")
+ try:
+ spec = parse_arn(arn)
+ except ArnParseError:
+ spec = None
if isinstance(name, str) and name:
arns.append(f"arn:aws:iot:{region}:{account_id}:{rtype}/{name}")
+ elif spec and spec.service == "iot" and spec.account_id == account_id and spec.resource.startswith(f"{rtype}/"):
+ arns.append(f"arn:aws:iot:{region}:{account_id}:{spec.resource}")
else:
arns.append(arn if isinstance(arn, str) and arn else "*")
return arns
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 740e00db..5c5a1131 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -1877,15 +1877,53 @@ def _delete_thing_group(name: str) -> tuple:
return json_response({})
+_MEMBERSHIP_ARN_ERRORS = {
+ "thingGroup": ("thinggroup", "Invalid ThingGroupArn",
+ "ThingGroupName from thingGroupArn does not match specified thingGroupName in request"),
+ "thing": ("thing", "Invalid ThingArn", "ThingName in thingArn does not match specified thingName in request"),
+}
+
+
+def _membership_name(payload: dict, field: str) -> tuple[str, tuple | None]:
+ """The thing group or thing (``field``) a membership call names by name or ARN, or the call's refusal."""
+ rtype, invalid, mismatch = _MEMBERSHIP_ARN_ERRORS[field]
+ name, arn = payload.get(f"{field}Name"), payload.get(f"{field}Arn")
+ if not arn:
+ if name:
+ return name, None
+ message = f"Both {field}Arn and {field}Name are empty. Need to specify at least one of them"
+ return "", error_response_json("InvalidRequestException", message, 400)
+ try:
+ spec = parse_arn(arn)
+ except ArnParseError:
+ return "", error_response_json("InvalidRequestException", "Invalid arn in request", 400)
+ if spec.account_id != get_account_id():
+ return "", error_response_json(
+ "InvalidRequestException", "ResourceArn doesn't belong in requester's account", 400)
+ # The ARN's region is not checked: the call acts on the resource of its own region.
+ if spec.service != "iot" or not spec.resource.startswith(f"{rtype}/"):
+ return "", error_response_json("InvalidRequestException", invalid, 400)
+ arn_name = spec.resource[len(rtype) + 1:]
+ if name and name != arn_name:
+ return "", error_response_json("InvalidRequestException", mismatch, 400)
+ return arn_name, None
+
+
+def _membership_names(payload: dict) -> tuple[str, str, tuple | None]:
+ """The thing group and the thing a membership call names, or its refusal (the group's first)."""
+ gname, error = _membership_name(payload, "thingGroup")
+ if error:
+ return "", "", error
+ tname, error = _membership_name(payload, "thing")
+ return gname, tname, error
+
+
async def _add_thing_to_group(payload: dict) -> tuple:
"""Async because a CONTINUOUS job the thing joins publishes
jobs/notify(-next) through the broker."""
- gname = payload.get("thingGroupName")
- tname = payload.get("thingName")
- if not gname or not tname:
- return error_response_json(
- "InvalidRequestException", "thingGroupName and thingName are required", 400
- )
+ gname, tname, error = _membership_names(payload)
+ if error:
+ return error
group = _thing_groups.get(gname)
if group is None:
return _error_not_found("ThingGroupMember", gname)
@@ -1909,15 +1947,16 @@ async def _add_thing_to_group(payload: dict) -> tuple:
async def _remove_thing_from_group(payload: dict) -> tuple:
"""Async because a QUEUED CONTINUOUS execution the removal retires
publishes jobs/notify(-next) through the broker."""
- gname = payload.get("thingGroupName")
- tname = payload.get("thingName")
- group = _thing_groups.get(gname) if gname else None
- thing = _things.get(tname) if tname else None
+ gname, tname, error = _membership_names(payload)
+ if error:
+ return error
+ group = _thing_groups.get(gname)
+ thing = _things.get(tname)
if thing is None:
- return _error_not_found("Thing", tname or "")
+ return _error_not_found("Thing", tname)
if group is None:
- # Only a named group that does not exist answers 200; a group ARN is not resolved.
- return json_response({}) if gname else _error_not_found("ThingGroup", "")
+ # A group that does not exist answers 200.
+ return json_response({})
prev_next = jobs_first_pending_job_id(tname)
left = tname in group.get("things", [])
if left:
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 2e0cd3d2..d2459ee2 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -2448,6 +2448,7 @@ class TestResourceArn:
for path in ("/thing-groups/addThingToThingGroup", "/thing-groups/removeThingFromThingGroup"):
for body in ({"thingGroupName": "fleet", "thingName": "dev-1"},
{"thingGroupArn": group, "thingArn": thing},
+ {"thingGroupArn": group.replace("us-east-1", "eu-west-3"), "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]
diff --git a/tests/test_iot.py b/tests/test_iot.py
index a1bbb707..5d3ec5ce 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -956,8 +956,57 @@ def test_iot_thing_group_membership(iot_client):
iot_client.delete_thing_group(thingGroupName=gname)
+def test_iot_thing_group_membership_by_arn(iot_client):
+ """Either side may be named by ARN; a name and an ARN must agree, and the ARN's region is not checked."""
+ gname, other, tname = _unique("group"), _unique("group"), _unique("thing")
+ group = iot_client.create_thing_group(thingGroupName=gname)["thingGroupArn"]
+ other_group = iot_client.create_thing_group(thingGroupName=other)["thingGroupArn"]
+ thing = iot_client.create_thing(thingName=tname)["thingArn"]
+ _, _, _, region, account, _ = group.split(":", 5)
+ elsewhere = group.replace(f":{region}:", ":eu-west-3:" if region != "eu-west-3" else ":us-east-1:")
+ foreign = group.replace(f":{account}:", ":123456789012:" if account != "123456789012" else ":210987654321:")
+ try:
+ for kwargs in ({"thingGroupArn": group, "thingArn": thing},
+ {"thingGroupArn": elsewhere, "thingName": tname},
+ {"thingGroupName": gname, "thingGroupArn": group, "thingName": tname, "thingArn": thing}):
+ iot_client.add_thing_to_thing_group(**kwargs)
+ assert tname in iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]
+ iot_client.remove_thing_from_thing_group(**kwargs)
+ assert tname not in iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]
+
+ refused = (
+ ({"thingGroupName": gname, "thingGroupArn": other_group, "thingName": tname},
+ "ThingGroupName from thingGroupArn does not match specified thingGroupName in request"),
+ ({"thingGroupName": gname, "thingName": _unique("thing"), "thingArn": thing},
+ "ThingName in thingArn does not match specified thingName in request"),
+ ({"thingName": tname},
+ "Both thingGroupArn and thingGroupName are empty. Need to specify at least one of them"),
+ ({"thingGroupName": gname}, "Both thingArn and thingName are empty. Need to specify at least one of them"),
+ ({"thingGroupArn": thing, "thingName": tname}, "Invalid ThingGroupArn"),
+ ({"thingGroupName": gname, "thingArn": group}, "Invalid ThingArn"),
+ ({"thingGroupArn": gname, "thingName": tname}, "Invalid arn in request"),
+ ({"thingGroupArn": foreign, "thingName": tname}, "ResourceArn doesn't belong in requester's account"),
+ )
+ for kwargs, message in refused:
+ for call in (iot_client.add_thing_to_thing_group, iot_client.remove_thing_from_thing_group):
+ with pytest.raises(ClientError) as ei:
+ call(**kwargs)
+ error = ei.value.response
+ assert error["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert (error["Error"]["Code"], error["Error"]["Message"]) == ("InvalidRequestException", message)
+ assert tname not in iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]
+
+ unknown = f"{group.rsplit('/', 1)[0]}/{_unique('group')}"
+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):
+ iot_client.add_thing_to_thing_group(thingGroupArn=unknown, thingName=tname)
+ finally:
+ iot_client.delete_thing_group(thingGroupName=gname)
+ iot_client.delete_thing_group(thingGroupName=other)
+ iot_client.delete_thing(thingName=tname)
+
+
def test_iot_remove_thing_from_an_unknown_thing_group_succeeds(iot_client):
- """An unknown group name answers 200; an unknown thing, or no group name at all, is refused."""
+ """An unknown group, by name or by ARN, answers 200; an unknown thing is refused."""
tname, gname = _unique("thing"), _unique("group")
iot_client.create_thing(thingName=tname)
resp = iot_client.remove_thing_from_thing_group(thingGroupName=_unique("group"), thingName=tname)
@@ -965,11 +1014,12 @@ def test_iot_remove_thing_from_an_unknown_thing_group_succeeds(iot_client):
with pytest.raises(iot_client.exceptions.ResourceNotFoundException):
iot_client.remove_thing_from_thing_group(thingGroupName=_unique("group"), thingName=_unique("thing"))
group_arn = iot_client.create_thing_group(thingGroupName=gname)["thingGroupArn"]
+ unknown_arn = f"{group_arn.rsplit('/', 1)[0]}/{_unique('group')}"
+ resp = iot_client.remove_thing_from_thing_group(thingGroupArn=unknown_arn, thingName=tname)
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
iot_client.add_thing_to_thing_group(thingGroupName=gname, thingName=tname)
- with pytest.raises(iot_client.exceptions.ResourceNotFoundException):
- iot_client.remove_thing_from_thing_group(thingGroupArn=group_arn, thingName=tname)
- assert tname in iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]
- iot_client.remove_thing_from_thing_group(thingGroupName=gname, thingName=tname)
+ iot_client.remove_thing_from_thing_group(thingGroupArn=group_arn, thingName=tname)
+ assert tname not in iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]
iot_client.delete_thing_group(thingGroupName=gname)
iot_client.delete_thing(thingName=tname)
@@ -1015,6 +1065,48 @@ def test_iot_thing_group_membership_authorizes_on_the_group_and_the_thing(auth_e
iot_client.delete_thing(thingName=tname)
+def test_iot_thing_group_membership_by_arn_authorizes_the_resources_it_names(auth_enabled, iam_user, iot_client):
+ """A group ARN of another region is checked, and acted on, as the group of the request's region."""
+ gname, tname = _unique("group"), _unique("thing")
+ group = iot_client.create_thing_group(thingGroupName=gname)["thingGroupArn"]
+ thing = iot_client.create_thing(thingName=tname)["thingArn"]
+ region = group.split(":")[3]
+ elsewhere = group.replace(f":{region}:", ":eu-west-3:" if region != "eu-west-3" else ":us-east-1:")
+
+ 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)
+ for body in ({"thingGroupArn": group, "thingArn": thing}, {"thingGroupArn": elsewhere, "thingArn": thing}):
+ allowed.add_thing_to_thing_group(**body)
+ assert tname in iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]
+ allowed.remove_thing_from_thing_group(**body)
+ assert tname not in iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]
+
+ # A grant on the other region's ARN does not cover the group the call acts on.
+ user = client(elsewhere, thing)
+ 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(thingGroupArn=elsewhere, thingName=tname)
+ error = ei.value.response
+ assert error["ResponseMetadata"]["HTTPStatusCode"] == 403
+ assert error["Error"]["Code"] == "AccessDeniedException"
+ assert f" iot:{action} on resource: {group} " in error["Error"]["Message"]
+ else:
+ assert call(thingGroupArn=elsewhere, 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")