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
feat(iot): evaluate MQTT connect, publish, subscribe and receive policies under AUTH=true (#2147)
iot-rocket280965123373
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9c889653..f1e91407 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added++- **IoT — MQTT publish, subscribe and receive evaluate IoT policies under `AUTH=true`** — after the CONNECT a certificate session could publish, subscribe and receive on any topic; it now needs `iot:Publish` on the topic (and `iot:RetainPublish` for a retained message or will), `iot:Subscribe` per topic filter and `iot:Receive` per delivered message. A refused PUBLISH or SUBSCRIBE closes an MQTT 3.1.1 connection (disconnect reason `CLIENT_ERROR`), MQTT 5 answers PUBACK 0x87, DISCONNECT 0x87 at QoS 0 (`AUTH_ERROR`) or 0x87 for the refused filter, which the `subscribed` event leaves out (no event when none is granted), a refused will refuses the CONNECT, and a message the subscriber may not receive is dropped. Contributed by @iot-rocket.+- **IoT — MQTT connections evaluate `iot:Connect` under `AUTH=true`** — a device certificate on the mTLS listener connected under any client id, with or without a policy; with `AUTH=true` the CONNECT now needs an attached policy that allows `iot:Connect` on `client/<client id>` and none that denies it, with `${iot:ClientId}`, `${iot:Connection.Thing.ThingName}`, `iot:Connection.Thing.IsAttached` and `${iot:Certificate.Subject.CommonName}` resolved. A refusal closes an MQTT 3.1.1 connection without a CONNACK, answers MQTT 5 with CONNACK 0x87 and publishes `$aws/events/presence/connect_failed/{clientId}`. Contributed by @iot-rocket.### Fixed- **IoT — republish inside the rule's own topic filter** — `CreateTopicRule` and `ReplaceTopicRule` accepted a `republish` action whose topic the rule's `FROM` filter matches, so the rule fed on its own output; they now refuse it with AWS's `InvalidRequestException`, and an `AWS::IoT::TopicRule` with such an action fails its stack. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex dac34b6f..61917450 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, 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 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, except on mTLS MQTT connections with `AUTH=true`; **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/core/x509_utils.py b/ministack/core/x509_utils.pyindex 3c71fbf2..738a3b0b 100644--- a/ministack/core/x509_utils.py+++ b/ministack/core/x509_utils.py@@ -340,3 +340,11 @@ def get_certificate_id(cert_pem: str) -> str:cert = x509.load_pem_x509_certificate(cert_pem.encode("utf-8"))der = cert.public_bytes(serialization.Encoding.DER)return hashlib.sha256(der).hexdigest()+++def certificate_common_name(cert_pem: str) -> str | None:+ """Return the subject common name of ``cert_pem``, or None when it has none."""+ _require_crypto()+ cert = x509.load_pem_x509_certificate(cert_pem.encode("utf-8"))+ names = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)+ return str(names[0].value) if names else Nonediff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex a7bd011a..9ace80bd 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -72,6 +72,7 @@ import base64import contextlibimport contextvarsimport copy+import functoolsimport hashlibimport jsonimport logging@@ -90,6 +91,7 @@ from typing import Awaitable, Callablefrom urllib.parse import parse_qsl, parse_qsfrom ministack.core.arn import ArnParseError, parse_arn+from ministack.core.iam_evaluator import EvalContext, evaluate, parse_policy_documentfrom ministack.core.responses import (AccountRegionScopedDict,_request_account_id,@@ -103,6 +105,7 @@ from ministack.core.responses import ()from ministack.core.router import extract_access_key_idfrom ministack.core.x509_utils import (+ certificate_common_name,certificate_is_signed_by,generate_ca,get_certificate_id,@@ -7444,6 +7447,56 @@ def _reserved_topic_publish_allowed(topic: str) -> bool:return not topic.startswith("$") or topic.startswith(RESERVED_PUBLISH_PREFIXES)+_POLICY_VARIABLE_RE = re.compile(r"\$\{(iot:[A-Za-z.]+)\}")+++def _mqtt_policy_context(account_id: str, region: str, certificate_id: str, client_id: str) -> dict:+ """The policy variables of a certificate session, keyed in lower case."""+ with request_scope(account_id, region):+ record = _certificates.get(certificate_id) or {}+ attached = client_id in _things and _thing_arn(client_id) in record.get("attachedThings", [])+ context = {"iot:clientid": client_id, "iot:connection.thing.isattached": str(attached).lower()}+ if attached:+ context["iot:connection.thing.thingname"] = client_id+ common_name = certificate_common_name(record["certificatePem"]) if record.get("certificatePem") else None+ if common_name is not None:+ context["iot:certificate.subject.commonname"] = common_name+ return context++[email protected]_cache(maxsize=1024)+def _parsed_iot_policy(document: str, context: tuple) -> list:+ """The statements of an IoT policy document with the policy variables in ``context`` substituted."""+ values = dict(context)++ def substitute(match: re.Match) -> str:+ value = values.get(match.group(1).lower())+ return match.group(0) if value is None else json.dumps(value)[1:-1]++ return parse_policy_document(_POLICY_VARIABLE_RE.sub(substitute, document))+++def _mqtt_policy_allows(+ account_id: str, region: str, certificate_id: str, context: dict, action: str, resource: str+) -> bool:+ """Whether the policies attached to the certificate allow ``action`` on ``resource``."""+ with request_scope(account_id, region):+ record = _certificates.get(certificate_id) or {}+ policies = [_policies.get(name) for name in record.get("attachedPolicies", [])]+ documents = [p["versions"][p["defaultVersionId"]]["document"] for p in policies if p]+ ctx = EvalContext(+ principal_arn=f"arn:aws:iot:{region}:{account_id}:cert/{certificate_id}",+ principal_type="Certificate",+ principal_account=account_id,+ action=action,+ resource_arn=f"arn:aws:iot:{region}:{account_id}:{resource}",+ region=region,+ service_context=context,+ )+ variables = tuple(sorted(context.items()))+ return evaluate(ctx, [_parsed_iot_policy(doc, variables) for doc in documents]).decision == "Allow"++# ---------------------------------------------------------------------------# Broker public API (consumed by iot_data.py and handle_websocket)# ---------------------------------------------------------------------------@@ -9157,14 +9210,20 @@ class _WSSession:# Set when the broker itself ends the session, overriding whatever the# socket then looks like from the client's side.self._forced_disconnect_reason: str | None = None+ # The client certificate of an mTLS session; its policies are evaluated+ # under AUTH=true.+ self.certificate_id: str | None = None+ self._policy_context: dict = {}def disconnect_reason(self) -> str:"""Why this session ended, in AWS's disconnect-reason vocabulary.- Only the three the broker can actually tell apart are ever reported: a+ Only the reasons the broker can actually tell apart are ever reported: aDISCONNECT packet (``CLIENT_INITIATED_DISCONNECT``), a takeover by asecond connection using the same client id (``DUPLICATE_CLIENTID``),- and everything else — a transport that went away (``CONNECTION_LOST``).+ a packet the certificate's policies refuse (``CLIENT_ERROR`` on 3.1.1,+ ``AUTH_ERROR`` on MQTT 5), and everything else — a transport that went+ away (``CONNECTION_LOST``).AWS's remaining reasons name machinery this broker does not have(throttling, credential expiry, keep-alive enforcement), so reportingone would be a guess dressed up as a fact.@@ -9184,7 +9243,7 @@ class _WSSession:lifecycle events, so none is published for them."""if "#" in self._client_id or "+" in self._client_id:return- group ="presence" if event_type.endswith("connected") else "subscriptions"+ group = "subscriptions" if event_type.endswith("subscribed") else "presence"await _publish_event(self.account_id,self.region,@@ -9251,6 +9310,8 @@ class _WSSession:return properties or b"\x00"async def deliver_to_client(self, topic: str, payload: bytes, qos: int) -> None:+ if not self._policy_allows("iot:Receive", f"topic/{topic}"):+ returnproperties = _delivery_properties.get()retain = _delivery_retain.get()if qos == 0:@@ -9331,6 +9392,53 @@ class _WSSession:))+ def _evaluates_policies(self) -> bool:+ """Whether this session is held to its certificate's IoT policies (AUTH=true only)."""+ from ministack import app++ return app.AUTH and self.certificate_id is not None++ def _policy_allows(self, action: str, resource: str) -> bool:+ """Whether this session may do ``action`` on ``resource``."""+ return not self._evaluates_policies() or _mqtt_policy_allows(+ self.account_id, self.region, self.certificate_id, self._policy_context, action, resource+ )++ def _publish_allowed(self, topic: str, retain: bool) -> bool:+ """iot:Publish on the topic, and iot:RetainPublish too for a retained message."""+ resource = f"topic/{topic}"+ return self._policy_allows("iot:Publish", resource) and (+ not retain or self._policy_allows("iot:RetainPublish", resource)+ )++ async def _refuse_connect(self, denied: str) -> bool:+ """Refuse a CONNECT: CONNACK 0x87 on MQTT 5, a plain close on 3.1.1, and a connect_failed event."""+ _broker_logger.warning(+ "IoT broker: CONNECT from %r refused, the attached policies do not allow %s", self._client_id, denied+ )+ self._session_identifier = str(uuid.uuid4())+ await self._publish_lifecycle(+ "connect_failed", connectFailureReason="AUTHORIZATION_FAILED", ipAddress=_publish_source_ip.get()+ )+ self._client_id = ""+ self._will_topic = None+ if self.protocol_version == MQTT_5:+ await self.send_bytes(_make_connack(return_code=RC5_NOT_AUTHORIZED, protocol_version=MQTT_5))+ return False++ async def _close_unauthorized(self) -> bool:+ """End the session over a refused packet: DISCONNECT 0x87 on MQTT 5, a plain close on 3.1.1."""+ # Nothing more reaches the client, its own will included; the filters stay for a stored session.+ for sid in self._sub_ids:+ await broker_unsubscribe(sid)+ self._sub_ids.clear()+ if self.protocol_version == MQTT_5:+ self._forced_disconnect_reason = "AUTH_ERROR"+ await self.send_bytes(_make_disconnect(RC5_NOT_AUTHORIZED))+ else:+ self._forced_disconnect_reason = "CLIENT_ERROR"+ return False+async def _reject_malformed_packet(self, pkt_type: int, exc: Exception) -> None:"""Answer a packet this broker could not parse, then let the caller close.@@ -9478,6 +9586,15 @@ class _WSSession:self._will_retain = Falseself._will_properties = b""+ if self._evaluates_policies():+ self._policy_context = _mqtt_policy_context(+ self.account_id, self.region, self.certificate_id, client_id+ )+ if not self._policy_allows("iot:Connect", f"client/{client_id}"):+ return await self._refuse_connect(f"iot:Connect on client/{client_id}")+ if self._will_topic is not None and not self._publish_allowed(self._will_topic, self._will_retain):+ return await self._refuse_connect(f"the will on topic/{self._will_topic}")+self._graceful_disconnect = Falseself._forced_disconnect_reason = Noneself._session_identifier = str(uuid.uuid4())@@ -9567,6 +9684,16 @@ class _WSSession:if self.protocol_version == MQTT_5:await self.send_bytes(_make_disconnect(RC5_NOT_AUTHORIZED))return False+ if not self._publish_allowed(topic, retain):+ # MQTT 5 answers a refused QoS 1 PUBLISH with PUBACK 0x87 and+ # keeps the connection.+ _broker_logger.warning(+ "IoT broker: PUBLISH from %r to %r refused by the attached policies", self._client_id, topic+ )+ if self.protocol_version == MQTT_5 and qos == 1 and packet_id is not None:+ await self.send_bytes(_make_puback(packet_id, reason_code=RC5_NOT_AUTHORIZED))+ return True+ return await self._close_unauthorized()payload = body[off:]delivered = await broker_publish(self.account_id,@@ -9598,7 +9725,6 @@ class _WSSession:topics = []while off < len(body):topic, off = _read_string(body, off)- topics.append(topic)# MQTT 5 replaces 3.1.1's bare QoS byte with a subscription# options byte: the low two bits are the QoS, the rest are No# Local, Retain As Published and Retain Handling. In 3.1.1 the@@ -9608,6 +9734,16 @@ class _WSSession:raise ValueError("SUBSCRIBE topic filter without options byte")subscription_options = body[off]off += 1+ if not self._policy_allows("iot:Subscribe", f"topicfilter/{topic}"):+ # As on AWS: 3.1.1 closes, MQTT 5 refuses this filter alone.+ _broker_logger.warning(+ "IoT broker: SUBSCRIBE from %r to %r refused by the attached policies", self._client_id, topic+ )+ if self.protocol_version != MQTT_5:+ return await self._close_unauthorized()+ granted.append(RC5_NOT_AUTHORIZED)+ continue+ topics.append(topic)granted_qos = min(subscription_options & SUB_OPT_QOS_MASK, 1)# A granted QoS doubles as an MQTT 5 SUBACK reason code: 0x00# and 0x01 mean the same thing in both versions.@@ -9633,7 +9769,9 @@ class _WSSession:await self.send_bytes(_make_suback(packet_id, granted, protocol_version=self.protocol_version))- await self._publish_lifecycle("subscribed", topics=topics)+ # The event lists the granted filters; one with none granted raises no event.+ if topics or not granted:+ await self._publish_lifecycle("subscribed", topics=topics)return Trueif pkt_type == PKT_PUBACK:@@ -9910,6 +10048,11 @@ async def handle_websocket(# mean anything and what real AWS IoT does. The ambiguous case cannot be# attributed at all: two registrations see byte-identical bytes, so any# tie-break would award the session to whoever registered the copy.+# * with ``AUTH=true``, a session under a certificate is also held to the IoT+# policies attached to it, as on AWS: ``iot:Connect`` on the client id at+# CONNECT, ``iot:Publish`` (and ``iot:RetainPublish``) for a PUBLISH and the+# will, ``iot:Subscribe`` per topic filter and ``iot:Receive`` per delivered+# message. Without it no policy is evaluated.# * just-in-time registration, as on AWS: a certificate that is unknown, or# still PENDING_ACTIVATION, and signed by a registered CA that is ACTIVE# with auto-registration enabled is created PENDING_ACTIVATION in that CA's@@ -10551,9 +10694,9 @@ async def _mtls_serve_conn(reader: asyncio.StreamReader, writer: asyncio.StreamWaccount_token = _request_account_id.set(account_id)region_token = _request_region.set(region)- session = _WSSession(- _tcp_send, account_id, region, hashlib.sha256(der).hexdigest() if der else None- )+ certificate_id = hashlib.sha256(der).hexdigest() if der else None+ session = _WSSession(_tcp_send, account_id, region, certificate_id)+ session.certificate_id = certificate_idmax_buffer = _max_frame_buffer_bytes()_mtls_logger.info("IoT mTLS: connection from %s serving %s/%s (%s)",diff --git a/tests/conftest.py b/tests/conftest.pyindex c1cd8d6c..a924f503 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -334,6 +334,7 @@ _SERIAL_TESTS = {"tests/test_iot_data.py::test_mtls_listener_survives_reset","tests/test_iot_data.py::test_mtls_reset_rebinds_with_a_device_connected","tests/test_iot_data.py::test_mtls_shutdown_completes_with_a_device_connected",+ "tests/test_iot_data.py::test_mtls_auth_evaluates_iot_connect",}diff --git a/tests/test_iot.py b/tests/test_iot.pyindex e800326d..4f5ea58a 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -7244,6 +7244,306 @@ def test_iot_jitr_sni_only_ca_in_two_accounts_registers_where_the_name_points():assert second["status"] == "PENDING_ACTIVATION"+# ----------------------------------------------------------------------+# IoT policy evaluation on certificate sessions (AUTH=true)+# ----------------------------------------------------------------------++_POLICY_ARN = f"arn:aws:iot:{_TEST_REGION}:{_JITR_ACCOUNT}"+++async def _policy_device(iot_module, policies=(), thing=None, common_name=None) -> str:+ """Register an ACTIVE device certificate in the test scope, attach one policy+ per statement list in ``policies`` and the thing ``thing``; returns its id."""+ pytest.importorskip("cryptography")+ from ministack.core.responses import set_request_account_id, set_request_region+ from ministack.core.x509_utils import generate_ca, sign_leaf_certificate++ set_request_account_id(_JITR_ACCOUNT)+ set_request_region(_TEST_REGION)+ ca_pem, ca_key_pem = generate_ca(common_name=_unique("policy-ca"))+ cert_pem = sign_leaf_certificate(+ ca_cert_pem=ca_pem, ca_key_pem=ca_key_pem, common_name=common_name or _unique("device")+ )[0]+ registered = {"certificatePem": cert_pem, "status": "ACTIVE"}+ status, _, body = await iot_module.handle_request(+ "POST", "/certificate/register-no-ca", {}, json.dumps(registered).encode(), {}+ )+ assert status == 200+ cert = json.loads(body)+ for statements in policies:+ name = _unique("policy")+ doc = json.dumps({"Version": "2012-10-17", "Statement": statements})+ for method, path, payload in (+ ("POST", f"/policies/{name}", {"policyDocument": doc}),+ ("PUT", f"/target-policies/{name}", {"target": cert["certificateArn"]}),+ ):+ assert (await iot_module.handle_request(method, path, {}, json.dumps(payload).encode(), {}))[0] == 200+ if thing:+ principal = {"x-amzn-principal": cert["certificateArn"]}+ assert (await iot_module.handle_request("PUT", f"/things/{thing}/principals", principal, b"", {}))[0] == 200+ return cert["certificateId"]+++async def _policy_connect(cert_id, client_id, mqtt5=False, **connect):+ """CONNECT a session under ``cert_id``: (session, sent messages, keep open)."""+ send, sent = _mock_send()+ session = _IoTWSSession(send, _JITR_ACCOUNT, _TEST_REGION, cert_id)+ session.certificate_id = cert_id+ body = _build_mqtt5_connect_body(client_id) if mqtt5 else _build_connect_body(client_id, **connect)+ return session, sent, await session.handle_packet(PKT_CONNECT, 0, body)+++def test_mqtt_connect_evaluates_certificate_policies(monkeypatch):+ """Under AUTH=true a certificate session connects only when an attached+ policy allows iot:Connect on its client id and none denies it. A refusal+ closes without a CONNACK on 3.1.1 and answers 0x87 on MQTT 5, stores no+ session, publishes no will and publishes a connect_failed event."""+ import ministack.app as _app+ from ministack.services import iot as iot_module++ monkeypatch.setattr(_app, "AUTH", True)+ wills, failed, certs = [], [], {}++ async def _will(topic, payload, qos):+ wills.append(topic)++ async def _failed(topic, payload, qos):+ event = json.loads(payload)+ failed.append((event["clientId"], event["connectFailureReason"], event["principalIdentifier"], sorted(event)))++ async def _run():+ bare = certs["bare"] = await _policy_device(iot_module)+ only = certs["only"] = await _policy_device(+ iot_module, [[{"Effect": "Allow", "Action": "iot:Connect", "Resource": f"{_POLICY_ARN}:client/good"}]]+ )+ denied = certs["denied"] = await _policy_device(iot_module, [+ [{"Effect": "Allow", "Action": "iot:Connect", "Resource": "*"}],+ [{"Effect": "Deny", "Action": "iot:Connect", "Resource": f"{_POLICY_ARN}:client/blocked"}],+ ])+ await subscribe(_JITR_ACCOUNT, "will/#", _will)+ await subscribe(_JITR_ACCOUNT, "$aws/events/presence/connect_failed/+", _failed)+ cases = {+ "no policy": (bare, "bare", {"clean_session": False, "will_flag": True, "will_topic": "will/bare"}),+ "no policy, MQTT 5": (bare, "bare", {"mqtt5": True}),+ "allowed client": (only, "good", {}),+ "other client": (only, "other", {}),+ "denied client": (denied, "blocked", {}),+ "other client of the deny": (denied, "fine", {}),+ "no certificate": (None, "anonymous", {}),+ }+ outcomes = {}+ for label, (cert_id, client_id, connect) in cases.items():+ session, sent, keep = await _policy_connect(cert_id, client_id, **connect)+ await session.cleanup()+ outcomes[label] = (keep, _parse_connack(sent)[1])+ monkeypatch.setattr(_app, "AUTH", False)+ session, sent, keep = await _policy_connect(bare, "bare")+ await session.cleanup()+ outcomes["no policy, AUTH=false"] = (keep, _parse_connack(sent)[1])+ return outcomes++ try:+ outcomes = asyncio.run(_run())+ stored = (_JITR_ACCOUNT, _TEST_REGION, "bare") in _persistent_sessions+ finally:+ iot_module.reset()+ iot_module.broker_reset()+ assert outcomes == {+ "no policy": (False, None),+ "no policy, MQTT 5": (False, 0x87),+ "allowed client": (True, 0),+ "other client": (False, None),+ "denied client": (False, None),+ "other client of the deny": (True, 0),+ "no certificate": (True, 0),+ "no policy, AUTH=false": (True, 0),+ }+ assert wills == []+ assert not stored+ keys = ["clientId", "connectFailureReason", "eventType", "ipAddress", "principalIdentifier",+ "sessionIdentifier", "timestamp"]+ assert failed == [+ (client_id, "AUTHORIZATION_FAILED", certs[cert], keys)+ for client_id, cert in (("bare", "bare"), ("bare", "bare"), ("other", "only"), ("blocked", "denied"))+ ]+++def test_mqtt_connect_resolves_policy_variables(monkeypatch):+ """Thing variables resolve only when the client id is a thing attached to+ the certificate; the common name comes from the certificate subject."""+ import ministack.app as _app+ from ministack.core.responses import request_scope+ from ministack.services import iot as iot_module++ monkeypatch.setattr(_app, "AUTH", True)+ thing, other, name = _unique("thing"), _unique("other"), _unique("cn")++ async def _run():+ with request_scope(_JITR_ACCOUNT, _TEST_REGION):+ for t in (thing, other):+ assert (await iot_module.handle_request("POST", f"/things/{t}", {}, b"{}", {}))[0] == 200+ by_thing = await _policy_device(iot_module, [[{+ "Effect": "Allow", "Action": "iot:Connect",+ "Resource": f"{_POLICY_ARN}:client/${{iot:Connection.Thing.ThingName}}",+ }]], thing=thing)+ attached = await _policy_device(iot_module, [[{+ "Effect": "Allow", "Action": "iot:Connect", "Resource": "*",+ "Condition": {"Bool": {"iot:Connection.Thing.IsAttached": "true"}},+ }]], thing=thing)+ by_name = await _policy_device(iot_module, [[{+ "Effect": "Allow", "Action": "iot:Connect",+ "Resource": f"{_POLICY_ARN}:client/${{iot:Certificate.Subject.CommonName}}",+ }]], common_name=name)+ outcomes = []+ for cert_id, client_id in (+ (by_thing, thing), (by_thing, other), (by_thing, "nothing"),+ (attached, thing), (attached, other),+ (by_name, name), (by_name, "nothing"),+ ):+ session, _sent, keep = await _policy_connect(cert_id, client_id)+ await session.cleanup()+ outcomes.append(keep)+ return outcomes++ try:+ outcomes = asyncio.run(_run())+ finally:+ iot_module.reset()+ iot_module.broker_reset()+ assert outcomes == [True, False, False, True, False, True, False]+++def _sent_packets(sent):+ """(packet type, body) of every packet a session sent."""+ packets = []+ for msg in sent:+ data = msg["bytes"]+ _length, off = _decode_remaining_length(data, 1)+ packets.append((data[0] >> 4, data[off:]))+ return packets+++def test_mqtt_publish_subscribe_receive_evaluate_policies(monkeypatch):+ """Under AUTH=true iot:Publish (with iot:RetainPublish for a retained+ message or will), iot:Subscribe and iot:Receive are evaluated per packet.+ A refused PUBLISH or SUBSCRIBE closes a 3.1.1 session (CLIENT_ERROR);+ MQTT 5 answers PUBACK 0x87, DISCONNECT 0x87 for QoS 0 (AUTH_ERROR), or+ 0x87 for the one topic filter, which the subscribed event leaves out.+ A message the subscriber may not receive is dropped."""+ import ministack.app as _app+ from ministack.services import iot as iot_module++ monkeypatch.setattr(_app, "AUTH", True)+ events, received = [], []++ async def _received(topic, payload, qos):+ received.append(payload)++ async def _event(topic, payload, qos):+ event = json.loads(payload)+ detail = ("disconnectReason", "topics", "connectFailureReason")+ events.append((event["eventType"], event["clientId"], next(event[k] for k in detail if k in event)))++ def v3_publish(topic, packet_id):+ return _encode_string(topic) + struct.pack("!H", packet_id) + b"x"++ async def _run():+ cert = await _policy_device(iot_module, [[+ {"Effect": "Allow", "Action": "iot:Connect", "Resource": "*"},+ {"Effect": "Allow", "Action": "iot:Publish",+ "Resource": [f"{_POLICY_ARN}:topic/pub/${{iot:ClientId}}", f"{_POLICY_ARN}:topic/sub/*"]},+ {"Effect": "Allow", "Action": "iot:RetainPublish", "Resource": f"{_POLICY_ARN}:topic/sub/ret"},+ {"Effect": "Allow", "Action": "iot:Subscribe", "Resource": f"{_POLICY_ARN}:topicfilter/sub/#"},+ {"Effect": "Allow", "Action": "iot:Receive", "Resource": f"{_POLICY_ARN}:topic/sub/yes"},+ ]])+ for event_filter in ("presence/disconnected/+", "presence/connect_failed/+", "subscriptions/subscribed/+"):+ await subscribe(_JITR_ACCOUNT, f"$aws/events/{event_filter}", _event)+ await subscribe(_JITR_ACCOUNT, "sub/yes", _received)+ outcomes = {}++ async def _outcome(label, client_id, pkt_type, flags, body, mqtt5=False):+ session, sent, _keep = await _policy_connect(cert, client_id, mqtt5=mqtt5)+ sent.clear()+ keep = await session.handle_packet(pkt_type, flags, body)+ await session.cleanup()+ outcomes[label] = (keep, [(t, b.hex()) for t, b in _sent_packets(sent)])++ await _outcome("3.1.1 publish own topic", "c3", PKT_PUBLISH, 0x02, v3_publish("pub/c3", 1))+ await _outcome("3.1.1 publish other topic", "c3", PKT_PUBLISH, 0x02, v3_publish("pub/other", 2))+ await _outcome("3.1.1 publish retained, no RetainPublish", "c3", PKT_PUBLISH, 0x03, v3_publish("sub/x", 3))+ await _outcome("3.1.1 publish retained with RetainPublish", "c3", PKT_PUBLISH, 0x03, v3_publish("sub/ret", 4))+ await _outcome("3.1.1 subscribe allowed", "c3", PKT_SUBSCRIBE, 0x02,+ _build_subscribe_body(5, [("sub/#", 1)]))+ await _outcome("3.1.1 subscribe one refused", "c3", PKT_SUBSCRIBE, 0x02,+ _build_subscribe_body(6, [("sub/#", 1), ("other/#", 1)]))+ await _outcome("5 publish QoS 1 other topic", "c5", PKT_PUBLISH, 0x02,+ _build_mqtt5_publish_body("pub/other", b"x", qos=1, packet_id=7), mqtt5=True)+ await _outcome("5 publish QoS 0 other topic", "c5", PKT_PUBLISH, 0x00,+ _build_mqtt5_publish_body("pub/other", b"x"), mqtt5=True)+ await _outcome("5 subscribe one refused", "c5", PKT_SUBSCRIBE, 0x02,+ _build_mqtt5_subscribe_body(8, "sub/#", 1)+ + _encode_string("other/#") + b"\x01", mqtt5=True)+ await _outcome("5 subscribe all refused", "c5", PKT_SUBSCRIBE, 0x02,+ _build_mqtt5_subscribe_body(10, "other/#", 1), mqtt5=True)++ session, sent, keep = await _policy_connect(+ cert, "w3", will_flag=True, will_topic="sub/x", will_retain=True, will_message=b"bye"+ )+ await session.cleanup()+ outcomes["3.1.1 retained will, no RetainPublish"] = (keep, _sent_packets(sent))++ session, sent, _keep = await _policy_connect(+ cert, "w4", will_flag=True, will_topic="sub/yes", will_message=b"bye"+ )+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, _build_subscribe_body(11, [("sub/#", 0)]))+ sent.clear()+ keep = await session.handle_packet(PKT_PUBLISH, 0x02, v3_publish("pub/other", 12))+ await session.cleanup()+ outcomes["3.1.1 refused publish, own will"] = (keep, _sent_packets(sent))++ subscriber, sent, _keep = await _policy_connect(cert, "s3")+ await subscriber.handle_packet(PKT_SUBSCRIBE, 0x02, _build_subscribe_body(9, [("sub/#", 0)]))+ sent.clear()+ for topic in ("sub/yes", "sub/no", "sub/yes"):+ await publish(_JITR_ACCOUNT, topic, topic.encode())+ outcomes["receive"] = [frame[0] for frame in _extract_publish_frames(sent)]+ await subscriber.cleanup()+ return outcomes++ try:+ outcomes = asyncio.run(_run())+ finally:+ iot_module.reset()+ iot_module.broker_reset()+ assert outcomes == {+ "3.1.1 publish own topic": (True, [(PKT_PUBACK, "0001")]),+ "3.1.1 publish other topic": (False, []),+ "3.1.1 publish retained, no RetainPublish": (False, []),+ "3.1.1 publish retained with RetainPublish": (True, [(PKT_PUBACK, "0004")]),+ "3.1.1 subscribe allowed": (True, [(PKT_SUBACK, "000501")]),+ "3.1.1 subscribe one refused": (False, []),+ "5 publish QoS 1 other topic": (True, [(PKT_PUBACK, "00078700")]),+ "5 publish QoS 0 other topic": (False, [(PKT_DISCONNECT, "8700")]),+ "5 subscribe one refused": (True, [(PKT_SUBACK, "0008000187")]),+ "5 subscribe all refused": (True, [(PKT_SUBACK, "000a0087")]),+ "3.1.1 retained will, no RetainPublish": (False, []),+ "3.1.1 refused publish, own will": (False, []),+ "receive": ["sub/yes", "sub/yes"],+ }+ assert received == [b"bye", b"sub/yes", b"sub/yes"]+ lost, refused = ("disconnected", "c3", "CONNECTION_LOST"), ("disconnected", "c3", "CLIENT_ERROR")+ assert events == [+ lost, refused, refused, lost, ("subscribed", "c3", ["sub/#"]), lost, refused,+ ("disconnected", "c5", "CONNECTION_LOST"),+ ("disconnected", "c5", "AUTH_ERROR"),+ ("subscribed", "c5", ["sub/#"]), ("disconnected", "c5", "CONNECTION_LOST"),+ ("disconnected", "c5", "CONNECTION_LOST"),+ ("connect_failed", "w3", "AUTHORIZATION_FAILED"),+ ("subscribed", "w4", ["sub/#"]), ("disconnected", "w4", "CLIENT_ERROR"),+ ("subscribed", "s3", ["sub/#"]), ("disconnected", "s3", "CONNECTION_LOST"),+ ]++# ----------------------------------------------------------------------# Registry events ($aws/events/...) gated by UpdateEventConfigurations# ----------------------------------------------------------------------diff --git a/tests/test_iot_data.py b/tests/test_iot_data.pyindex 44872a81..14c56d55 100644--- a/tests/test_iot_data.py+++ b/tests/test_iot_data.py@@ -3886,6 +3886,40 @@ def test_mtls_ambiguous_cert_is_refused(broker, tmp_path):peer.close()+def test_mtls_auth_evaluates_iot_connect(tmp_path):+ """With AUTH=true a device certificate connects only under a policy that+ allows iot:Connect on its client id; otherwise the 3.1.1 CONNECT is closed+ without a CONNACK. A private instance, because AUTH is read at startup."""+ pytest.importorskip("cryptography")+ http_port, mqtt_port = _free_port(), _free_port()+ proc = _spawn({"AUTH": "true", "IOT_MTLS_ENABLED": "1", "IOT_MTLS_PORT": str(mqtt_port)}, http_port)+ try:+ _wait_ready(f"http://127.0.0.1:{http_port}/_ministack/ready")+ private = _Broker(http_port, mqtt_port)+ iot = private.client("iot")+ cert_id, cert_pem, key_pem = _new_cert(private)+ client_id = _unique("device")+ assert _refused_below_mqtt(private, cert_pem, key_pem, tmp_path, client_id)++ policy = _unique("connect")+ iot.create_policy(policyName=policy, policyDocument=json.dumps({+ "Version": "2012-10-17",+ "Statement": [+ {"Effect": "Allow", "Action": "iot:Connect", "Resource": f"arn:aws:iot:*:*:client/{client_id}"}+ ],+ }))+ arn = iot.describe_certificate(certificateId=cert_id)["certificateDescription"]["certificateArn"]+ iot.attach_policy(policyName=policy, target=arn)+ peer = _Peer(_mtls_connect(private, cert_pem, key_pem, tmp_path))+ try:+ _assert_connack(peer.connect(client_id))+ finally:+ peer.close()+ assert _refused_below_mqtt(private, cert_pem, key_pem, tmp_path, _unique("other"))+ finally:+ _terminate(proc)++def test_mtls_registered_cert_connects_whatever_its_ca(broker, tmp_path):"""An ACTIVE device certificate connects after its CA is deactivated ordeleted, and when it was registered without a CA, as on AWS; only its own