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
fix(iot): evaluate aws:ResourceTag and name the resource in denials (#2267)
iot-rocketbadb3fbb6ae1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6df93b40..1e9ac22d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **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.- **AppSync — data-plane error responses** — Event API `POST /event` refusals answered `{"__type", "message"}` with MiniStack's own messages, and the GraphQL endpoint answered 500 for a body that is not a JSON object, a message-only 400 for a missing query and 200 for an unparseable one; both now answer AWS's `{"errors": [{"errorType", "message"}]}` envelope with AWS's error types, messages and `x-amzn-ErrorType` header (`SerializationException`, `MalformedHttpRequestException`, `ResourceNotFoundException` for an unknown API, `UnknownOperationException` for another path on an Event API host), and the publish endpoint answers `application/json`. Contributed by @iot-rocket.- **Cognito — OAuth scope checks for federation and `client_credentials`** — `/oauth2/authorize` with an `identity_provider` went on to the identity provider whatever the `scope`; it now redirects to the callback with `error_description=invalid_scope` (and the `state`) when a requested scope is not in the client's `AllowedOAuthScopes`, as the managed login does. The `client_credentials` grant answered `invalid_scope` to any request naming an undefined resource server scope; it now ignores those once a defined scope is requested, so `api/read bogus/x` is granted `api/read` and `api/admin bogus/x` answers `invalid_grant`, as AWS does. Contributed by @iot-rocket.diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex 17f03800..60df90f5 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -2107,7 +2107,9 @@ def access_denied_response(service: str, action: str, principal_arn: str,"with an explicit deny in an identity-based policy" if explicit_denyelse f"because no identity-based policy allows the {action} action")- message = f"User: {principal_arn} is not authorized to perform: {action} {reason}"+ # IoT names the resource, "*" for an action that takes none.+ on_resource = f" on resource: {resource_arn}" if service == "iot" else ""+ message = f"User: {principal_arn} is not authorized to perform: {action}{on_resource} {reason}"code = error_code or _DENIED_CODES.get(service, "AccessDenied")status = 403if code in _AUTH_FAILURES:diff --git a/ministack/services/tagging.py b/ministack/services/tagging.pyindex d171e03c..da005245 100644--- a/ministack/services/tagging.py+++ b/ministack/services/tagging.py@@ -269,10 +269,17 @@ def _collect_secretsmanager():yield secret.get("ARN", ""), _normalise_list(secret.get("Tags"))+def _collect_iot():+ import ministack.services.iot as svc+ for arn, tags in svc._tags.items():+ yield arn, _normalise_flat(tags)++# ARN service -> collector, for resolving aws:ResourceTag_RESOURCE_TAG_COLLECTORS = {"dynamodb": _collect_dynamodb,"iam": _collect_iam,+ "iot": _collect_iot,"kms": _collect_kms,"lambda": _collect_lambda,"secretsmanager": _collect_secretsmanager,diff --git a/tests/test_iot.py b/tests/test_iot.pyindex a1131d95..aadb3d9e 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -1222,6 +1222,66 @@ def test_iot_tagging_authorizes_on_the_resource_arn(auth_enabled, iam_user, iot_iot_client.delete_thing_group(thingGroupName=arn.rsplit("/", 1)[1])[email protected]_contract+def test_iot_resource_tag_conditions_decide_on_the_named_resource(auth_enabled, iam_user, iot_client):+ deletes = ["iot:DeleteThingGroup", "iot:DeletePolicy"]+ user = iam_user(policy={"Version": "2012-10-17", "Statement": [+ {"Effect": "Allow", "Action": ["iot:ListTagsForResource", "iot:DescribeThingGroup", "iot:GetPolicy"],+ "Resource": "*", "Condition": {"StringEquals": {"aws:ResourceTag/env": "dev"}}},+ {"Effect": "Allow", "Action": deletes, "Resource": "*"},+ {"Effect": "Deny", "Action": deletes, "Resource": "*",+ "Condition": {"StringEquals": {"aws:ResourceTag/env": "prod"}}},+ ]})+ client = user.client("iot")+ document = json.dumps({"Version": "2012-10-17", "Statement": [+ {"Effect": "Allow", "Action": "iot:Connect", "Resource": "*"}]})+ names = {env: _unique(f"rt-{env}") for env in ("dev", "prod", "untagged")}+ groups, policies = {}, {}+ for env, name in names.items():+ tags = {} if env == "untagged" else {"tags": [{"Key": "env", "Value": env}]}+ groups[env] = iot_client.create_thing_group(thingGroupName=name, **tags)["thingGroupArn"]+ policies[env] = iot_client.create_policy(policyName=name, policyDocument=document, **tags)["policyArn"]+ no_allow = "because no identity-based policy allows the {} action"+ explicit_deny = "with an explicit deny in an identity-based policy"+ try:+ client.describe_thing_group(thingGroupName=names["dev"])+ client.get_policy(policyName=names["dev"])+ client.list_tags_for_resource(resourceArn=policies["dev"])++ for call, action, resource, reason, kwargs in (+ (client.describe_thing_group, "DescribeThingGroup", groups["prod"], no_allow,+ {"thingGroupName": names["prod"]}),+ (client.describe_thing_group, "DescribeThingGroup", groups["untagged"], no_allow,+ {"thingGroupName": names["untagged"]}),+ (client.get_policy, "GetPolicy", policies["prod"], no_allow, {"policyName": names["prod"]}),+ (client.list_thing_groups, "ListThingGroups", "*", no_allow, {}),+ (client.delete_thing_group, "DeleteThingGroup", groups["prod"], explicit_deny,+ {"thingGroupName": names["prod"]}),+ (client.delete_policy, "DeletePolicy", policies["prod"], explicit_deny, {"policyName": names["prod"]}),+ ):+ if auth_enabled:+ with pytest.raises(ClientError) as ei:+ call(**kwargs)+ error = ei.value.response+ assert error["ResponseMetadata"]["HTTPStatusCode"] == 403+ assert error["Error"]["Code"] == "AccessDeniedException"+ assert error["Error"]["Message"] == (+ f"User: {user.arn} is not authorized to perform: iot:{action} on resource: {resource} "+ + reason.format(f"iot:{action}"))+ else:+ assert call(**kwargs)["ResponseMetadata"]["HTTPStatusCode"] == 200+ client.delete_thing_group(thingGroupName=names["untagged"])+ client.delete_policy(policyName=names["untagged"])+ finally:+ for name in names.values():+ for call, kwargs in ((iot_client.delete_thing_group, {"thingGroupName": name}),+ (iot_client.delete_policy, {"policyName": name})):+ try:+ call(**kwargs)+ except ClientError:+ pass++def test_iot_tag_limits_and_validation(iot_client):from conftest import make_client