Skip to content

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

feat(iot): add GetRetainedMessage and ListRetainedMessages (#2141)

iot-rocket6a4d1ac92d15
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 251adb82..5197a74c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
+- **IoT — retained messages** — `GetRetainedMessage` and `ListRetainedMessages` answered 501 `not yet implemented`; they now return the broker's retained messages (newest first, paged by `maxResults` and `nextToken`, with the user properties of an MQTT 5 publish), and a `PERSIST_STATE=1` restart keeps each message's `lastModifiedTime` and user properties. Contributed by @iot-rocket.
- **IoT — `ListJobExecutionsForJob`** — `GET /jobs/{jobId}/things` answered 400 `Unsupported IoT path`; it now lists every execution of the job, earlier ones of a rejoined thing included, most recently updated first, with the `status` filter and `maxResults` / `nextToken` paging. Contributed by @iot-rocket.
- **IoT — `DeleteJobExecution`** — `DELETE /things/{thingName}/jobs/{jobId}/executionNumber/{executionNumber}` answered 400 `Unsupported IoT path`; it now deletes the execution (an `IN_PROGRESS` one only with `force`), drops it from the job's lists and counts, completes the job when only finished executions are left, and publishes the `deleted` job execution event and the thing's `jobs/notify` topics; a `CONTINUOUS` job's thing left with no execution gets none back until it leaves the group, which leaves a `REMOVED` execution 1. Contributed by @iot-rocket.
### Fixed
diff --git a/README.md b/README.md
index de61e205..a2943bcb 100644
--- a/README.md
+++ b/README.md
@@ -646,8 +646,8 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i
| **CodeBuild** | CreateProject, BatchGetProjects, ListProjects, UpdateProject, DeleteProject, StartBuild, BatchGetBuilds, StopBuild, ListBuilds, ListBuildsForProject, BatchDeleteBuilds | 11 actions; project and build metadata stored in-memory; builds complete immediately with SUCCEEDED status by default. Set `MINISTACK_CODEBUILD_EXECUTE=1` and mount the Docker socket to **really run them**: the project's inline buildspec goes to the official AWS CodeBuild local agent, which runs the phases in `environment.image`, and `BatchGetBuilds` reports live `phases` with a real `SUCCEEDED`/`FAILED` outcome. Execution needs the workspace shared with the host at the **same path** (`-v /tmp/ministack-codebuild:/tmp/ministack-codebuild`), because the agent bind-mounts it into the build container; a build gets `AWS_ENDPOINT_URL` pointing back at MiniStack, honours `timeoutInMinutes`, and is stopped by `StopBuild`. An executed build streams the agent output into its `logs.groupName` / `logs.streamName`, so `aws logs tail` reads the build log back |
| **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, ListJobExecutionsForJob, DescribeJobExecution, CancelJobExecution, DeleteJobExecution, CreateJobTemplate, DescribeJobTemplate, ListJobTemplates, DeleteJobTemplate; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 16 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 counted in `jobProcessDetails`; a thing that leaves every target group of a `CONTINUOUS` job turns its `QUEUED` execution `REMOVED`, or gets a `REMOVED` execution 1 (without an event) if all its executions were deleted; 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 1 for a thing's first execution of a job and one more each time the thing rejoins a `CONTINUOUS` job's target group after its execution finished. 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()`, `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 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), GetRetainedMessage, ListRetainedMessages, MQTT-over-WebSocket pub/sub, DescribeEventConfigurations, UpdateEventConfigurations, CreateDomainConfiguration, DescribeDomainConfiguration, ListDomainConfigurations, UpdateDomainConfiguration, DeleteDomainConfiguration | 65 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/iot.py b/ministack/services/iot.py
index 5ea26b4e..9f2f68ac 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -201,15 +201,15 @@ _retained: dict[str, "_RetainedMessage"] = {}
class _RetainedMessage:
__slots__ = ("payload", "properties", "qos", "topic", "ts")
- def __init__(self, topic: str, payload: bytes, qos: int, properties: bytes = b""):
+ def __init__(self, topic: str, payload: bytes, qos: int, properties: bytes = b"",
+ ts: float | None = None):
self.topic = topic
self.payload = payload
self.qos = qos
# Encoded MQTT 5 property block forwarded to v5 subscribers, empty for
- # a message published by a 3.1.1 client. Runtime only: properties are
- # not part of the persisted retained-message state.
+ # a message published by a 3.1.1 client.
self.properties = properties
- self.ts = time.time()
+ self.ts = time.time() if ts is None else ts
def _broker_get_state() -> dict:
@@ -222,6 +222,8 @@ def _broker_get_state() -> dict:
"topic": msg.topic,
"payload": base64.b64encode(msg.payload).decode("ascii"),
"qos": msg.qos,
+ "properties": base64.b64encode(msg.properties).decode("ascii"),
+ "ts": msg.ts,
})
return {"region_scoped": True, "retained": retained_list}
@@ -240,7 +242,8 @@ def _broker_restore_state(data: dict | None) -> None:
)
payload = base64.b64decode(entry["payload"])
qos = entry.get("qos", 0)
- _retained[topic] = _RetainedMessage(topic, payload, qos)
+ properties = base64.b64decode(entry.get("properties", ""))
+ _retained[topic] = _RetainedMessage(topic, payload, qos, properties, entry.get("ts"))
# ---------------------------------------------------------------------------
@@ -8252,6 +8255,19 @@ async def broker_unsubscribe(subscription_id: str) -> None:
_subscriptions.pop(filter_, None)
+def broker_get_retained(account_id: str, region: str, topic: str) -> "_RetainedMessage | None":
+ """The retained message stored for ``topic``, or None."""
+ return _retained.get(_scoped_topic(account_id, region, topic))
+
+
+def broker_list_retained(account_id: str, region: str) -> list[tuple[str, "_RetainedMessage"]]:
+ """``(topic, message)`` for every retained message here, most recently stored first."""
+ prefix = f"{account_id}/{region}/"
+ found = [(k[len(prefix):], m) for k, m in _retained.items() if k.startswith(prefix)]
+ found.sort(key=lambda item: item[1].ts, reverse=True)
+ return found
+
+
def broker_reset() -> None:
_subscriptions.clear()
_retained.clear()
diff --git a/ministack/services/iot_data.py b/ministack/services/iot_data.py
index 2a9b04cd..675c2447 100644
--- a/ministack/services/iot_data.py
+++ b/ministack/services/iot_data.py
@@ -4,7 +4,8 @@
Implements the HTTP-side of the AWS IoT Data Plane. The data plane mirrors
the broker over a small REST surface (``Publish`` is the primary
-operation; ``GetRetainedMessage`` / ``ListRetainedMessages`` are not yet implemented).
+operation; ``GetRetainedMessage`` / ``ListRetainedMessages`` read the broker's
+retained messages).
Routing reaches us either through credential-scope detection (the SDK signs
requests with the ``iotdata`` scope) or via the host pattern
@@ -16,6 +17,7 @@ which applies account-and-region-scoped topic prefixing transparently.
from __future__ import annotations
+import base64
import copy
import json
import logging
@@ -36,6 +38,10 @@ logger = logging.getLogger("iot_data")
# AWS IoT topics: max 7 segments, max 256 UTF-8 bytes total.
_MAX_TOPIC_BYTES = 256
+# ListRetainedMessages page size without maxResults, and the most it allows.
+_RETAINED_PAGE_DEFAULT = 20
+_RETAINED_PAGE_MAX = 200
+
# HTTPS Publish to a topic starting with "$" is refused unless the topic sits
# under one of these reserved families. Within them, the device-side jobs,
# Device Defender and commands topics are MQTT-only.
@@ -120,20 +126,10 @@ async def handle_request(
if path.startswith("/things/") and path.endswith("/shadow"):
return await _shadow(method, path, body, qp)
- # Placeholders — return 501 so SDKs that probe these endpoints
- # get a clear "not implemented" rather than a generic 404.
- if path == "/retainedMessage":
- return error_response_json(
- "InvalidRequestException",
- "ListRetainedMessages is not yet implemented",
- 501,
- )
- if path.startswith("/retainedMessage/"):
- return error_response_json(
- "InvalidRequestException",
- "GetRetainedMessage is not yet implemented",
- 501,
- )
+ if method == "GET" and path == "/retainedMessage":
+ return _list_retained_messages(qp)
+ if method == "GET" and path.startswith("/retainedMessage/"):
+ return _get_retained_message(path[len("/retainedMessage/"):])
return error_response_json(
"InvalidRequestException", f"Unsupported iot-data path: {method} {path}", 400
@@ -249,3 +245,91 @@ async def _publish(raw_topic: str, body: bytes, qp: dict) -> tuple:
)
# AWS returns 200 with empty body for Publish.
return 200, {"Content-Type": "application/json"}, b""
+
+
+def _user_properties(properties: bytes) -> bytes:
+ """MQTT 5 user properties as the JSON array AWS returns, or b"" without any."""
+ if not properties:
+ return b""
+ props, _ = _iot_module._decode_properties(properties, 0)
+ pairs = [
+ {value[0]: value[1]}
+ for identifier, value in props
+ if identifier == _iot_module.PROP_USER_PROPERTY
+ ]
+ if not pairs:
+ return b""
+ return json.dumps(pairs, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
+
+
+def _get_retained_message(raw_topic: str) -> tuple:
+ """``GET /retainedMessage/{topic}``: the retained message stored for the topic."""
+ topic = unquote(raw_topic)
+ if not topic:
+ return error_response_json("InvalidRequestException", "unknown", 400)
+ if "+" in topic or "#" in topic:
+ return error_response_json(
+ "InvalidRequestException", "Invalid topic filter", 400
+ )
+ msg = _iot_module.broker_get_retained(get_account_id(), get_region(), topic)
+ if msg is None:
+ return error_response_json(
+ "ResourceNotFoundException", "Retained message not found", 404
+ )
+ body = {
+ "topic": topic,
+ "qos": msg.qos,
+ "payload": base64.b64encode(msg.payload).decode("ascii"),
+ }
+ user_properties = _user_properties(msg.properties)
+ if user_properties:
+ body["userProperties"] = base64.b64encode(user_properties).decode("ascii")
+ body["lastModifiedTime"] = int(msg.ts * 1000)
+ return json_response(body)
+
+
+def _list_retained_messages(qp: dict) -> tuple:
+ """``GET /retainedMessage``: retained topics, newest first, paged by an offset token."""
+ raw = qp.get("maxResults")
+ try:
+ limit = _RETAINED_PAGE_DEFAULT if raw is None else int(raw)
+ except (TypeError, ValueError):
+ return error_response_json(
+ "InvalidRequestException", f"Invalid maxResults value: {raw}", 400
+ )
+ if not 1 <= limit <= _RETAINED_PAGE_MAX:
+ return error_response_json(
+ "InvalidRequestException",
+ "Invalid maxResults value: Invalid max results parameter",
+ 400,
+ )
+ start = 0
+ token = qp.get("nextToken")
+ if token:
+ try:
+ raw_token = base64.urlsafe_b64decode(token + "=" * (-len(token) % 4)).decode()
+ prefix, _, offset = raw_token.partition(":")
+ start = int(offset) if prefix == "retainedmessages" else -1
+ except ValueError: # binascii.Error and UnicodeDecodeError included
+ start = -1
+ if start < 0:
+ return error_response_json("InvalidRequestException", "unknown", 400)
+ ordered = _iot_module.broker_list_retained(get_account_id(), get_region())
+ body: dict = {
+ "retainedTopics": [
+ {
+ "payloadSize": len(msg.payload),
+ "lastModifiedTime": int(msg.ts * 1000),
+ "topic": topic,
+ "qos": msg.qos,
+ }
+ for topic, msg in ordered[start:start + limit]
+ ],
+ # The last page carries an empty token.
+ "nextToken": "",
+ }
+ if start + limit < len(ordered):
+ body["nextToken"] = base64.urlsafe_b64encode(
+ f"retainedmessages:{start + limit}".encode()
+ ).decode().rstrip("=")
+ return json_response(body)
diff --git a/tests/test_iot_data.py b/tests/test_iot_data.py
index a8b2fff9..2a01bd3b 100644
--- a/tests/test_iot_data.py
+++ b/tests/test_iot_data.py
@@ -59,6 +59,187 @@ def test_iot_data_publish_accepts_qos_and_retain(iot_data_client):
assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+def _own_account_iot_data(**config):
+ """An iot-data client in a fresh account, so other tests' retained messages stay out of its listings."""
+ return boto3.client(
+ "iot-data",
+ endpoint_url=ENDPOINT,
+ aws_access_key_id=f"{uuid.uuid4().int % 10**12:012d}",
+ aws_secret_access_key="test",
+ region_name="us-east-1",
+ config=Config(retries={"mode": "standard"}, **config),
+ )
+
+
+def test_get_retained_message_returns_the_retained_publish():
+ client = _own_account_iot_data()
+ payload = bytes(range(256))
+ for topic in ("sensors/bin", "sensors/a b%c/ü"):
+ before = int(time.time() * 1000)
+ client.publish(topic=topic, qos=1, retain=True, payload=payload)
+ after = int(time.time() * 1000)
+ resp = client.get_retained_message(topic=topic)
+ assert resp["topic"] == topic
+ assert resp["payload"] == payload
+ assert resp["qos"] == 1
+ assert before <= resp["lastModifiedTime"] <= after
+ assert "userProperties" not in resp
+
+
+def test_get_retained_message_errors():
+ client = _own_account_iot_data(parameter_validation=False)
+ with pytest.raises(ClientError) as ei:
+ client.get_retained_message(topic="sensors/never")
+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ assert ei.value.response["Error"]["Message"] == "Retained message not found"
+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ for topic, message in (
+ ("sensors/+", "Invalid topic filter"),
+ ("sensors/#", "Invalid topic filter"),
+ ("sensors/a+b", "Invalid topic filter"),
+ ("", "unknown"),
+ ):
+ with pytest.raises(ClientError) as ei:
+ client.get_retained_message(topic=topic)
+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
+ assert ei.value.response["Error"]["Message"] == message
+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+
+
+def test_retained_message_is_replaced_kept_and_cleared():
+ """A live publish keeps the retained message, a retained one replaces it, an empty one clears it."""
+ client = _own_account_iot_data()
+ client.publish(topic="t", qos=0, retain=True, payload=b"hello")
+ first = client.get_retained_message(topic="t")
+ client.publish(topic="t", qos=1, payload=b"live")
+ client.publish(topic="t", qos=0, payload=b"")
+ kept = client.get_retained_message(topic="t")
+ assert (kept["payload"], kept["qos"]) == (b"hello", 0)
+ assert kept["lastModifiedTime"] == first["lastModifiedTime"]
+
+ time.sleep(0.01)
+ client.publish(topic="t", qos=1, retain=True, payload=b"second")
+ replaced = client.get_retained_message(topic="t")
+ assert (replaced["payload"], replaced["qos"]) == (b"second", 1)
+ assert replaced["lastModifiedTime"] > first["lastModifiedTime"]
+
+ client.publish(topic="t", qos=0, retain=True, payload=b"")
+ with pytest.raises(ClientError) as ei:
+ client.get_retained_message(topic="t")
+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ assert client.list_retained_messages()["retainedTopics"] == []
+
+
+def test_list_retained_messages_newest_first_in_pages():
+ client = _own_account_iot_data()
+ for name in ("c", "a", "d", "b"):
+ client.publish(topic=f"order/{name}", qos=1, retain=True, payload=name.encode() * 3)
+ time.sleep(0.01)
+ client.publish(topic="order/a", qos=0, payload=b"live")
+
+ resp = client.list_retained_messages()
+ assert resp["nextToken"] == ""
+ assert [e["topic"] for e in resp["retainedTopics"]] == [
+ "order/b", "order/d", "order/a", "order/c"
+ ]
+ entry = resp["retainedTopics"][0]
+ assert set(entry) == {"topic", "payloadSize", "qos", "lastModifiedTime"}
+ assert (entry["payloadSize"], entry["qos"]) == (3, 1)
+ assert entry["lastModifiedTime"] == client.get_retained_message(
+ topic="order/b")["lastModifiedTime"]
+
+ seen, kwargs = [], {"maxResults": 3}
+ while True:
+ page = client.list_retained_messages(**kwargs)
+ seen.append([e["topic"] for e in page["retainedTopics"]])
+ if not page["nextToken"]:
+ break
+ kwargs["nextToken"] = page["nextToken"]
+ assert seen == [["order/b", "order/d", "order/a"], ["order/c"]]
+
+
+def test_list_retained_messages_pages_by_twenty_without_max_results():
+ client = _own_account_iot_data()
+ for i in range(21):
+ client.publish(topic=f"page/{i:02d}", retain=True, payload=b"p")
+ first = client.list_retained_messages()
+ assert len(first["retainedTopics"]) == 20
+ rest = client.list_retained_messages(nextToken=first["nextToken"])
+ assert [e["topic"] for e in rest["retainedTopics"]] == ["page/00"]
+ assert rest["nextToken"] == ""
+
+
+ ("kwargs", "message"),
+ [
+ ({"maxResults": 0}, "Invalid maxResults value: Invalid max results parameter"),
+ ({"maxResults": 201}, "Invalid maxResults value: Invalid max results parameter"),
+ ({"maxResults": -1}, "Invalid maxResults value: Invalid max results parameter"),
+ ({"maxResults": "abc"}, "Invalid maxResults value: abc"),
+ ({"nextToken": "not-a-token"}, "unknown"),
+ ],
+)
+def test_list_retained_messages_rejects_bad_paging(kwargs, message):
+ client = _own_account_iot_data(parameter_validation=False)
+ with pytest.raises(ClientError) as ei:
+ client.list_retained_messages(**kwargs)
+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
+ assert ei.value.response["Error"]["Message"] == message
+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+
+
+def test_retained_user_properties_and_time_survive_persistence():
+ """User properties come back as AWS's JSON array and survive a restore with lastModifiedTime, per region."""
+ import asyncio
+
+ from ministack.core.responses import set_request_account_id, set_request_region
+ from ministack.services import iot as iot_module
+ from ministack.services import iot_data
+
+ account = "123456789012"
+ user_props = iot_module._encode_properties([
+ (iot_module.PROP_CONTENT_TYPE, "text/plain"),
+ (iot_module.PROP_USER_PROPERTY, ("app", "demo")),
+ (iot_module.PROP_USER_PROPERTY, ("k", "v1")),
+ (iot_module.PROP_USER_PROPERTY, ("k", "v2")),
+ (iot_module.PROP_USER_PROPERTY, ("u", "ü")),
+ ])
+ content_type_only = iot_module._encode_properties([(iot_module.PROP_CONTENT_TYPE, "text/plain")])
+
+ async def _get(region, path):
+ set_request_account_id(account)
+ set_request_region(region)
+ status, _headers, body = await iot_data.handle_request("GET", path, {}, b"", {})
+ return status, json.loads(body)
+
+ async def _run():
+ await iot_module.broker_publish(
+ account, "eu-west-1", "dev/props", b"{}", qos=1, retain=True, properties=user_props)
+ await iot_module.broker_publish(
+ account, "eu-west-1", "dev/plain", b"x", retain=True, properties=content_type_only)
+ status, before = await _get("eu-west-1", "/retainedMessage/dev/props")
+ assert status == 200
+ assert base64.b64decode(before["userProperties"]) == (
+ '[{"app":"demo"},{"k":"v1"},{"k":"v2"},{"u":"ü"}]'.encode())
+ assert "userProperties" not in (await _get("eu-west-1", "/retainedMessage/dev/plain"))[1]
+ assert (await _get("eu-west-3", "/retainedMessage"))[1]["retainedTopics"] == []
+
+ saved = iot_module.get_state()
+ iot_module.reset()
+ iot_module.broker_reset()
+ assert (await _get("eu-west-1", "/retainedMessage/dev/props"))[0] == 404
+ await asyncio.sleep(0.01)
+ iot_module.load_persisted_state(saved)
+ assert await _get("eu-west-1", "/retainedMessage/dev/props") == (200, before)
+
+ iot_module.broker_reset()
+ try:
+ asyncio.run(_run())
+ finally:
+ iot_module.reset()
+ iot_module.broker_reset()
+
+
def test_iot_data_publish_rejects_wildcard_topic():
"""Wildcard characters in publish topics must produce a 400."""
import urllib.request