Skip to content

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

feat(iot): add TagResource, UntagResource and ListTagsForResource (#2145)

iot-rocket8cc8c1dae692
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 038ac19f..f2330364 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+
+- **IoT — `TagResource`, `UntagResource` and `ListTagsForResource`** — the three operations answered `Unsupported IoT path`, so the tags the Create calls accept could not be read back. They now work on thing types, thing groups, policies, topic rules, jobs, job templates, CA certificates, provisioning templates and domain configurations with AWS's limits and errors, Create calls and CloudFormation `Tags` write the same tags, and deleting a resource drops them. Contributed by @iot-rocket.
### Fixed
- **IoT — deleting things, certificates, policies and thing types still in use** — `DeleteThing` detached a thing's certificates and deleted it, and `DeleteCertificate` refused only an `ACTIVE` certificate. Now `DeleteThing` refuses a thing with a certificate attached, `DeleteCertificate` refuses a certificate with things attached and, without `forceDelete`, one with policies attached (`forceDelete` detaches them), `DeletePolicy` refuses a policy with non-default versions and `DeleteThingType` one that things still use, all with AWS's messages. Contributed by @iot-rocket.
diff --git a/README.md b/README.md
index 78b8525c..dac34b6f 100644
--- a/README.md
+++ b/README.md
@@ -647,7 +647,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i
| **AppConfig** | CreateApplication, GetApplication, ListApplications, UpdateApplication, DeleteApplication, CreateEnvironment, GetEnvironment, ListEnvironments, UpdateEnvironment, DeleteEnvironment, CreateConfigurationProfile, GetConfigurationProfile, ListConfigurationProfiles, UpdateConfigurationProfile, DeleteConfigurationProfile, CreateHostedConfigurationVersion, GetHostedConfigurationVersion, ListHostedConfigurationVersions, DeleteHostedConfigurationVersion, CreateDeploymentStrategy, GetDeploymentStrategy, ListDeploymentStrategies, UpdateDeploymentStrategy, DeleteDeploymentStrategy, StartDeployment, GetDeployment, ListDeployments, StopDeployment, TagResource, UntagResource, ListTagsForResource, StartConfigurationSession, GetLatestConfiguration | 33 operations; control plane + data plane; hosted configuration versions; the AWS-predefined deployment strategies (4) are listed and immutable; deployments move through `DEPLOYING`, `BAKING` and `COMPLETE` on the strategy's schedule (`LINEAR` or `EXPONENTIAL` steps, then the bake time), with `PercentageComplete`, the event log and the environment `State` reported along the way; a `Monitors` alarm that goes to `ALARM` before the bake ends rolls the deployment back; one deployment per environment at a time (`ConflictException`, also for a stale `LatestDeploymentNumber`); `StopDeployment` rolls back a `DEPLOYING` deployment, and with `AllowRevert` also a `BAKING` one, or reverts a completed one within 72 hours; during a rollout a session gets the new version once the rollout reaches its fixed slot (MiniStack's choice, since AWS does not document how it picks targets); `GetLatestConfiguration` returns an empty body when the session already has the latest version, plus `Version-Label`, and uses `RequiredMinimumPollIntervalInSeconds` as the poll interval |
| **Transfer Family** | CreateServer, DescribeServer, DeleteServer, ListServers, StartServer, StopServer, CreateUser, DescribeUser, DeleteUser, ListUsers, ImportSshPublicKey, DeleteSshPublicKey | 12 operations; **real SFTP listener** on `:2222` (override with `SFTP_PORT`) backed by S3 — `ls`, `put`, `get`, `mkdir`, `rename` work end-to-end against the local S3 emulator; `SFTP_PORT_PER_SERVER=1` allocates one port per `CreateServer` from `SFTP_BASE_PORT` (default 2300); SSH key auth scans every user across every server and account; `LOGICAL` and `PATH` home-directory mappings; host key persists across restarts when `PERSIST_STATE=1` |
| **IoT Jobs** | Control plane (`iot`): CreateJob, UpdateJob, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, DescribeJobExecution, CancelJobExecution, CreateJobTemplate, DescribeJobTemplate, ListJobTemplates, DeleteJobTemplate; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 14 control-plane + 4 device data-plane operations sharing one store. A job created with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a request member replaces the template's. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED, TIMED_OUT}`; an execution past its `timeoutConfig.inProgressTimeoutInMinutes`, or past the `stepTimeoutInMinutes` the device reported, becomes `TIMED_OUT`, and the device plane reports `approximateSecondsBeforeTimedOut` while it runs. `REMOVED` is modeled and counted in `jobProcessDetails` but nothing sets it: deleting a thing DELETES its executions (freeing a job that was only waiting on that thing) rather than marking them `REMOVED`. `versionNumber` gives optimistic concurrency: every transition bumps it and a stale `expectedVersion` is rejected with a 409 whose message carries the current version — coded `VersionConflictException` on the control plane and `InvalidStateTransitionException` on the device plane, each as its own service model declares. `executionNumber` is write-once (always 1: an execution is never re-queued). Devices may only report `IN_PROGRESS` / `SUCCEEDED` / `FAILED` / `REJECTED` via `UpdateJobExecution`; targets are thing or thing-group ARNs — `SNAPSHOT` jobs resolve group membership once at creation, `CONTINUOUS` jobs also pick up things added to a target group later, and a target must name a thing or thing group in the caller's own account and region (anything else is `ResourceNotFoundException`, since it would resolve to no devices at all); a non-continuous job auto-`COMPLETED`s (with `jobProcessDetails` counts) once every execution is terminal. **`documentSource` is not fetched**: a job created with an S3 `documentSource` serves a `{"documentSource": "<url>"}` placeholder as its document rather than the object's content, so the lifecycle still runs — pass `document` when the content matters; a job template with a `documentSource` stores the same placeholder. **Timestamps are epoch seconds on every plane, as AWS documents**: control-plane responses use `timestamp` shapes (boto3 parses them to datetimes) while `iot-jobs-data` responses carry whole-second integer `long`s. **Jobs over MQTT**: the reserved `$aws/things/<thing>/jobs/#` request topics (`get`, `start-next`, `<jobId>/get` incl. `$next`, `<jobId>/update`) answer on their `accepted`/`rejected` topics from the same store as the HTTP plane (`jobDocument` as a JSON object over MQTT, a string over HTTP, as on AWS; rejections carry the string `ErrorCode` values and the execution's state on version and state-transition conflicts); `notify` fires when the pending set changes and `notify-next` when the queue front changes; `stepTimeoutInMinutes` and `executionNumber` are accepted but ignored. Job state persists with the IoT store when `PERSIST_STATE=1` |
-| **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, ListThingGroupsForThing, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, CreateCertificateFromCsr, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, ListCertificatesByCA, CreateProvisioningTemplate, DescribeProvisioningTemplate, ListProvisioningTemplates, UpdateProvisioningTemplate, DeleteProvisioningTemplate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub, DescribeEventConfigurations, UpdateEventConfigurations, CreateDomainConfiguration, DescribeDomainConfiguration, ListDomainConfigurations, UpdateDomainConfiguration, DeleteDomainConfiguration | 63 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `principal()`, `traceid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; a **provisioning-template registry** (`CreateProvisioningTemplate` and friends) — storage + CRUD only, so `provisioningRoleArn` is presence-checked but not resolved and the fleet-provisioning MQTT workflow (`$aws/provisioning-templates/...`) is not implemented; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry; the broker publishes the presence and subscription lifecycle events (`$aws/events/presence/connected\|disconnected/{clientId}`, `$aws/events/subscriptions/subscribed\|unsubscribed/{clientId}`) |
+| **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, ListThingGroupsForThing, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, CreateCertificateFromCsr, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, ListCertificatesByCA, CreateProvisioningTemplate, DescribeProvisioningTemplate, ListProvisioningTemplates, UpdateProvisioningTemplate, DeleteProvisioningTemplate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub, DescribeEventConfigurations, UpdateEventConfigurations, CreateDomainConfiguration, DescribeDomainConfiguration, ListDomainConfigurations, UpdateDomainConfiguration, DeleteDomainConfiguration, TagResource, UntagResource, ListTagsForResource | 66 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; a **provisioning-template registry** (`CreateProvisioningTemplate` and friends) — storage + CRUD only, so `provisioningRoleArn` is presence-checked but not resolved and the fleet-provisioning MQTT workflow (`$aws/provisioning-templates/...`) is not implemented; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry; the broker publishes the presence and subscription lifecycle events (`$aws/events/presence/connected\|disconnected/{clientId}`, `$aws/events/subscriptions/subscribed\|unsubscribed/{clientId}`) |
| **IoT Wireless** | GetPositionEstimate | Single operation (`POST /position-estimate`, SigV4 scope `iotwireless`, endpoint prefix `api.iotwireless`). **The response is the raw GeoJSON blob** — the output shape's `payload` trait — so boto3 hands back a `StreamingBody` under `GeoJsonPayload`, not a JSON envelope. Resolves from `Ip` only: `WiFiAccessPoints` / `CellTowers` / `Gnss` are accepted and ignored, `Timestamp` and `AdvancedConfiguration` only reach `properties`, and the estimate is synthetic + deterministic — the canonical IP (an IPv4-mapped IPv6 address counts as its IPv4 form) hashes onto lon [-180, 180) / lat [-60, 60), 4 decimals — so the same address always answers the same estimate and consumer tests can assert on it. `properties` carry `horizontalAccuracy` 1000000 (the value of one live call) and `horizontalConfidenceLevel` 0.68 (the default the AWS IoT Core Device Location guide documents — `AdvancedConfiguration.WiFiCellular.ConfidencePercent` overrides it, divided by 100, within the 50 to 99 the model allows) plus `timestamp`, which is always there: AWS documents the request's `Timestamp` as the resolve time and the receive time as its substitute when the caller sends none, so send a `Timestamp` and the whole blob is byte-identical. The real payload's `country` and city/state/postal properties are omitted for that determinism. An input with no resolver hint and an `IpAddress` that `ipaddress.ip_address()` refuses answer `ValidationException` (those two wordings are recorded from the live service; every other message in this service is MiniStack's own, since none is documented); a `Timestamp` that is not a Unix timestamp, and a `ConfidencePercent` outside the model's range, are `ValidationException` too; a valid address that is **not globally routable or is multicast** (private, loopback, TEST-NET, multicast groups, ...) answers `ResourceNotFoundException` `Cannot find position for the IP address <ip>`, mirroring the real service's refusal when its geo database has no entry. A well-formed request whose only measurements are WLAN/cell/GNSS is `ResourceNotFoundException` too — the developer guide documents 404 for exactly that ("no location information was found or solved ... The MAC address or cellular tower information is not sufficient ... The GNSS payload is not sufficient"), and 400 for measurement data formatted incorrectly. Stateless — nothing persists |
| **EventBridge Scheduler** | CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource | 12 actions; schedules **fire their targets** — a background sweep invokes each enabled schedule's target (Lambda, SQS, SNS, Step Functions) when due, honoring `State`, `StartDate`/`EndDate`, and `ActionAfterCompletion: DELETE`; schedule groups with cascading deletes; `rate()`, `cron()`, `at()` expressions; group/prefix/state filters on list; default group auto-created; CFN `AWS::Scheduler::Schedule` and `AWS::Scheduler::ScheduleGroup` supported |
| **EKS** | CreateCluster, DescribeCluster, ListClusters, DeleteCluster, CreateNodegroup, DescribeNodegroup, ListNodegroups, DeleteNodegroup, CreateAddon, DescribeAddon, ListAddons, UpdateAddon, DeleteAddon, AssociateEncryptionConfig, CreateAccessEntry, DescribeAccessEntry, ListAccessEntries, UpdateAccessEntry, DeleteAccessEntry, AssociateAccessPolicy, DisassociateAccessPolicy, ListAssociatedAccessPolicies, AssociateIdentityProviderConfig, DescribeIdentityProviderConfig, DisassociateIdentityProviderConfig, ListIdentityProviderConfigs, CreatePodIdentityAssociation, DescribePodIdentityAssociation, ListPodIdentityAssociations, UpdatePodIdentityAssociation, DeletePodIdentityAssociation, TagResource, UntagResource, ListTagsForResource | `CreateCluster` spawns a real **k3s** container (75 MB) with a full Kubernetes API server; `kubectl`, Helm, and any K8s tooling work out of the box; cascading delete removes nodegroups and k3s container; addon CRUD (e.g. `vpc-cni`, `coredns`, `kube-proxy`, `aws-ebs-csi-driver`) at `/clusters/{name}/addons` flips status to `ACTIVE` on create / update; `AssociateEncryptionConfig` at `/clusters/{name}/encryption-config/associate` records KMS encryption config (rejects re-association, AWS-shape `update` envelope); **Access Entries** (modern post-1.29 IAM bindings — replaces aws-auth ConfigMap) at `/clusters/{name}/access-entries[/{principalArn}[/access-policies[/{policyArn}]]]` for Crossplane / Terraform `aws_eks_access_entry` + `aws_eks_access_policy_association`; OIDC discovery + JWKS served at the cluster's `identity.oidc.issuer` URL so Terraform's `aws_iam_openid_connect_provider` (IRSA) works against ministack; **OIDC Identity Provider Config** (`AssociateIdentityProviderConfig` / `DescribeIdentityProviderConfig` / `DisassociateIdentityProviderConfig` / `ListIdentityProviderConfigs`) at `/clusters/{name}/identity-provider-configs[/{verb}]` — one OIDC IdP per cluster, issuer + clientId + claims forwarded to the k3s API server via `--kube-apiserver-arg=oidc-*` flags, tags reachable via `ListTagsForResource`; CFN `AWS::EKS::Cluster` and `AWS::EKS::Nodegroup` supported |
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 528c6cf5..fea7050e 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -3700,7 +3700,12 @@ def _pascal_to_camel(obj):
def _iot_topic_rule_create(logical_id, props, stack_name):
name = props.get("RuleName") or _physical_name(stack_name, logical_id).replace("-", "_")
payload = _pascal_to_camel(props.get("TopicRulePayload", {}))
+ tags = _iot_tags(props)
+ err = _iot._tags_error(tags, required=False)
+ if err:
+ raise ValueError(f"AWS::IoT::TopicRule create failed: {err[2]!r}")
_iot.put_topic_rule(name, payload)
+ _iot._set_created_tags(_iot._topic_rule_arn(name), tags)
return name, {"Arn": _iot._topic_rule_arn(name)}
@@ -3722,6 +3727,7 @@ def _iot_topic_rule_update(physical_id, old_props, new_props, stack_name, logica
name, payload,
created_at=existing.get("createdAt") if existing else None,
)
+ _iot_update_tags(_iot._topic_rule_arn(name), old_props, new_props)
return name, {"Arn": _iot._topic_rule_arn(name)}
@@ -13253,9 +13259,19 @@ def _iot_policy_principal_attachment_delete(physical_id, props):
# readable back through its real API instead of the stack rolling back.
+def _iot_tags(props):
+ """A Tags property as the IoT API's tag list."""
+ return [{"Key": k, "Value": v} for k, v in _tag_map(props.get("Tags")).items()]
+
+
+def _iot_update_tags(arn, old_props, new_props):
+ _reconcile_tag_map(_iot._tags.setdefault(arn, {}), old_props, new_props)
+
+
def _iot_thing_type_create(logical_id, props, stack_name):
name = props.get("ThingTypeName") or _physical_name(stack_name, logical_id)
- payload = {"thingTypeProperties": _pascal_to_camel(props.get("ThingTypeProperties") or {})}
+ payload = {"thingTypeProperties": _pascal_to_camel(props.get("ThingTypeProperties") or {}),
+ "tags": _iot_tags(props)}
resp = _iot._create_thing_type(name, payload)
if resp[0] >= 400:
raise ValueError(f"AWS::IoT::ThingType create failed: {resp[2]!r}")
@@ -13279,6 +13295,7 @@ def _iot_thing_type_import(identifier):
def _iot_thing_type_delete(physical_id, props):
_iot._thing_types.pop(physical_id, None)
+ _iot._tags.pop(_iot._thing_type_arn(physical_id), None)
def _iot_thing_type_update(physical_id, old_props, new_props, stack_name,
@@ -13321,6 +13338,7 @@ def _iot_thing_type_update(physical_id, old_props, new_props, stack_name,
status, _headers, body = _iot._deprecate_thing_type(physical_id, {"undoDeprecate": not deprecate})
if status >= 400:
raise ValueError(f"DeprecateThingType failed: {body}")
+ _iot_update_tags(_iot._thing_type_arn(physical_id), old_props, new_props)
return physical_id, _iot_thing_type_attrs(physical_id)
@@ -13352,7 +13370,7 @@ def _iot_thing_group_create(logical_id, props, stack_name):
# anything, whatever the properties (measured eu-central-1, 2026-10-05).
if name in _iot._thing_groups:
raise ValueError(f"Resource of type 'AWS::IoT::ThingGroup' with identifier '{name}' already exists.")
- payload = {"thingGroupProperties": _iot_thing_group_properties(props)}
+ payload = {"thingGroupProperties": _iot_thing_group_properties(props), "tags": _iot_tags(props)}
if props.get("ParentGroupName"):
payload["parentGroupName"] = props["ParentGroupName"]
resp = _iot._create_thing_group(name, payload)
@@ -13369,9 +13387,8 @@ def _iot_thing_group_update(physical_id, old_props, new_props, stack_name, logic
"""Update a thing group in place through UpdateThingGroup: ThingGroupProperties
is the one property the reference marks No interruption that the service
stores. ThingGroupName and ParentGroupName changes are replaced in
- ``_update_resource`` before this runs. QueryString and Tags are accepted
- without effect — the service has no dynamic groups and no tag store for
- thing groups."""
+ ``_update_resource`` before this runs. Tags go to the tag store; QueryString
+ is accepted without effect, the service has no dynamic groups."""
rec = _iot_thing_group_record(physical_id)
if rec is None:
return _iot_thing_group_create(logical_id or physical_id, new_props, stack_name)
@@ -13380,6 +13397,7 @@ def _iot_thing_group_update(physical_id, old_props, new_props, stack_name, logic
name, {"thingGroupProperties": _iot_thing_group_properties(new_props)})
if resp[0] >= 400:
raise ValueError(f"AWS::IoT::ThingGroup update failed: {resp[2]!r}")
+ _iot_update_tags(rec["thingGroupArn"], old_props, new_props)
return physical_id, {"Arn": rec["thingGroupArn"], "Id": physical_id}
@@ -13424,7 +13442,8 @@ def _iot_policy_prune_versions(name):
def _iot_policy_create(logical_id, props, stack_name):
name = props.get("PolicyName") or _physical_name(stack_name, logical_id)
- resp = _iot._create_policy(name, {"policyDocument": _iot_policy_document(props)})
+ resp = _iot._create_policy(name, {"policyDocument": _iot_policy_document(props),
+ "tags": _iot_tags(props)})
if resp[0] >= 400:
raise ValueError(f"AWS::IoT::Policy create failed: {resp[2]!r}")
return name, {"Arn": _iot._policy_arn(name), "Id": name}
@@ -13451,6 +13470,7 @@ def _iot_policy_update(physical_id, old_props, new_props, stack_name, logical_id
)
if resp[0] >= 400:
raise ValueError(f"AWS::IoT::Policy update failed: {resp[2]!r}")
+ _iot_update_tags(_iot._policy_arn(name), old_props, new_props)
return name, {"Arn": _iot._policy_arn(name), "Id": name}
@@ -13461,6 +13481,7 @@ def _iot_policy_import(identifier):
def _iot_policy_delete(physical_id, props):
_iot._policies.pop(physical_id, None)
+ _iot._tags.pop(_iot._policy_arn(physical_id), None)
def _iot_provisioning_template_body(props):
@@ -13502,7 +13523,7 @@ def _iot_provisioning_template_create(logical_id, props, stack_name):
stack_name, logical_id, max_len=36
)
resp = _iot._create_provisioning_template(
- _iot_provisioning_template_payload(name, props)
+ {**_iot_provisioning_template_payload(name, props), "tags": _iot_tags(props)}
)
if resp[0] == 409:
# Re-create of a surviving template (rollback replay re-enters create):
@@ -13560,6 +13581,7 @@ def _iot_provisioning_template_update(physical_id, old_props, new_props, stack_n
)
tmpl["templateBody"] = body
_iot._provisioning_templates[name] = tmpl
+ _iot_update_tags(_iot._provisioning_template_arn(name), old_props, new_props)
return name, _iot_provisioning_template_attrs(name)
@@ -13660,6 +13682,7 @@ def _iot_ca_certificate_create(logical_id, props, stack_name):
"verificationCertificate": props.get("VerificationCertificatePem"),
"certificateMode": props.get("CertificateMode"),
"registrationConfig": _registration_config_payload(props),
+ "tags": _iot_tags(props),
}
resp = _iot._register_ca_certificate(
{k: v for k, v in payload.items() if v is not None},
@@ -13716,6 +13739,7 @@ def _iot_ca_certificate_update(physical_id, old_props, new_props, stack_name):
"AWS::IoT::CACertificate cannot change CertificateMode in place: "
"CloudFormation documents it as update-requires-replacement."
)
+ _iot_update_tags(_iot._ca_cert_arn(physical_id), old_props, new_props)
return _iot_ca_certificate_apply(physical_id, new_props)
@@ -13778,7 +13802,7 @@ def _iot_domain_configuration_create(logical_id, props, stack_name):
k: v for k, v in props.items()
if k not in ("DomainConfigurationName", "DomainConfigurationStatus", "Tags")
})
- resp = _iot._create_domain_configuration(name, payload)
+ resp = _iot._create_domain_configuration(name, {**payload, "tags": _iot_tags(props)})
if resp[0] >= 400:
raise ValueError(f"AWS::IoT::DomainConfiguration create failed: {resp[2]!r}")
if props.get("DomainConfigurationStatus") != "ENABLED":
@@ -13795,7 +13819,9 @@ def _iot_domain_configuration_update(physical_id, old_props, new_props, stack_na
})
if payload:
_iot_domain_configuration_set(physical_id, payload, "update")
- return physical_id, _iot_domain_configuration_attrs(physical_id)
+ attrs = _iot_domain_configuration_attrs(physical_id)
+ _iot_update_tags(attrs["Arn"], old_props, new_props)
+ return physical_id, attrs
def _iot_domain_configuration_delete(physical_id, props):
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index ac300616..1a775f1b 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -50,6 +50,8 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:
``UpdateDomainConfiguration``, ``DeleteDomainConfiguration``, including
the ``iot:Data-ATS`` / ``iot:CredentialProvider`` configurations IoT owns
(control plane only: the broker does not serve a configured domain)
+ - Tags: ``TagResource``, ``UntagResource``, ``ListTagsForResource`` on the
+ taggable types above, which also take ``tags`` when created
This is the control plane — pure HTTP/JSON, no MQTT broker
dependency. The data plane (``iot_data.py``) is
@@ -85,7 +87,7 @@ import uuid
import weakref
from datetime import datetime, timezone
from typing import Awaitable, Callable
-from urllib.parse import parse_qs
+from urllib.parse import parse_qsl, parse_qs
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.responses import (
@@ -144,6 +146,8 @@ _jobs: AccountRegionScopedDict = AccountRegionScopedDict() # jobId -> Job dict
# (thingName, jobId) -> JobExecution dict — tuple keys, same pattern as _shadows
_job_executions: AccountRegionScopedDict = AccountRegionScopedDict()
_job_templates: AccountRegionScopedDict = AccountRegionScopedDict() # jobTemplateId -> record
+# Tags of the taggable resources: resource ARN -> {key: value}
+_tags: AccountRegionScopedDict = AccountRegionScopedDict()
# Local CA state — lazily generated on first use, persisted across restarts.
import threading
@@ -273,6 +277,7 @@ def get_state() -> dict:
"jobs": copy.deepcopy(_jobs),
"job_executions": copy.deepcopy(_job_executions),
"job_templates": copy.deepcopy(_job_templates),
+ "tags": copy.deepcopy(_tags),
"ca": {"ca_cert_pem": _ca_cert_pem, "ca_key_pem": _ca_key_pem}
if _ca_cert_pem and _ca_key_pem
else {},
@@ -311,6 +316,15 @@ def _restore_state(data: dict | None) -> None:
_jobs.update(data.get("jobs", {}))
_job_executions.update(data.get("job_executions", {}))
_job_templates.update(data.get("job_templates", {}))
+ _tags.update(data.get("tags", {}))
+ # Older state kept these tags on the records.
+ for store, arn_key in ((_thing_groups, "thingGroupArn"), (_jobs, "jobArn"),
+ (_job_templates, "jobTemplateArn")):
+ for (account, region, _), record in store.all_items():
+ legacy = record.pop("tags", None)
+ if legacy and not _tags.contains_scoped(account, region, record[arn_key]):
+ _tags.set_scoped(account, region, record[arn_key],
+ {t["Key"]: t.get("Value", "") for t in legacy})
ca_data = data.get("ca")
if ca_data:
cert = ca_data.get("ca_cert_pem")
@@ -354,6 +368,7 @@ def reset() -> None:
_jobs.clear()
_job_executions.clear()
_job_templates.clear()
+ _tags.clear()
with _CA_LOCK:
_ca_cert_pem = None
_ca_key_pem = None
@@ -655,7 +670,14 @@ async def _route_request(
if path == "/rules" and method == "GET":
return _list_topic_rules(qp)
if path.startswith("/rules/"):
- return _handle_topic_rule(method, path, body)
+ return _handle_topic_rule(method, path, body, hdr)
+
+ if path == "/tags" and method == "POST":
+ return _tag_resource(_parse_body(body))
+ if path == "/untag" and method == "POST":
+ return _untag_resource(_parse_body(body))
+ if path == "/tags" and method == "GET":
+ return _list_tags_for_resource(qp)
return error_response_json(
"InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400
@@ -979,7 +1001,8 @@ def _create_domain_configuration(name: str, payload: dict) -> tuple:
the configuration is AWS_MANAGED and gets a generated ``-ats`` host; with
one it is CUSTOMER_MANAGED on the caller's ``domainName``."""
err = (_domain_config_name_error(name, _DOMAIN_CONFIG_NAME_RE)
- or _domain_config_model_error(payload))
+ or _domain_config_model_error(payload)
+ or _tags_error(payload.get("tags"), required=False))
if err:
return err
service_type = payload.get("serviceType") or "DATA"
@@ -1058,6 +1081,7 @@ def _create_domain_configuration(name: str, payload: dict) -> tuple:
if payload.get(member):
record[member] = payload[member]
_domain_configurations[name] = record
+ _set_created_tags(record["domainConfigurationArn"], payload.get("tags"))
return json_response({
"domainConfigurationName": name,
"domainConfigurationArn": record["domainConfigurationArn"],
@@ -1204,6 +1228,7 @@ def _delete_domain_configuration(name: str) -> tuple:
"AWS Managed Domain Configuration must be disabled for at least 7 days "
"before it can be deleted")
del _domain_configurations[name]
+ _tags.pop(record["domainConfigurationArn"], None)
return json_response({})
@@ -1471,6 +1496,9 @@ def _thing_type_props_identity(props: dict) -> tuple:
def _create_thing_type(name: str, payload: dict) -> tuple:
+ err = _tags_error(payload.get("tags"), required=False, missing_value=_TAG_WITHOUT_VALUE)
+ if err:
+ return err
props = payload.get("thingTypeProperties") or {}
existing = _thing_types.get(name)
if existing is not None:
@@ -1505,6 +1533,7 @@ def _create_thing_type(name: str, payload: dict) -> tuple:
},
}
_thing_types[name] = record
+ _set_created_tags(record["thingTypeArn"], payload.get("tags"))
_thing_type_event("CREATED", record)
logger.info("IoT Thing Type created: %s", name)
return json_response({
@@ -1554,6 +1583,7 @@ def _delete_thing_type(name: str) -> tuple:
400,
)
del _thing_types[name]
+ _tags.pop(t["thingTypeArn"], None)
_thing_type_event("DELETED", t)
return json_response({})
@@ -1590,10 +1620,6 @@ def _handle_thing_group(method: str, path: str, body: bytes, qp: dict) -> tuple:
)
-def _thing_group_tag_pairs(tags: list | None) -> list:
- return sorted((t.get("Key"), t.get("Value")) for t in tags or [])
-
-
def _create_existing_thing_group(group: dict, payload: dict) -> tuple:
"""CreateThingGroup on a name that exists. AWS answers 200 with the
existing group when the request describes it exactly: description,
@@ -1615,7 +1641,8 @@ def _create_existing_thing_group(group: dict, payload: dict) -> tuple:
or (payload.get("parentGroupName") or None) != stored_parent
):
message = f"Thing Group {group['thingGroupName']} already exists in current account"
- elif _thing_group_tag_pairs(payload.get("tags")) != _thing_group_tag_pairs(group.get("tags")):
+ elif ({t.get("Key"): t.get("Value") for t in payload.get("tags") or []}
+ != (_tags.get(group["thingGroupArn"]) or {})):
message = f"Resource {group['thingGroupArn']} already exists in current account"
else:
return json_response({
@@ -1638,6 +1665,9 @@ def _create_thing_group(name: str, payload: dict) -> tuple:
f"ThingGroup {name!r} already exists",
409,
)
+ err = _tags_error(payload.get("tags"), required=False, missing_value=_TAG_WITHOUT_VALUE)
+ if err:
+ return err
props = payload.get("thingGroupProperties") or {}
attr_payload = props.get("attributePayload") or {}
parent = payload.get("parentGroupName")
@@ -1654,8 +1684,6 @@ def _create_thing_group(name: str, payload: dict) -> tuple:
"version": 1,
"things": [],
"creationDate": _now_epoch(),
- # Kept for a repeated CreateThingGroup to compare; not echoed.
- "tags": list(payload.get("tags") or []),
}
if parent:
# DescribeThingGroup reports the parent under thingGroupMetadata, as
@@ -1665,6 +1693,7 @@ def _create_thing_group(name: str, payload: dict) -> tuple:
"creationDate": record["creationDate"],
}
_thing_groups[name] = record
+ _set_created_tags(record["thingGroupArn"], payload.get("tags"))
_thing_group_event("CREATED", record)
if parent:
_hierarchy_event("ADDED", _thing_groups[parent], record)
@@ -1771,6 +1800,7 @@ def _delete_thing_group(name: str) -> tuple:
if parent:
_hierarchy_event("REMOVED", parent, g)
del _thing_groups[name]
+ _tags.pop(g["thingGroupArn"], None)
return json_response({})
@@ -1920,7 +1950,8 @@ def _create_provisioning_template(payload: dict) -> tuple:
return error_response_json(
"InvalidRequestException", f"{field} is required", 400
)
- err = _validate_provisioning_template_body(payload["templateBody"])
+ err = (_validate_provisioning_template_body(payload["templateBody"])
+ or _tags_error(payload.get("tags"), required=False))
if err:
return err
if name in _provisioning_templates:
@@ -1948,6 +1979,7 @@ def _create_provisioning_template(payload: dict) -> tuple:
if payload.get("preProvisioningHook"):
record["preProvisioningHook"] = payload["preProvisioningHook"]
_provisioning_templates[name] = record
+ _set_created_tags(record["templateArn"], payload.get("tags"))
logger.info("IoT provisioning template created: %s", name)
return json_response({
"templateArn": record["templateArn"],
@@ -2015,7 +2047,7 @@ def _update_provisioning_template(name: str, payload: dict) -> tuple:
def _delete_provisioning_template(name: str) -> tuple:
if _provisioning_templates.get(name) is None:
return _provisioning_template_not_found(name)
- del _provisioning_templates[name]
+ _tags.pop(_provisioning_templates.pop(name)["templateArn"], None)
logger.info("IoT provisioning template deleted: %s", name)
return json_response({})
@@ -2584,7 +2616,7 @@ def _register_ca_certificate(payload: dict, qp: dict) -> tuple:
)
refused = _verification_certificate_error(
ca_pem, payload.get("verificationCertificate"), certificate_mode
- )
+ ) or _tags_error(payload.get("tags"), required=False)
if refused is not None:
return refused
if ca_id in _ca_certificates:
@@ -2604,6 +2636,7 @@ def _register_ca_certificate(payload: dict, qp: dict) -> tuple:
if registration_config is not None:
record["registrationConfig"] = registration_config
_ca_certificates[ca_id] = record
+ _set_created_tags(record["certificateArn"], payload.get("tags"))
return json_response({
"certificateArn": record["certificateArn"],
"certificateId": ca_id,
@@ -2710,6 +2743,7 @@ def _handle_ca_certificate(method: str, path: str, body: bytes, qp: dict) -> tup
406,
)
del _ca_certificates[ca_id]
+ _tags.pop(record["certificateArn"], None)
return json_response({})
return error_response_json(
"InvalidRequestException", f"Unsupported method: {method}", 400
@@ -2841,6 +2875,9 @@ def _create_policy(name: str, payload: dict) -> tuple:
return error_response_json(
"InvalidRequestException", "policyDocument is required", 400
)
+ err = _tags_error(payload.get("tags"), required=False)
+ if err:
+ return err
try:
json.loads(doc)
except (TypeError, json.JSONDecodeError):
@@ -2863,6 +2900,7 @@ def _create_policy(name: str, payload: dict) -> tuple:
"targets": [],
}
_policies[name] = record
+ _set_created_tags(record["policyArn"], payload.get("tags"))
return json_response({
"policyName": name,
"policyArn": record["policyArn"],
@@ -2911,6 +2949,7 @@ def _delete_policy(name: str) -> tuple:
409,
)
del _policies[name]
+ _tags.pop(p["policyArn"], None)
return json_response({})
@@ -4792,12 +4831,13 @@ def put_topic_rule(name: str, payload: dict, *, created_at: float | None = None)
def delete_topic_rule(name: str) -> None:
_topic_rules.pop(name, None)
+ _tags.pop(_topic_rule_arn(name), None)
-def _handle_topic_rule(method: str, path: str, body: bytes) -> tuple:
+def _handle_topic_rule(method: str, path: str, body: bytes, headers: dict) -> tuple:
name = path[len("/rules/"):]
if method == "POST":
- return _create_topic_rule(name, _parse_body(body))
+ return _create_topic_rule(name, _parse_body(body), headers.get("x-amz-tagging"))
if method == "GET":
return _get_topic_rule(name)
if method == "PATCH":
@@ -4809,7 +4849,8 @@ def _handle_topic_rule(method: str, path: str, body: bytes) -> tuple:
)
-def _create_topic_rule(name: str, payload: dict) -> tuple:
+def _create_topic_rule(name: str, payload: dict, tagging: str | None = None) -> tuple:
+ """CreateTopicRule; its tags arrive as the ``x-amz-tagging`` header, ``k1=v1&k2=v2``."""
if not _RULE_NAME_RE.match(name or ""):
return error_response_json(
"InvalidRequestException",
@@ -4822,12 +4863,24 @@ def _create_topic_rule(name: str, payload: dict) -> tuple:
)
if not payload.get("sql"):
return error_response_json("SqlParseException", "sql is required", 400)
+ try:
+ pairs = parse_qsl(tagging or "", keep_blank_values=True, strict_parsing=True)
+ except ValueError:
+ return error_response_json(
+ "InvalidRequestException",
+ "Invalid tag parameters, please make sure the tags are in correct format with tagKeys "
+ "not exceeding 128 characters and tagValues not exceeding 256 characters", 400)
+ tags = [{"Key": k, "Value": v} for k, v in pairs]
+ err = _tags_error(tags, required=False)
+ if err:
+ return err
try:
put_topic_rule(name, payload)
except RuleSqlError as exc:
return error_response_json("SqlParseException", str(exc), 400)
except RuleRoleError as exc:
return error_response_json("InvalidRequestException", str(exc), 400)
+ _set_created_tags(_topic_rule_arn(name), tags)
return json_response({})
@@ -4851,7 +4904,7 @@ def _get_topic_rule(name: str) -> tuple:
def _delete_topic_rule(name: str) -> tuple:
- _topic_rules.pop(name, None)
+ delete_topic_rule(name)
return json_response({})
@@ -4868,6 +4921,178 @@ def _list_topic_rules(qp: dict) -> tuple:
return json_response({"rules": rules})
+# ---------------------------------------------------------------------------
+# Tags (TagResource / UntagResource / ListTagsForResource)
+# ---------------------------------------------------------------------------
+
+_TAG_KEY_PATTERN = r"^([\p{L}\p{Z}\p{N}_.:/=+\-@]*)$"
+_TAGS_PER_RESOURCE = 50
+_TOO_MANY_TAGS = "Too many tags provided in the request. Please check the input."
+_INVALID_TAG_REQUEST = "Invalid request exception. Please check the input."
+# What CreateThingType/CreateThingGroup and CreateJob/CreateJobTemplate answer for a tag without a value.
+_TAG_WITHOUT_VALUE = "All tags in request should have keys and values."
+_INVALID_JOB_TAG = "Invalid tag parameter exception. Please check the input."
+
+# ARN resource type -> (the store keyed by what follows the type, the message of
+# TagResource and UntagResource for a resource that does not exist)
+_TAGGABLE_RESOURCES = {
+ "thinggroup": (_thing_groups, "Thing Group {name} does not exist."),
+ "thingtype": (_thing_types, "Thing Type {name} does not exist."),
+ "policy": (_policies, "This resource is not found"),
+ "rule": (_topic_rules, "Rule {name} not found. accountId: {account}, resourceArn: {arn}"),
+ "job": (_jobs, "Job {name} cannot be found."),
+ "jobtemplate": (_job_templates, "Job Template {name} cannot be found."),
+ "cacert": (_ca_certificates, "CA Certificate {name} not found"),
+ "provisioningtemplate": (_provisioning_templates, "Unable to get template id, template not found"),
+ "domainconfiguration": (_domain_configurations, None),
+}
+# Resource types IoT has but does not tag.
+_UNTAGGABLE_RESOURCE_TYPES = ("thing", "cert")
+
+
+def _tag_request_error(message: str) -> tuple:
+ return error_response_json("InvalidRequestException", message, 400)
+
+
+def _tag_key_error(key) -> str | None:
+ """The model constraint a tag key fails, or None."""
+ if not isinstance(key, str):
+ return "Member must not be null"
+ if not key:
+ return "Member must have length greater than or equal to 1"
+ if len(key) > 128:
+ return "Member must have length less than or equal to 128"
+ if not all(unicodedata.category(c)[0] in "LNZ" or c in "_.:/=+-@" for c in key):
+ return f"Member must satisfy regular expression pattern: {_TAG_KEY_PATTERN}"
+ return None
+
+
+def _tags_error(tags, required: bool = True,
+ missing_value: str = _INVALID_TAG_REQUEST) -> tuple | None:
+ """The refusal of the tag list of a TagResource (or, not required, a Create) call."""
+ if not tags:
+ if not required:
+ return None
+ if tags is None:
+ return _job_template_validation_error(None, "tags", "Member must not be null")
+ return _tag_request_error("The validated collection is empty")
+ if not isinstance(tags, list) or not all(isinstance(t, dict) for t in tags):
+ return _tag_request_error(_INVALID_TAG_REQUEST)
+ clauses = []
+ for index, tag in enumerate(tags, 1):
+ constraint = _tag_key_error(tag.get("Key"))
+ if constraint:
+ clauses.append(_job_validation_clause(
+ tag.get("Key"), f"tags.{index}.member.key", constraint))
+ value = tag.get("Value")
+ if isinstance(value, str) and len(value) > 256:
+ clauses.append(_job_validation_clause(
+ value, f"tags.{index}.member.value",
+ "Member must have length less than or equal to 256"))
+ if clauses:
+ return _job_validation_error(clauses)
+ for tag in tags:
+ if not isinstance(tag.get("Value"), str):
+ return _tag_request_error(missing_value)
+ if tag["Key"].lower().startswith("aws:"):
+ return _tag_request_error(f'Tags cannot begin with "aws:", offending tag: {tag["Key"]}')
+ if len({tag["Key"] for tag in tags}) > _TAGS_PER_RESOURCE:
+ return _tag_request_error(_TOO_MANY_TAGS)
+ return None
+
+
+def _set_created_tags(arn: str, tags: list | None) -> None:
+ """Store the tags a Create call carried; none drops what a deleted namesake left."""
+ if tags:
+ _tags[arn] = {tag["Key"]: tag["Value"] for tag in tags}
+ else:
+ _tags.pop(arn, None)
+
+
+def _tag_target_error(arn, must_exist: bool) -> tuple | None:
+ """The refusal of a tagging call on ``arn``, or None; ListTagsForResource passes must_exist=False."""
+ try:
+ spec = parse_arn(arn)
+ except ArnParseError:
+ spec = None
+ rtype, _, rest = spec.resource.partition("/") if spec else ("", "", "")
+ if not rest or spec.service != "iot" or (
+ rtype not in _TAGGABLE_RESOURCES and rtype not in _UNTAGGABLE_RESOURCE_TYPES):
+ return _tag_request_error("Invalid arn in request")
+ if spec.account_id != get_account_id():
+ return _tag_request_error("ResourceArn doesn't belong in requester's account")
+ if rtype in _UNTAGGABLE_RESOURCE_TYPES:
+ return _tag_request_error(f"Invalid resource type in ARN: {rtype}")
+ if not must_exist:
+ return None
+ if spec.region != get_region():
+ return _tag_request_error(_INVALID_TAG_REQUEST)
+ store, message = _TAGGABLE_RESOURCES[rtype]
+ # A domain configuration ARN ends in a generated id after the name.
+ name = rest.partition("/")[0] if rtype == "domainconfiguration" else rest
+ record = store.get(name)
+ if record is not None and record.get("domainConfigurationArn", arn) == arn:
+ return None
+ if message is None:
+ return _domain_config_not_found(name)
+ return error_response_json(
+ "ResourceNotFoundException",
+ message.format(name=name, account=spec.account_id, arn=arn), 404)
+
+
+def _tag_resource(payload: dict) -> tuple:
+ """``POST /tags``: add or overwrite tags; the last of a repeated key wins."""
+ arn, tags = payload.get("resourceArn"), payload.get("tags")
+ err = _tags_error(tags) or _tag_target_error(arn, must_exist=True)
+ if err:
+ return err
+ merged = {**(_tags.get(arn) or {}), **{tag["Key"]: tag["Value"] for tag in tags}}
+ if len(merged) > _TAGS_PER_RESOURCE:
+ return _tag_request_error(_TOO_MANY_TAGS)
+ _tags[arn] = merged
+ return json_response({})
+
+
+def _untag_resource(payload: dict) -> tuple:
+ """``POST /untag``: a key the resource does not carry is no error."""
+ keys = payload.get("tagKeys")
+ if keys is None:
+ return _job_template_validation_error(None, "tagKeys", "Member must not be null")
+ if not keys:
+ return _tag_request_error("The validated collection is empty")
+ if not isinstance(keys, list):
+ return _tag_request_error(_INVALID_TAG_REQUEST)
+ if any(_tag_key_error(key) for key in keys):
+ return _job_template_validation_error(
+ "[" + ", ".join(map(str, keys)) + "]", "tagKeys",
+ "Member must satisfy constraint: [Member must have length less than or equal "
+ "to 128, Member must have length greater than or equal to 1, Member must "
+ f"satisfy regular expression pattern: {_TAG_KEY_PATTERN}]")
+ reserved = next((key for key in keys if key.lower().startswith("aws:")), None)
+ if reserved is not None:
+ return _tag_request_error(f'Tags cannot begin with "aws:", offending tag: {reserved}')
+ arn = payload.get("resourceArn")
+ err = _tag_target_error(arn, must_exist=True)
+ if err:
+ return err
+ stored = _tags.get(arn) or {}
+ for key in keys:
+ stored.pop(key, None)
+ return json_response({})
+
+
+def _list_tags_for_resource(qp: dict) -> tuple:
+ """``GET /tags``: every tag in one page, whatever nextToken says."""
+ arn = qp.get("resourceArn")
+ err = _tag_target_error(arn, must_exist=False)
+ if err:
+ return err
+ return json_response({
+ "nextToken": None,
+ "tags": [{"Key": k, "Value": v} for k, v in (_tags.get(arn) or {}).items()],
+ })
+
+
# ---------------------------------------------------------------------------
# IoT Jobs (control plane; execution state shared with iot_jobs_data.py)
# ---------------------------------------------------------------------------
@@ -5376,6 +5601,9 @@ async def _create_job(job_id: str, payload: dict) -> tuple:
payload, err = _job_payload_from_template(payload)
if err:
return err
+ err = _tags_error(payload.get("tags"), required=False, missing_value=_INVALID_JOB_TAG)
+ if err:
+ return err
# Absent means SNAPSHOT (the AWS default); present means it has to be one
# of the two modeled values — including the empty string, which would
# otherwise default its way to a SNAPSHOT job the caller never asked for.
@@ -5485,9 +5713,9 @@ async def _create_job(job_id: str, payload: dict) -> tuple:
"documentParameters": payload.get("documentParameters"),
"schedulingConfig": payload.get("schedulingConfig"),
"destinationPackageVersions": payload.get("destinationPackageVersions"),
- "tags": payload.get("tags"),
"snapshotted": False,
}
+ _set_created_tags(_job_arn(job_id), payload.get("tags"))
_jobs_materialize_executions(job_id)
# New QUEUED executions joined each target's pending set — notify, as AWS
# does (notify-next only reaches the things whose queue front changed).
@@ -5812,6 +6040,7 @@ async def _delete_job(job_id: str, qp: dict) -> tuple:
job["lastUpdatedAt"] = _jobs_now_ms()
_job_event(job, "deletion_in_progress")
del _jobs[job_id]
+ _tags.pop(job["jobArn"], None)
for key in [k for k in _job_executions.keys() if k[1] == job_id]:
_job_execution_event(_job_executions[key], "DELETED")
del _job_executions[key]
@@ -5965,6 +6194,8 @@ def _create_job_template(template_id: str, payload: dict) -> tuple:
"Job document and job document source cannot be specified at the same time.",
400,
)
+ if err := _tags_error(payload.get("tags"), required=False, missing_value=_INVALID_JOB_TAG):
+ return err
if not document and not source and not payload.get("jobArn"):
return error_response_json(
"InvalidRequestException",
@@ -6000,12 +6231,13 @@ def _create_job_template(template_id: str, payload: dict) -> tuple:
# Same stand-in as CreateJob's: the S3 object is not fetched.
record["document"] = json.dumps({"documentSource": source})
for member in _JOB_TEMPLATE_CONFIG_MEMBERS + (
- "maintenanceWindows", "destinationPackageVersions", "tags",
+ "maintenanceWindows", "destinationPackageVersions",
):
if payload.get(member) is not None:
record[member] = copy.deepcopy(payload[member])
_job_config_floats(record)
_job_templates[template_id] = record
+ _set_created_tags(record["jobTemplateArn"], payload.get("tags"))
return json_response({
"jobTemplateArn": record["jobTemplateArn"], "jobTemplateId": template_id,
})
@@ -6096,7 +6328,7 @@ def _list_job_templates(qp: dict) -> tuple:
def _delete_job_template(template_id: str) -> tuple:
if _job_templates.get(template_id) is None:
return _job_template_not_found(template_id)
- del _job_templates[template_id]
+ _tags.pop(_job_templates.pop(template_id)["jobTemplateArn"], None)
# AWS answers 200 with an empty body.
return 200, {"Content-Type": "application/x-amz-json-1.0"}, b""
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index d6284796..5093d8ce 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -26883,8 +26883,8 @@ def test_cfn_apigateway_deployment_update_in_place_and_replacement(cfn, apigw_v1
def test_cfn_iot_thing_group_missing_parent_fails_and_unmodelled_properties_are_accepted(cfn, iot_client):
"""A parent that does not exist fails the stack with the service's own
- ResourceNotFoundException; QueryString (dynamic groups) and Tags, which
- the service does not model, are accepted without effect."""
+ ResourceNotFoundException; QueryString (dynamic groups), which the service
+ does not model, is accepted without effect."""
uid = _uuid_mod.uuid4().hex[:8]
stack_name = f"cfn-thing-group-edge-{uid}"
cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps({
@@ -26919,6 +26919,48 @@ def test_cfn_iot_thing_group_missing_parent_fails_and_unmodelled_properties_are_
_delete_cfn_test_stack(cfn, stack_name)
+def test_cfn_iot_tags_follow_the_template(cfn, iot_client):
+ """The Tags of AWS::IoT::ThingGroup, Policy and TopicRule reach
+ ListTagsForResource; an update applies changed and dropped tags in place,
+ and deleting the stack drops them."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-iot-tags-{uid}"
+ group, policy, rule = f"cfn-tags-group-{uid}", f"cfn-tags-policy-{uid}", f"cfn_tags_rule_{uid}"
+
+ def template(tags):
+ extra = {} if tags is None else {"Tags": [{"Key": k, "Value": v} for k, v in tags.items()]}
+ return json.dumps({"Resources": {
+ "Group": {"Type": "AWS::IoT::ThingGroup", "Properties": {"ThingGroupName": group, **extra}},
+ "Policy": {"Type": "AWS::IoT::Policy", "Properties": {
+ "PolicyName": policy, **extra, "PolicyDocument": {"Version": "2012-10-17", "Statement": [
+ {"Effect": "Deny", "Action": "iot:Publish", "Resource": "*"}]}}},
+ "Rule": {"Type": "AWS::IoT::TopicRule", "Properties": {
+ "RuleName": rule, **extra,
+ "TopicRulePayload": {"Sql": "SELECT * FROM 't'", "Actions": [], "RuleDisabled": True}}},
+ }})
+
+ def listed():
+ return [{t["Key"]: t["Value"] for t in iot_client.list_tags_for_resource(resourceArn=arn)["tags"]}
+ for arn in arns]
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template({"own": "1"}))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arns = [iot_client.describe_thing_group(thingGroupName=group)["thingGroupArn"],
+ iot_client.get_policy(policyName=policy)["policyArn"],
+ iot_client.get_topic_rule(ruleName=rule)["ruleArn"]]
+ assert listed() == [{"own": "1"}] * 3
+ for tags in ({"own": "2", "new": "x"}, None):
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(tags))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert listed() == [tags or {}] * 3
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ assert listed() == [{}] * 3
+
+
def test_cfn_kms_alias_target_change_in_place_and_rename_replaces(cfn, kms_client):
"""A TargetKeyId change re-points the alias under its name (Ref keeps its
value), an AliasName change replaces the alias — the new name exists, the
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 16e70e1f..ec5e2b4a 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -796,6 +796,20 @@ def test_iot_create_thing_group_repeat_compares_tags(iot_client):
iot_client.delete_thing_group(thingGroupName=tagged)
+def test_iot_create_thing_group_repeat_compares_current_tags(iot_client):
+ name = _unique("group")
+ created = [{"Key": "team", "Value": "a"}]
+ arn = iot_client.create_thing_group(thingGroupName=name, tags=created)["thingGroupArn"]
+ iot_client.tag_resource(resourceArn=arn, tags=[{"Key": "added", "Value": "1"}])
+ for tags in (created, None):
+ kwargs = {} if tags is None else {"tags": tags}
+ assert _iot_error(iot_client.create_thing_group, thingGroupName=name, **kwargs) == (
+ 409, f"Resource {arn} already exists in current account with different properties")
+ current = [{"Key": "added", "Value": "1"}, {"Key": "team", "Value": "a"}]
+ for tags in (current, current[::-1]):
+ assert iot_client.create_thing_group(thingGroupName=name, tags=tags)["thingGroupArn"] == arn
+
+
def test_iot_delete_thing_group_with_child_groups_is_refused(iot_client):
parent, child = _unique("parent"), _unique("child")
iot_client.create_thing_group(thingGroupName=parent)
@@ -861,6 +875,309 @@ def test_iot_list_thing_groups_for_thing(iot_client):
iot_client.delete_thing_group(thingGroupName=g2)
+# ---------------------------------------------------------------------------
+# Tags (TagResource / UntagResource / ListTagsForResource)
+# ---------------------------------------------------------------------------
+
+
+def _iot_tags(iot_client, arn):
+ return {t["Key"]: t["Value"] for t in iot_client.list_tags_for_resource(resourceArn=arn)["tags"]}
+
+
+def _iot_error(call, **kwargs):
+ with pytest.raises(ClientError) as ei:
+ call(**kwargs)
+ response = ei.value.response
+ return response["ResponseMetadata"]["HTTPStatusCode"], response["Error"]["Message"]
+
+
+def test_iot_create_time_tags_are_listed(iot_client):
+ tags = [{"Key": "team", "Value": "a"}, {"Key": "env", "Value": "dev"}]
+ thing_arn = iot_client.create_thing(thingName=_unique("thing"))["thingArn"]
+ rule = _unique("rule").replace("-", "_")
+ iot_client.create_topic_rule(
+ ruleName=rule, topicRulePayload={"sql": "SELECT * FROM 't'", "actions": []},
+ tags="team=a&env=dev")
+ template_arn = iot_client.create_job_template(
+ jobTemplateId=_unique("jt"), description="d", document="{}", tags=tags)["jobTemplateArn"]
+ arns = [
+ iot_client.create_thing_type(thingTypeName=_unique("type"), tags=tags)["thingTypeArn"],
+ iot_client.create_thing_group(thingGroupName=_unique("group"), tags=tags)["thingGroupArn"],
+ iot_client.create_policy(policyName=_unique("policy"), policyDocument="{}", tags=tags)["policyArn"],
+ iot_client.get_topic_rule(ruleName=rule)["ruleArn"],
+ template_arn,
+ iot_client.create_job(jobId=_unique("job"), targets=[thing_arn], document="{}", tags=tags)["jobArn"],
+ iot_client.register_ca_certificate(
+ caCertificate=iot_test_ca("unused")[0], certificateMode="SNI_ONLY", tags=tags)["certificateArn"],
+ iot_client.create_provisioning_template(
+ templateName=_unique("prov"), templateBody=_provisioning_template_body(),
+ provisioningRoleArn="arn:aws:iam::000000000000:role/p", tags=tags)["templateArn"],
+ iot_client.create_domain_configuration(
+ domainConfigurationName=_unique("dc-tags"), tags=tags)["domainConfigurationArn"],
+ ]
+ for arn in arns:
+ assert _iot_tags(iot_client, arn) == {"team": "a", "env": "dev"}, arn
+ # A job created from a tagged template does not take the template's tags.
+ job_arn = iot_client.create_job(
+ jobId=_unique("job"), targets=[thing_arn], jobTemplateArn=template_arn)["jobArn"]
+ assert _iot_tags(iot_client, job_arn) == {}
+ # The generated id after a domain configuration's name is part of its ARN.
+ assert _iot_error(iot_client.tag_resource, resourceArn=arns[-1].rsplit("/", 1)[0] + "/other",
+ tags=tags)[0] == 404
+
+
+def test_iot_create_calls_refuse_bad_tags(iot_client):
+ from conftest import make_client
+
+ raw = make_client("iot", {"parameter_validation": False})
+ thing_arn = iot_client.create_thing(thingName=_unique("thing"))["thingArn"]
+ type_name, policy_name = _unique("type"), _unique("policy")
+ generic = "Invalid request exception. Please check the input."
+ job_tag = "Invalid tag parameter exception. Please check the input."
+ for create, missing_value in (
+ (lambda tags: raw.create_thing_type(thingTypeName=type_name, tags=tags),
+ "All tags in request should have keys and values."),
+ (lambda tags: raw.create_thing_group(thingGroupName=_unique("group"), tags=tags),
+ "All tags in request should have keys and values."),
+ (lambda tags: raw.create_policy(policyName=policy_name, policyDocument="{}", tags=tags), generic),
+ (lambda tags: raw.create_job_template(
+ jobTemplateId=_unique("jt"), description="d", document="{}", tags=tags), job_tag),
+ (lambda tags: raw.create_job(
+ jobId=_unique("job"), targets=[thing_arn], document="{}", tags=tags), job_tag),
+ (lambda tags: raw.create_provisioning_template(
+ templateName=_unique("prov"), templateBody=_provisioning_template_body(),
+ provisioningRoleArn="arn:aws:iam::000000000000:role/p", tags=tags), generic),
+ (lambda tags: raw.register_ca_certificate(
+ caCertificate=iot_test_ca("unused")[0], certificateMode="SNI_ONLY", tags=tags), generic),
+ ):
+ assert _iot_error(create, tags=[{"Key": "aws:x", "Value": "v"}]) == (
+ 400, 'Tags cannot begin with "aws:", offending tag: aws:x')
+ assert _iot_error(create, tags=[{"Key": "k"}]) == (400, missing_value)
+ assert _iot_error(iot_client.describe_thing_type, thingTypeName=type_name)[0] == 404
+ assert _iot_error(iot_client.get_policy, policyName=policy_name)[0] == 404
+
+ rule = _unique("rule").replace("-", "_")
+ for tagging, message in (
+ ("aws:x=v", 'Tags cannot begin with "aws:", offending tag: aws:x'),
+ ("k", "Invalid tag parameters, please make sure the tags are in correct format with tagKeys "
+ "not exceeding 128 characters and tagValues not exceeding 256 characters"),
+ ):
+ assert _iot_error(iot_client.create_topic_rule, ruleName=rule, tags=tagging,
+ topicRulePayload={"sql": "SELECT * FROM 't'", "actions": []}) == (400, message)
+ assert rule not in [r["ruleName"] for r in iot_client.list_topic_rules()["rules"]]
+
+
+def test_iot_tag_untag_and_delete(iot_client):
+ raw = iot_client.list_tags_for_resource
+ name = _unique("group")
+ arn = iot_client.create_thing_group(thingGroupName=name)["thingGroupArn"]
+ listed = raw(resourceArn=arn)
+ assert listed["tags"] == [] and "nextToken" not in listed
+ out = iot_client.tag_resource(resourceArn=arn, tags=[
+ {"Key": "a", "Value": "1"}, {"Key": "b", "Value": ""},
+ {"Key": "dup", "Value": "1"}, {"Key": "dup", "Value": "2"}])
+ assert out["ResponseMetadata"]["HTTPStatusCode"] == 200
+ iot_client.tag_resource(resourceArn=arn, tags=[{"Key": "a", "Value": "new"}])
+ assert _iot_tags(iot_client, arn) == {"a": "new", "b": "", "dup": "2"}
+ iot_client.untag_resource(resourceArn=arn, tagKeys=["b", "missing"])
+ assert _iot_tags(iot_client, arn) == {"a": "new", "dup": "2"}
+
+ # Deleting a resource drops its tags; a namesake starts without them.
+ rule, payload = name.replace("-", "_"), {"sql": "SELECT * FROM 't'", "actions": []}
+
+ def create():
+ iot_client.create_thing_group(thingGroupName=name)
+ iot_client.create_policy(policyName=name, policyDocument="{}")
+ iot_client.create_topic_rule(ruleName=rule, topicRulePayload=payload)
+
+ def delete():
+ iot_client.delete_thing_group(thingGroupName=name)
+ iot_client.delete_policy(policyName=name)
+ iot_client.delete_topic_rule(ruleName=rule)
+
+ iot_client.create_policy(policyName=name, policyDocument="{}")
+ iot_client.create_topic_rule(ruleName=rule, topicRulePayload=payload)
+ resources = (arn, arn.replace(f"thinggroup/{name}", f"policy/{name}"),
+ arn.replace(f"thinggroup/{name}", f"rule/{rule}"))
+ for resource in resources[1:]:
+ iot_client.tag_resource(resourceArn=resource, tags=[{"Key": "k", "Value": "v"}])
+ delete()
+ for resource in resources:
+ assert _iot_tags(iot_client, resource) == {}
+ assert _iot_error(iot_client.tag_resource, resourceArn=resource,
+ tags=[{"Key": "k", "Value": "v"}])[0] == 404
+ create()
+ for resource in resources:
+ assert _iot_tags(iot_client, resource) == {}
+ delete()
+
+
+def test_iot_tagging_refuses_unknown_and_foreign_arns(iot_client):
+ arn = iot_client.create_thing_group(thingGroupName=_unique("group"))["thingGroupArn"]
+ head, account = arn.rsplit(":", 1)[0], arn.split(":")[4]
+ tags, missing = [{"Key": "k", "Value": "v"}], _unique("missing").replace("-", "_")
+ for resource, message in (
+ (f"thinggroup/{missing}", f"Thing Group {missing} does not exist."),
+ (f"thingtype/{missing}", f"Thing Type {missing} does not exist."),
+ (f"policy/{missing}", "This resource is not found"),
+ (f"rule/{missing}", f"Rule {missing} not found. accountId: {account}, "
+ f"resourceArn: {head}:rule/{missing}"),
+ (f"job/{missing}", f"Job {missing} cannot be found."),
+ (f"jobtemplate/{missing}", f"Job Template {missing} cannot be found."),
+ ("cacert/" + "0" * 64, f"CA Certificate {'0' * 64} not found"),
+ (f"provisioningtemplate/{missing}", "Unable to get template id, template not found"),
+ ):
+ target = f"{head}:{resource}"
+ assert _iot_error(iot_client.tag_resource, resourceArn=target, tags=tags) == (404, message)
+ assert _iot_error(iot_client.untag_resource, resourceArn=target, tagKeys=["k"]) == (404, message)
+ assert iot_client.list_tags_for_resource(resourceArn=target)["tags"] == []
+
+ other_region = arn.replace(":us-east-1:", ":eu-west-1:")
+ for call, kwargs in ((iot_client.tag_resource, {"tags": tags}),
+ (iot_client.untag_resource, {"tagKeys": ["k"]})):
+ assert _iot_error(call, resourceArn=other_region, **kwargs) == (
+ 400, "Invalid request exception. Please check the input.")
+ assert iot_client.list_tags_for_resource(resourceArn=other_region)["tags"] == []
+
+ for target, message in (
+ (f"{head}:thing/{missing}", "Invalid resource type in ARN: thing"),
+ (f"{head}:cert/{'0' * 64}", "Invalid resource type in ARN: cert"),
+ (f"{head}:widget/{missing}", "Invalid arn in request"),
+ (f"{head}:", "Invalid arn in request"),
+ ("not-an-arn", "Invalid arn in request"),
+ (f"arn:aws:sqs:us-east-1:{account}:{missing}", "Invalid arn in request"),
+ (arn.replace(f":{account}:", ":123456789012:"), "ResourceArn doesn't belong in requester's account"),
+ ):
+ assert _iot_error(iot_client.tag_resource, resourceArn=target, tags=tags) == (400, message)
+ assert _iot_error(iot_client.untag_resource, resourceArn=target, tagKeys=["k"]) == (400, message)
+ assert _iot_error(iot_client.list_tags_for_resource, resourceArn=target) == (400, message)
+
+
+def test_iot_tag_limits_and_validation(iot_client):
+ from conftest import make_client
+
+ raw = make_client("iot", {"parameter_validation": False})
+ arn = iot_client.create_thing_group(thingGroupName=_unique("group"))["thingGroupArn"]
+ too_many = "Too many tags provided in the request. Please check the input."
+ fifty = [{"Key": f"k{i:02d}", "Value": "v"} for i in range(50)]
+ assert _iot_error(raw.tag_resource, resourceArn=arn, tags=fifty + [{"Key": "k50", "Value": "v"}]) == (
+ 400, too_many)
+ raw.tag_resource(resourceArn=arn, tags=fifty)
+ assert _iot_error(raw.tag_resource, resourceArn=arn, tags=[{"Key": "k50", "Value": "v"}]) == (
+ 400, too_many)
+ raw.tag_resource(resourceArn=arn, tags=[{"Key": "k00", "Value": "new"}])
+ assert len(_iot_tags(iot_client, arn)) == 50
+ raw.untag_resource(resourceArn=arn, tagKeys=[t["Key"] for t in fifty])
+
+ pattern = r"^([\p{L}\p{Z}\p{N}_.:/=+\-@]*)$"
+ for tags, message in (
+ ([{"Key": "b" * 129, "Value": "v"}], f"1 validation error detected: Value '{'b' * 129}' at "
+ "'tags.1.member.key' failed to satisfy constraint: Member must have length less than or equal to 128"),
+ ([{"Key": "v", "Value": "x" * 257}], f"1 validation error detected: Value '{'x' * 257}' at "
+ "'tags.1.member.value' failed to satisfy constraint: Member must have length less than or equal to 256"),
+ ([{"Key": "", "Value": "v"}], "1 validation error detected: Value '' at 'tags.1.member.key' failed "
+ "to satisfy constraint: Member must have length greater than or equal to 1"),
+ ([{"Key": "a#b", "Value": "v"}], "1 validation error detected: Value 'a#b' at 'tags.1.member.key' "
+ f"failed to satisfy constraint: Member must satisfy regular expression pattern: {pattern}"),
+ ([{"Key": "AWS:x", "Value": "v"}], 'Tags cannot begin with "aws:", offending tag: AWS:x'),
+ ([{"Key": "novalue"}], "Invalid request exception. Please check the input."),
+ ([], "The validated collection is empty"),
+ (None, "1 validation error detected: Value null at 'tags' failed to satisfy constraint: "
+ "Member must not be null"),
+ ):
+ kwargs = {} if tags is None else {"tags": tags}
+ assert _iot_error(raw.tag_resource, resourceArn=arn, **kwargs) == (400, message)
+ raw.tag_resource(resourceArn=arn, tags=[
+ {"Key": "a" * 128, "Value": "x" * 256}, {"Key": "a b+-=._:/@", "Value": "aws:x"},
+ {"Key": "awsx", "Value": ""}])
+ assert len(_iot_tags(iot_client, arn)) == 3
+
+ for keys, message in (
+ (["aws:x"], 'Tags cannot begin with "aws:", offending tag: aws:x'),
+ ([], "The validated collection is empty"),
+ (None, "1 validation error detected: Value null at 'tagKeys' failed to satisfy constraint: "
+ "Member must not be null"),
+ (["b" * 129], f"1 validation error detected: Value '[{'b' * 129}]' at 'tagKeys' failed to "
+ "satisfy constraint: Member must satisfy constraint: [Member must have length less than or "
+ "equal to 128, Member must have length greater than or equal to 1, Member must satisfy "
+ f"regular expression pattern: {pattern}]"),
+ ):
+ kwargs = {} if keys is None else {"tagKeys": keys}
+ assert _iot_error(raw.untag_resource, resourceArn=arn, **kwargs) == (400, message)
+
+ # A Create call refuses the same tags, and creates nothing.
+ for tags, message in (
+ ([{"Key": "aws:x", "Value": "v"}], 'Tags cannot begin with "aws:", offending tag: aws:x'),
+ ([{"Key": f"k{i:02d}", "Value": "v"} for i in range(51)], too_many),
+ ):
+ name = _unique("group")
+ assert _iot_error(raw.create_thing_group, thingGroupName=name, tags=tags) == (400, message)
+ assert _iot_error(iot_client.describe_thing_group, thingGroupName=name)[0] == 404
+
+
+def test_iot_tags_are_persisted_and_reset():
+ import asyncio
+
+ from ministack.core.responses import set_request_account_id, set_request_region
+ from ministack.services import iot as iot_module
+
+ name = _unique("group")
+ arn = f"arn:aws:iot:eu-west-1:123456789012:thinggroup/{name}"
+
+ async def _tags():
+ set_request_account_id("123456789012")
+ set_request_region("eu-west-1")
+ _status, _headers, body = await iot_module.handle_request(
+ "GET", "/tags", {}, b"", {"resourceArn": arn})
+ return json.loads(body)["tags"]
+
+ async def _run():
+ set_request_account_id("123456789012")
+ set_request_region("eu-west-1")
+ body = json.dumps({"tags": [{"Key": "k", "Value": "v"}]}).encode()
+ status, _headers, _body = await iot_module.handle_request(
+ "POST", f"/thing-groups/{name}", {}, body, {})
+ assert status == 200
+ assert await _tags() == [{"Key": "k", "Value": "v"}]
+ saved = iot_module.get_state()
+ iot_module.reset()
+ assert await _tags() == []
+ iot_module.load_persisted_state(saved)
+ assert await _tags() == [{"Key": "k", "Value": "v"}]
+
+ asyncio.run(_run())
+
+
+def test_iot_tags_on_records_of_older_state_move_to_the_store():
+ import asyncio
+
+ from ministack.core.responses import set_request_account_id, set_request_region
+ from ministack.services import iot as iot_module
+
+ name, tags = _unique("group"), [{"Key": "k", "Value": "v"}]
+ arn = f"arn:aws:iot:eu-west-1:123456789012:thinggroup/{name}"
+
+ async def _call(method, path, body=b"", qp=None):
+ set_request_account_id("123456789012")
+ set_request_region("eu-west-1")
+ return await iot_module.handle_request(method, path, {}, body, qp or {})
+
+ async def _run():
+ body = json.dumps({"tags": tags}).encode()
+ assert (await _call("POST", f"/thing-groups/{name}", body))[0] == 200
+ saved = iot_module.get_state()
+ # What older versions saved: the tags on the record and no tag store.
+ del saved["tags"]
+ saved["thing_groups"].get_scoped("123456789012", "eu-west-1", name)["tags"] = tags
+ iot_module.reset()
+ iot_module.load_persisted_state(saved)
+ _status, _headers, listed = await _call("GET", "/tags", qp={"resourceArn": arn})
+ assert json.loads(listed)["tags"] == tags
+ assert (await _call("POST", f"/thing-groups/{name}", body))[0] == 200
+
+ asyncio.run(_run())
+
+
# ---------------------------------------------------------------------------
# Certificates (issued via the Local CA)
# ---------------------------------------------------------------------------