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): add job templates and AWS::IoT::JobTemplate (#2038)
iot-rocket7a37cadd5caa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 64ca6a89..8db6fe48 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added++- **IoT — job templates and `AWS::IoT::JobTemplate`** — `CreateJobTemplate`, `DescribeJobTemplate`, `ListJobTemplates` and `DeleteJobTemplate` were missing, so a `jobTemplateArn` could not be created or used. Templates now store a document or a `documentSource` (not fetched, like `CreateJob`'s), every job configuration member, maintenance windows and tags, can be copied from a job through `jobArn`, list newest first with `maxResults` / `nextToken` paging, and answer AWS's errors and messages. `CreateJob` with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a member the request names replaces the template's. CloudFormation creates and deletes `AWS::IoT::JobTemplate` (Ref is the id, `Fn::GetAtt` `Arn`); every property is create-only, so an update under the same `JobTemplateId` fails with AWS's custom-name sentence and a new id replaces the template. Contributed by @iot-rocket.### Fixed- **Kinesis — active subscriptions survive retention pruning** — `SubscribeToShard` tracks its selected sequence boundary instead of a record-list offset, so removing expired records cannot skip newly appended records. The starting boundary and checkpoint are captured before streaming begins and progress remains stable through idle polls and repeated pruning. Contributed by @AdrianAcala.diff --git a/README.md b/README.mdindex e3586bd4..62b3c63c 100644--- a/README.md+++ b/README.md@@ -580,6 +580,7 @@ subnet = ec2.create_subnet(| `AWS::ApiGatewayV2::DomainName` | Domain name | DomainNameArn, RegionalDomainName, RegionalHostedZoneId || `AWS::ApiGatewayV2::ApiMapping` | API mapping ID | ApiMappingId || `AWS::IoT::ProvisioningTemplate` | Template name | TemplateArn, Arn |+| `AWS::IoT::JobTemplate` | Job template id | Arn || `AWS::SES::EmailIdentity` | Identity | EmailIdentity || `AWS::SES::ConfigurationSet` | Configuration set name | None || `AWS::SES::ConfigurationSetEventDestination` | Event destination ID | Id |@@ -635,7 +636,7 @@ 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 complete immediately; session-based configuration retrieval with token rotation || **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, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, DescribeJobExecution, CancelJobExecution; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 9 control-plane + 4 device data-plane operations sharing one store. 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. **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 Jobs** | Control plane (`iot`): CreateJob, 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 | 13 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, 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 | 57 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 |diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex ed449932..ebc18e55 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -1527,6 +1527,7 @@ def extract_resource_arn(service: str, method: str, path: str,"rules": "rule","jobs": "job","provisioning-templates": "provisioningtemplate",+ "job-templates": "jobtemplate",}for segment, rtype in _IOT_RESOURCES.items():if segment in parts:diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex b170034a..ca6b7097 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -744,6 +744,7 @@ _CUSTOM_NAME_REPLACEMENT = {!= new.get("TemplateType", "FLEET_PROVISIONING")),},+ "AWS::IoT::JobTemplate": {"name": "JobTemplateId"},"AWS::Lambda::Function": {"name": "FunctionName"},"AWS::SQS::Queue": {"name": "QueueName",@@ -12947,6 +12948,51 @@ def _iot_provisioning_template_delete(physical_id, props):_iot._delete_provisioning_template(physical_id)+# AWS::IoT::JobTemplate. Every property is create-only (a change is a+# replacement, refused under the required, custom JobTemplateId), so the type+# has no update handler. Two CloudFormation member names differ from the API's.+_IOT_JOB_TEMPLATE_RENAMES = {+ "exponentialRolloutRate": "exponentialRate",+ "retryCriteriaList": "criteriaList",+}+++def _iot_job_template_payload(props):+ props = dict(props)+ if isinstance(props.get("Document"), (dict, list)):+ props["Document"] = json.dumps(props["Document"])+ tags = props.pop("Tags", None)+ props.pop("JobTemplateId", None)+ payload = {+ key: ({_IOT_JOB_TEMPLATE_RENAMES.get(k, k): v for k, v in value.items()}+ if isinstance(value, dict) else value)+ for key, value in _pascal_to_camel(props).items()+ if value is not None+ }+ if tags:+ payload["tags"] = tags+ return payload+++def _iot_job_template_create(logical_id, props, stack_name):+ template_id = str(props.get("JobTemplateId") or "")+ # A stack never adopts an existing template: AWS fails its name-conflict+ # validation before creating anything (measured eu-central-1, 2026-10-05).+ if template_id in _iot._job_templates:+ raise ValueError(+ f"Resource of type 'AWS::IoT::JobTemplate' with identifier '{template_id}' already exists."+ )+ resp = (_iot._job_template_id_error(template_id)+ or _iot._create_job_template(template_id, _iot_job_template_payload(props)))+ if resp[0] >= 400:+ raise ValueError(f"AWS::IoT::JobTemplate create failed: {resp[2]!r}")+ return template_id, {"Arn": _iot._job_template_arn(template_id)}+++def _iot_job_template_delete(physical_id, props):+ _iot._delete_job_template(physical_id)++def _registration_config_payload(props):"""CFN's RegistrationConfig (RoleArn/TemplateBody/TemplateName) in theAPI's camelCase, or None when the template declares none."""@@ -13406,6 +13452,11 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {"AWS::IAM::ManagedPolicy": ("ManagedPolicyName", "Description", "Path"),"AWS::ECR::Repository": ("RepositoryName", "EncryptionConfiguration"),"AWS::IoT::ProvisioningTemplate": ("TemplateName", "TemplateType"),+ "AWS::IoT::JobTemplate": (+ "JobTemplateId", "JobArn", "Description", "Document", "DocumentSource",+ "TimeoutConfig", "JobExecutionsRolloutConfig", "AbortConfig", "PresignedUrlConfig",+ "DestinationPackageVersions", "JobExecutionsRetryConfig", "MaintenanceWindows", "Tags",+ ),"AWS::ElasticLoadBalancingV2::LoadBalancer": ("Name", "Scheme", "Type"),"AWS::ElasticLoadBalancingV2::TargetGroup": ("Name", "Port", "Protocol", "ProtocolVersion", "TargetType", "VpcId",@@ -14292,6 +14343,10 @@ _RESOURCE_HANDLERS = {"update_with_logical_id": True,"delete": _iot_provisioning_template_delete,},+ "AWS::IoT::JobTemplate": {+ "create": _iot_job_template_create,+ "delete": _iot_job_template_delete,+ },"AWS::IoT::CACertificate": {"create": _iot_ca_certificate_create,"update": _iot_ca_certificate_update,diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex 95e7e84b..8d736967 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -40,6 +40,9 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:``ListJobExecutionsForThing``, ``DescribeJobExecution``,``CancelJobExecution`` — execution state shared with the``iot-jobs-data`` device data plane (``iot_jobs_data.py``)+ - Job templates: ``CreateJobTemplate``, ``DescribeJobTemplate``,+ ``ListJobTemplates``, ``DeleteJobTemplate``; ``CreateJob`` with a+ ``jobTemplateArn`` takes the template's document and configuration- ``DescribeEndpoint`` returning a per-account hostnameThis is the control plane — pure HTTP/JSON, no MQTT broker@@ -125,6 +128,7 @@ _provisioning_templates: AccountRegionScopedDict = AccountRegionScopedDict()_jobs: AccountRegionScopedDict = AccountRegionScopedDict() # jobId -> Job dict# (thingName, jobId) -> JobExecution dict — tuple keys, same pattern as _shadows_job_executions: AccountRegionScopedDict = AccountRegionScopedDict()+_job_templates: AccountRegionScopedDict = AccountRegionScopedDict() # jobTemplateId -> record# Local CA state — lazily generated on first use, persisted across restarts.import threading@@ -249,6 +253,7 @@ def get_state() -> dict:"provisioning_templates": copy.deepcopy(_provisioning_templates),"jobs": copy.deepcopy(_jobs),"job_executions": copy.deepcopy(_job_executions),+ "job_templates": copy.deepcopy(_job_templates),"ca": {"ca_cert_pem": _ca_cert_pem, "ca_key_pem": _ca_key_pem}if _ca_cert_pem and _ca_key_pemelse {},@@ -285,6 +290,7 @@ def _restore_state(data: dict | None) -> None:_provisioning_templates.update(data.get("provisioning_templates", {}))_jobs.update(data.get("jobs", {}))_job_executions.update(data.get("job_executions", {}))+ _job_templates.update(data.get("job_templates", {}))ca_data = data.get("ca")if ca_data:cert = ca_data.get("ca_cert_pem")@@ -326,6 +332,7 @@ def reset() -> None:_provisioning_templates.clear()_jobs.clear()_job_executions.clear()+ _job_templates.clear()with _CA_LOCK:_ca_cert_pem = None_ca_key_pem = None@@ -618,6 +625,10 @@ async def _route_request(return _list_jobs(qp)if path.startswith("/jobs/"):return await _handle_job(method, path, body, qp)+ if path == "/job-templates" and method == "GET":+ return _list_job_templates(qp)+ if path.startswith("/job-templates/"):+ return _handle_job_template(method, path, body)# Topic rulesif path == "/rules" and method == "GET":@@ -4643,6 +4654,10 @@ async def _create_job(job_id: str, payload: dict) -> tuple:return error_response_json("ResourceAlreadyExistsException", f"Job {job_id} already exists", 409)+ if payload.get("jobTemplateArn") is not None:+ payload, err = _job_payload_from_template(payload)+ if err:+ return err# Absent means SNAPSHOT (the AWS default); present means it has to be one# of the two modeled values — including the empty string, which would# otherwise default its way to a SNAPSHOT job the caller never asked for.@@ -4910,6 +4925,286 @@ def _get_job_document(job_id: str) -> tuple:return json_response({"document": job.get("document") or "{}"})+# ---------------------------------------------------------------------------+# Job templates. A template has no update call; CreateJob copies what it needs+# from one at create time, so deleting a template leaves its jobs as they are.+# Messages and shapes below were measured on eu-central-1 2026-10-05.+# ---------------------------------------------------------------------------++# The configuration a template hands to a job created from it, and to a+# template created from a job (jobArn). A member the request names wins whole.+_JOB_TEMPLATE_CONFIG_MEMBERS = (+ "presignedUrlConfig", "jobExecutionsRolloutConfig", "abortConfig",+ "timeoutConfig", "jobExecutionsRetryConfig",+)+_JOB_TEMPLATE_PAGE_MAX = 250+++def _job_template_arn(template_id: str) -> str:+ return f"arn:aws:iot:{get_region()}:{get_account_id()}:jobtemplate/{template_id}"+++def _job_template_validation_error(value, member: str, constraint: str) -> tuple:+ shown = "null" if value is None else f"'{value}'"+ return error_response_json(+ "InvalidRequestException",+ f"1 validation error detected: Value {shown} at '{member}' failed to "+ f"satisfy constraint: {constraint}",+ 400,+ )+++def _job_template_id_error(template_id: str) -> tuple | None:+ if len(template_id) > 64:+ return _job_template_validation_error(+ template_id, "jobTemplateId",+ "Member must have length less than or equal to 64",+ )+ if not _JOB_ID_RE.match(template_id):+ return _job_template_validation_error(+ template_id, "jobTemplateId",+ "Member must satisfy regular expression pattern: [a-zA-Z0-9_-]+",+ )+ return None+++def _job_template_not_found(template_id: str) -> tuple:+ return error_response_json(+ "ResourceNotFoundException", f"Job Template {template_id} cannot be found.", 404+ )+++def _handle_job_template(method: str, path: str, body: bytes) -> tuple:+ template_id = path[len("/job-templates/"):]+ if "/" in template_id:+ return error_response_json(+ "InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400+ )+ err = _job_template_id_error(template_id)+ if err:+ return err+ if method == "PUT":+ return _create_job_template(template_id, _parse_body(body))+ if method == "GET":+ return _describe_job_template(template_id)+ if method == "DELETE":+ return _delete_job_template(template_id)+ return error_response_json(+ "InvalidRequestException", f"Unsupported method: {method}", 400+ )+++def _create_job_template(template_id: str, payload: dict) -> tuple:+ if payload.get("description") is None:+ return _job_template_validation_error(+ None, "description", "Member must not be null"+ )+ document = payload.get("document")+ if isinstance(document, str) and len(document) > 32768:+ return _job_template_validation_error(+ document, "document", "Member must have length less than or equal to 32768"+ )+ minutes = (payload.get("timeoutConfig") or {}).get("inProgressTimeoutInMinutes")+ if minutes is not None and not (isinstance(minutes, int) and 1 <= minutes <= 10080):+ return error_response_json(+ "InvalidRequestException",+ "Provide valid timeout value, inProgressTimeoutInMinutes cannot be "+ f"{minutes}.",+ 400,+ )+ source = payload.get("documentSource")+ if document and source:+ return error_response_json(+ "InvalidRequestException",+ "Job document and job document source cannot be specified at the same time.",+ 400,+ )+ if not document and not source and not payload.get("jobArn"):+ return error_response_json(+ "InvalidRequestException",+ "Neither job document nor job document source is specified.",+ 400,+ )+ if template_id in _job_templates:+ return error_response_json(+ "ConflictException", f"Job Template {template_id} already exists.", 409,+ extra={"resourceId": None},+ )+ record = {+ "jobTemplateArn": _job_template_arn(template_id),+ "jobTemplateId": template_id,+ "description": payload["description"],+ "createdAt": _now_epoch(),+ }+ if payload.get("jobArn"):+ job_id = str(payload["jobArn"]).rsplit("/", 1)[-1]+ job = _jobs.get(job_id)+ if job is None or job["jobArn"] != payload["jobArn"]:+ return error_response_json(+ "ResourceNotFoundException", f"Job {job_id} cannot be found.", 404+ )+ record["document"] = job.get("document")+ record["documentSource"] = job.get("documentSource")+ for member in _JOB_TEMPLATE_CONFIG_MEMBERS:+ record[member] = copy.deepcopy(job.get(member)) or None+ if document or source:+ record["document"] = document+ record["documentSource"] = source+ if source and not document:+ # Same stand-in as CreateJob's: the S3 object is not fetched.+ record["document"] = json.dumps({"documentSource": source})+ for member in _JOB_TEMPLATE_CONFIG_MEMBERS + (+ "maintenanceWindows", "destinationPackageVersions", "tags",+ ):+ if payload.get(member) is not None:+ record[member] = copy.deepcopy(payload[member])+ # The two `double` members read back as floats (25 comes back as 25.0).+ for criteria in (record.get("abortConfig") or {}).get("criteriaList") or []:+ if isinstance(criteria.get("thresholdPercentage"), int):+ criteria["thresholdPercentage"] = float(criteria["thresholdPercentage"])+ rate = (record.get("jobExecutionsRolloutConfig") or {}).get("exponentialRate") or {}+ if isinstance(rate.get("incrementFactor"), int):+ rate["incrementFactor"] = float(rate["incrementFactor"])+ _job_templates[template_id] = record+ return json_response({+ "jobTemplateArn": record["jobTemplateArn"], "jobTemplateId": template_id,+ })+++def _describe_job_template(template_id: str) -> tuple:+ t = _job_templates.get(template_id)+ if t is None:+ return _job_template_not_found(template_id)+ # AWS writes every member, null when unset, and the three structures+ # below as objects of nulls; botocore reads those as {}.+ rollout = {"exponentialRate": None, "maximumPerMinute": None,+ **(t.get("jobExecutionsRolloutConfig") or {})}+ if rollout["exponentialRate"] is not None:+ rate = dict(rollout["exponentialRate"])+ rate["rateIncreaseCriteria"] = {+ "numberOfNotifiedThings": None, "numberOfSucceededThings": None,+ **(rate.get("rateIncreaseCriteria") or {}),+ }+ rollout["exponentialRate"] = rate+ return json_response({+ "jobTemplateArn": t["jobTemplateArn"],+ "jobTemplateId": t["jobTemplateId"],+ "description": t["description"],+ "documentSource": t.get("documentSource"),+ "document": t.get("document"),+ "createdAt": t["createdAt"],+ "presignedUrlConfig": {"expiresInSec": None, "roleArn": None,+ **(t.get("presignedUrlConfig") or {})},+ "jobExecutionsRolloutConfig": rollout,+ "abortConfig": t.get("abortConfig"),+ "timeoutConfig": {"inProgressTimeoutInMinutes": None,+ **(t.get("timeoutConfig") or {})},+ "jobExecutionsRetryConfig": t.get("jobExecutionsRetryConfig"),+ "maintenanceWindows": t.get("maintenanceWindows"),+ "destinationPackageVersions": t.get("destinationPackageVersions"),+ })+++def _list_job_templates(qp: dict) -> tuple:+ """``GET /job-templates``, newest first, paged by ``maxResults`` /+ ``nextToken``; the token carries an offset into that order."""+ raw = qp.get("maxResults")+ try:+ limit = _JOB_TEMPLATE_PAGE_MAX if raw in (None, "") else int(raw)+ except (TypeError, ValueError):+ limit = 0+ if not 1 <= limit <= _JOB_TEMPLATE_PAGE_MAX:+ bound = ("greater than or equal to 1" if limit < 1+ else f"less than or equal to {_JOB_TEMPLATE_PAGE_MAX}")+ return _job_template_validation_error(+ raw, "maxResults", f"Member must have value {bound}"+ )+ 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 == "jobtemplates" else -1+ except ValueError: # binascii.Error and UnicodeDecodeError included+ start = -1+ if start < 0:+ return error_response_json(+ "InvalidRequestException", "Next token is invalid.", 400+ )+ ordered = sorted(_job_templates.values(), key=lambda t: t["createdAt"], reverse=True)+ page = ordered[start:start + limit]+ response = {"jobTemplates": [+ {k: t[k] for k in ("jobTemplateArn", "jobTemplateId", "description", "createdAt")}+ for t in page+ ]}+ if start + limit < len(ordered):+ response["nextToken"] = base64.urlsafe_b64encode(+ f"jobtemplates:{start + limit}".encode()+ ).decode().rstrip("=")+ return json_response(response)+++def _delete_job_template(template_id: str) -> tuple:+ if _job_templates.get(template_id) is None:+ return _job_template_not_found(template_id)+ del _job_templates[template_id]+ # AWS answers 200 with an empty body.+ return 200, {"Content-Type": "application/x-amz-json-1.0"}, b""+++def _job_payload_from_template(payload: dict) -> tuple[dict | None, tuple | None]:+ """CreateJob's request with its jobTemplateArn applied: the template's+ document (unless the request names a document or a source), its+ configuration and its maintenance windows; members of the request win.+ Returns (payload, None) or (None, error)."""+ arn = payload["jobTemplateArn"]+ try:+ parsed = parse_arn(arn)+ except ArnParseError:+ return None, error_response_json(+ "InvalidRequestException", f"Invalid jobTemplateArn: {arn}", 400+ )+ resource_type, _, template_id = parsed.resource.partition("/")+ if resource_type != "jobtemplate":+ return None, error_response_json(+ "InvalidRequestException",+ "Resource type should be jobtemplate but found invalid resource type "+ f"{resource_type}",+ 400,+ )+ template = _job_templates.get(template_id)+ if template is None or template["jobTemplateArn"] != arn:+ return None, _job_template_not_found(template_id)+ merged = {+ m: copy.deepcopy(template[m]) for m in _JOB_TEMPLATE_CONFIG_MEMBERS if template.get(m)+ }+ if not payload.get("document") and not payload.get("documentSource"):+ merged["document"] = template.get("document")+ merged["documentSource"] = template.get("documentSource")+ merged.update({k: v for k, v in payload.items() if v is not None})+ windows = template.get("maintenanceWindows")+ if windows:+ if merged.get("targetSelection", "SNAPSHOT") == "SNAPSHOT":+ return None, error_response_json(+ "InvalidRequestException",+ "TargetSelection is invalid. MaintenanceWindow cannot be used with "+ "SNAPSHOT job.",+ 400,+ )+ sched = dict(merged.get("schedulingConfig") or {})+ if not sched.get("startTime"):+ return None, error_response_json(+ "InvalidRequestException",+ "MaintenanceWindow cannot be used without StartTime of "+ "SchedulingConfig.",+ 400,+ )+ sched.setdefault("maintenanceWindows", copy.deepcopy(windows))+ merged["schedulingConfig"] = sched+ return merged, None++async def _cancel_job(job_id: str, payload: dict, qp: dict) -> tuple:job = _jobs.get(job_id)if job is None:diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex bc0d91a6..4c7cf895 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -1161,6 +1161,132 @@ def test_cfn_iot_provisioning_template_generated_name(cfn, iot_client):iot_client.describe_provisioning_template(templateName=name)+def _cfn_job_template(template_id, **overrides):+ props = {+ "JobTemplateId": template_id,+ "Description": "from cloudformation",+ "Document": json.dumps({"operation": "cfn"}),+ "TimeoutConfig": {"InProgressTimeoutInMinutes": 20},+ "JobExecutionsRetryConfig": {+ "RetryCriteriaList": [{"FailureType": "FAILED", "NumberOfRetries": 1}]},+ "JobExecutionsRolloutConfig": {+ "MaximumPerMinute": 40,+ "ExponentialRolloutRate": {+ "BaseRatePerMinute": 4, "IncrementFactor": 1.5,+ "RateIncreaseCriteria": {"NumberOfSucceededThings": 3}}},+ "AbortConfig": {"CriteriaList": [{+ "Action": "CANCEL", "FailureType": "ALL",+ "MinNumberOfExecutedThings": 2, "ThresholdPercentage": 25}]},+ "PresignedUrlConfig": {+ "RoleArn": "arn:aws:iam::000000000000:role/presign", "ExpiresInSec": 900},+ "MaintenanceWindows": [+ {"StartTime": "cron(0 3 ? * SUN *)", "DurationInMinutes": 90}],+ "Tags": [{"Key": "k", "Value": "v"}],+ **overrides,+ }+ return json.dumps({+ "Resources": {"T": {"Type": "AWS::IoT::JobTemplate", "Properties": props}},+ "Outputs": {"Ref": {"Value": {"Ref": "T"}},+ "Arn": {"Value": {"Fn::GetAtt": ["T", "Arn"]}}},+ })+++def test_cfn_iot_job_template(cfn, iot_client):+ """AWS::IoT::JobTemplate creates the template through the IoT API with the+ two renamed members mapped (ExponentialRolloutRate, RetryCriteriaList), and+ every property is create-only: an update under the same JobTemplateId+ fails and rolls back, a new JobTemplateId replaces the template (measured+ on AWS, eu-central-1, 2026-10-05)."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack, old_id, new_id = f"cfn-iot-jobtmpl-{uid}", f"cfn-jt-{uid}", f"cfn-jt2-{uid}"+ try:+ cfn.create_stack(StackName=stack, TemplateBody=_cfn_job_template(old_id))+ result = _wait_stack(cfn, stack)+ assert result["StackStatus"] == "CREATE_COMPLETE"+ outputs = {o["OutputKey"]: o["OutputValue"] for o in result["Outputs"]}+ assert outputs["Ref"] == old_id+ assert outputs["Arn"] == f"arn:aws:iot:us-east-1:000000000000:jobtemplate/{old_id}"++ desc = iot_client.describe_job_template(jobTemplateId=old_id)+ assert desc["description"] == "from cloudformation"+ assert desc["document"] == json.dumps({"operation": "cfn"})+ assert desc["timeoutConfig"] == {"inProgressTimeoutInMinutes": 20}+ assert desc["jobExecutionsRetryConfig"] == {+ "criteriaList": [{"failureType": "FAILED", "numberOfRetries": 1}]}+ assert desc["jobExecutionsRolloutConfig"] == {+ "maximumPerMinute": 40,+ "exponentialRate": {"baseRatePerMinute": 4, "incrementFactor": 1.5,+ "rateIncreaseCriteria": {"numberOfSucceededThings": 3}}}+ assert desc["abortConfig"] == {"criteriaList": [{+ "action": "CANCEL", "failureType": "ALL",+ "minNumberOfExecutedThings": 2, "thresholdPercentage": 25.0}]}+ assert desc["presignedUrlConfig"] == {+ "roleArn": "arn:aws:iam::000000000000:role/presign", "expiresInSec": 900}+ assert desc["maintenanceWindows"] == [+ {"startTime": "cron(0 3 ? * SUN *)", "durationInMinutes": 90}]++ for change in ({"Description": "changed"}, {"Tags": [{"Key": "k", "Value": "w"}]}):+ cfn.update_stack(StackName=stack,+ TemplateBody=_cfn_job_template(old_id, **change))+ assert _wait_stack(cfn, stack)["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"+ reasons = [e.get("ResourceStatusReason", "") for e in+ cfn.describe_stack_events(StackName=stack)["StackEvents"]+ if e["ResourceStatus"] == "UPDATE_FAILED"]+ assert (+ "CloudFormation cannot update a stack when a custom-named resource "+ f"requires replacing. Rename {old_id} and update the stack again."+ ) in reasons, change+ assert iot_client.describe_job_template(+ jobTemplateId=old_id)["description"] == "from cloudformation"++ cfn.update_stack(StackName=stack, TemplateBody=_cfn_job_template(+ new_id, Description="renamed"))+ result = _wait_stack(cfn, stack)+ assert result["StackStatus"] == "UPDATE_COMPLETE"+ assert {o["OutputKey"]: o["OutputValue"] for o in result["Outputs"]}["Ref"] == new_id+ assert iot_client.describe_job_template(+ jobTemplateId=new_id)["description"] == "renamed"+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.describe_job_template(jobTemplateId=old_id)++ cfn.delete_stack(StackName=stack)+ _wait_stack(cfn, stack)+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.describe_job_template(jobTemplateId=new_id)+ finally:+ _delete_cfn_test_stack(cfn, stack)+ for template_id in (old_id, new_id):+ try:+ iot_client.delete_job_template(jobTemplateId=template_id)+ except ClientError:+ pass+++def test_cfn_iot_job_template_existing_id_fails_the_stack(cfn, iot_client):+ """A JobTemplateId that already exists fails the create with AWS's+ name-conflict text and rolls the stack back, leaving the existing+ template alone."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack, template_id = f"cfn-iot-jobtmpl-dup-{uid}", f"cfn-jt-dup-{uid}"+ iot_client.create_job_template(jobTemplateId=template_id, description="mine",+ document="{}")+ try:+ cfn.create_stack(StackName=stack, TemplateBody=_cfn_job_template(template_id))+ assert _wait_stack(cfn, stack)["StackStatus"] == "ROLLBACK_COMPLETE"+ reasons = [e.get("ResourceStatusReason", "") for e in+ cfn.describe_stack_events(StackName=stack)["StackEvents"]+ if e["ResourceStatus"] == "CREATE_FAILED"]+ assert (+ f"Resource of type 'AWS::IoT::JobTemplate' with identifier '{template_id}' "+ "already exists."+ ) in reasons+ assert iot_client.describe_job_template(+ jobTemplateId=template_id)["description"] == "mine"+ finally:+ _delete_cfn_test_stack(cfn, stack)+ iot_client.delete_job_template(jobTemplateId=template_id)++def test_cfn_iot_ca_certificate_lifecycle(cfn, iot_client):"""AWS::IoT::CACertificate provisions onto the real CA registry instead ofrolling the stack back: create registers the PEM (readable back throughdiff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex b684217d..ad0ab6fd 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -1773,6 +1773,12 @@ class TestResourceArn:from ministack.core.iam_actions import extract_resource_arnassert extract_resource_arn("iot", "GET", "/provisioning-templates/fleet", {}, b"", {}, "us-east-1", "123") == "arn:aws:iot:us-east-1:123:provisioningtemplate/fleet"+ def test_iot_job_template(self):+ from ministack.core.iam_actions import extract_resource_arn+ assert extract_resource_arn(+ "iot", "PUT", "/job-templates/ota", {}, b"", {}, "us-east-1", "123"+ ) == "arn:aws:iot:us-east-1:123:jobtemplate/ota"+def test_iot_publish_topic_keeps_every_level(self):"""A topic ARN carries the whole topic, not its first segment:arn:aws:iot:...:topic/sensors/rack-1/temperature. Truncating it todiff --git a/tests/test_iot_jobs_data.py b/tests/test_iot_jobs_data.pyindex 84b7fa3d..b7c7299c 100644--- a/tests/test_iot_jobs_data.py+++ b/tests/test_iot_jobs_data.py@@ -228,6 +228,352 @@ def test_iot_jobs_create_duplicate_and_unknown_target_rejected(iot_client):_cleanup(iot_client, jobs=[job_id], things=[thing])+# ---------------------------------------------------------------------------+# Job templates — shapes and messages measured on AWS (eu-central-1,+# 2026-10-05)+# ---------------------------------------------------------------------------++_TEMPLATE_ROLE = "arn:aws:iam::000000000000:role/presign"+_TEMPLATE_CONFIG = {+ "presignedUrlConfig": {"roleArn": _TEMPLATE_ROLE, "expiresInSec": 300},+ "jobExecutionsRolloutConfig": {+ "maximumPerMinute": 50,+ "exponentialRate": {+ "baseRatePerMinute": 5, "incrementFactor": 2,+ "rateIncreaseCriteria": {"numberOfNotifiedThings": 10},+ },+ },+ "abortConfig": {"criteriaList": [{+ "failureType": "FAILED", "action": "CANCEL",+ "thresholdPercentage": 50, "minNumberOfExecutedThings": 5,+ }]},+ "timeoutConfig": {"inProgressTimeoutInMinutes": 30},+ "jobExecutionsRetryConfig": {+ "criteriaList": [{"failureType": "FAILED", "numberOfRetries": 2}]+ },+}+++def _delete_templates(iot_client, *template_ids):+ for template_id in template_ids:+ try:+ iot_client.delete_job_template(jobTemplateId=template_id)+ except ClientError:+ pass+++def _error(ei):+ err = ei.value.response+ return (+ err["ResponseMetadata"]["HTTPStatusCode"],+ err["Error"]["Code"],+ err["Error"]["Message"],+ )+++def _raw_bytes(method, path):+ """Raw HTTP against the iot control plane; returns (status, body bytes)."""+ req = urllib.request.Request(+ f"{ENDPOINT}{path}", method=method, headers={"Authorization": _IOT_AUTH}+ )+ with urllib.request.urlopen(req, timeout=5) as resp:+ return resp.status, resp.read()+++def test_iot_job_template_create_describe_list_delete(iot_client):+ full, minimal = _unique("tmpl-full"), _unique("tmpl-min")+ try:+ created = iot_client.create_job_template(+ jobTemplateId=full, description="full", document=_DOCUMENT,+ tags=[{"Key": "k", "Value": "v"}], **_TEMPLATE_CONFIG,+ )+ assert created["jobTemplateId"] == full+ assert created["jobTemplateArn"] == (+ f"arn:aws:iot:us-east-1:000000000000:jobtemplate/{full}"+ )+ desc = iot_client.describe_job_template(jobTemplateId=full)+ assert desc["description"] == "full"+ assert desc["document"] == _DOCUMENT+ assert isinstance(desc["createdAt"], datetime)+ for member in ("presignedUrlConfig", "abortConfig", "timeoutConfig",+ "jobExecutionsRetryConfig"):+ assert desc[member] == _TEMPLATE_CONFIG[member], member+ rate = desc["jobExecutionsRolloutConfig"]["exponentialRate"]+ assert rate["rateIncreaseCriteria"] == {"numberOfNotifiedThings": 10}+ # The two `double` members read back as floats, as on AWS.+ assert isinstance(rate["incrementFactor"], float)+ assert isinstance(+ desc["abortConfig"]["criteriaList"][0]["thresholdPercentage"], float+ )++ iot_client.create_job_template(+ jobTemplateId=minimal, description="minimal", document=_DOCUMENT+ )+ # AWS writes every member, an unset one as null, and three structures+ # as objects of nulls.+ status, body = _raw(_IOT_AUTH, "GET", f"/job-templates/{minimal}")+ assert status == 200+ assert body["abortConfig"] is None+ assert body["documentSource"] is None+ assert body["maintenanceWindows"] is None+ assert body["timeoutConfig"] == {"inProgressTimeoutInMinutes": None}+ assert body["presignedUrlConfig"] == {"expiresInSec": None, "roleArn": None}+ assert body["jobExecutionsRolloutConfig"] == {+ "exponentialRate": None, "maximumPerMinute": None+ }++ # Newest first, one per page, behind an opaque token.+ seen, token = [], None+ while True:+ page = iot_client.list_job_templates(+ maxResults=1, **({"nextToken": token} if token else {})+ )+ assert len(page["jobTemplates"]) <= 1+ seen += [t for t in page["jobTemplates"]+ if t["jobTemplateId"] in (full, minimal)]+ token = page.get("nextToken")+ if not token:+ break+ assert [t["jobTemplateId"] for t in seen] == [minimal, full]+ assert set(seen[0]) == {+ "jobTemplateArn", "jobTemplateId", "description", "createdAt"+ }++ # Delete answers 200 with an empty body.+ assert _raw_bytes("DELETE", f"/job-templates/{full}") == (200, b"")+ with pytest.raises(ClientError) as ei:+ iot_client.describe_job_template(jobTemplateId=full)+ assert _error(ei) == (+ 404, "ResourceNotFoundException", f"Job Template {full} cannot be found."+ )+ finally:+ _delete_templates(iot_client, full, minimal)+++def test_iot_job_template_from_a_job(iot_client):+ thing, job_id = _unique("jobs-thing"), _unique("job")+ from_job, with_doc = _unique("tmpl-job"), _unique("tmpl-jobdoc")+ try:+ job_arn = iot_client.create_job(+ jobId=job_id, targets=[_create_thing(iot_client, thing)],+ document=_DOCUMENT,+ timeoutConfig={"inProgressTimeoutInMinutes": 15},+ jobExecutionsRetryConfig=_TEMPLATE_CONFIG["jobExecutionsRetryConfig"],+ )["jobArn"]+ iot_client.create_job_template(+ jobTemplateId=from_job, description="from job", jobArn=job_arn+ )+ desc = iot_client.describe_job_template(jobTemplateId=from_job)+ assert desc["description"] == "from job"+ assert desc["document"] == _DOCUMENT+ assert desc["timeoutConfig"] == {"inProgressTimeoutInMinutes": 15}+ assert desc["jobExecutionsRetryConfig"] == (+ _TEMPLATE_CONFIG["jobExecutionsRetryConfig"]+ )+ assert "abortConfig" not in desc++ # A document in the request replaces the job's; the rest still comes+ # from the job.+ iot_client.create_job_template(+ jobTemplateId=with_doc, description="d", jobArn=job_arn, document="{}"+ )+ desc = iot_client.describe_job_template(jobTemplateId=with_doc)+ assert desc["document"] == "{}"+ assert desc["timeoutConfig"] == {"inProgressTimeoutInMinutes": 15}++ with pytest.raises(ClientError) as ei:+ iot_client.create_job_template(+ jobTemplateId=_unique("tmpl"), description="d",+ jobArn=f"{job_arn}-gone",+ )+ assert _error(ei) == (+ 404, "ResourceNotFoundException", f"Job {job_id}-gone cannot be found."+ )+ finally:+ _delete_templates(iot_client, from_job, with_doc)+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_job_template_rejects_what_aws_rejects(iot_client):+ template_id = _unique("tmpl")+ try:+ iot_client.create_job_template(+ jobTemplateId=template_id, description="d", document=_DOCUMENT+ )+ with pytest.raises(ClientError) as ei:+ iot_client.create_job_template(+ jobTemplateId=template_id, description="d", document=_DOCUMENT+ )+ assert _error(ei) == (+ 409, "ConflictException", f"Job Template {template_id} already exists."+ )+ cases = [+ ({"description": "d", "document": "{}", "documentSource": "https://x/y"},+ "Job document and job document source cannot be specified at the same "+ "time."),+ ({"description": "d"},+ "Neither job document nor job document source is specified."),+ ({"document": "{}"},+ "1 validation error detected: Value null at 'description' failed to "+ "satisfy constraint: Member must not be null"),+ ({"description": "d", "document": "{}",+ "timeoutConfig": {"inProgressTimeoutInMinutes": 0}},+ "Provide valid timeout value, inProgressTimeoutInMinutes cannot be 0."),+ ({"description": "d", "document": "{}",+ "timeoutConfig": {"inProgressTimeoutInMinutes": 10081}},+ "Provide valid timeout value, inProgressTimeoutInMinutes cannot be "+ "10081."),+ ]+ for payload, message in cases:+ status, body = _raw(+ _IOT_AUTH, "PUT", f"/job-templates/{_unique('tmpl')}", payload+ )+ assert (status, body["message"]) == (400, message), payload++ for bad_id, constraint in (+ ("has.dot", "Member must satisfy regular expression pattern: "+ "[a-zA-Z0-9_-]+"),+ ("a" * 65, "Member must have length less than or equal to 64"),+ ):+ for method in ("PUT", "GET"):+ status, body = _raw(+ _IOT_AUTH, method, f"/job-templates/{bad_id}",+ {"description": "d", "document": "{}"},+ )+ assert (status, body["message"]) == (+ 400,+ f"1 validation error detected: Value '{bad_id}' at "+ f"'jobTemplateId' failed to satisfy constraint: {constraint}",+ ), (bad_id, method)++ for call in (iot_client.describe_job_template, iot_client.delete_job_template):+ with pytest.raises(ClientError) as ei:+ call(jobTemplateId=f"{template_id}-unknown")+ assert _error(ei) == (+ 404, "ResourceNotFoundException",+ f"Job Template {template_id}-unknown cannot be found.",+ )++ for query, message in (+ ("maxResults=0", "1 validation error detected: Value '0' at 'maxResults' "+ "failed to satisfy constraint: Member must have value greater than or "+ "equal to 1"),+ ("maxResults=251", "1 validation error detected: Value '251' at "+ "'maxResults' failed to satisfy constraint: Member must have value less "+ "than or equal to 250"),+ ("nextToken=garbage", "Next token is invalid."),+ ):+ status, body = _raw(_IOT_AUTH, "GET", f"/job-templates?{query}")+ assert (status, body["message"]) == (400, message), query+ finally:+ _delete_templates(iot_client, template_id)+++def test_iot_jobs_create_from_a_job_template(iot_client):+ thing = _unique("jobs-thing")+ template_id, mw_template = _unique("tmpl"), _unique("tmpl-mw")+ plain, overridden = _unique("job"), _unique("job")+ try:+ thing_arn = _create_thing(iot_client, thing)+ template_arn = iot_client.create_job_template(+ jobTemplateId=template_id, description="from template",+ document=_DOCUMENT, **_TEMPLATE_CONFIG,+ )["jobTemplateArn"]++ iot_client.create_job(jobId=plain, targets=[thing_arn],+ jobTemplateArn=template_arn)+ job = iot_client.describe_job(jobId=plain)["job"]+ assert job["jobTemplateArn"] == template_arn+ assert job["timeoutConfig"] == {"inProgressTimeoutInMinutes": 30}+ assert job["presignedUrlConfig"]["roleArn"] == _TEMPLATE_ROLE+ assert job["jobExecutionsRolloutConfig"]["maximumPerMinute"] == 50+ assert job["abortConfig"]["criteriaList"][0]["minNumberOfExecutedThings"] == 5+ assert job["jobExecutionsRetryConfig"] == (+ _TEMPLATE_CONFIG["jobExecutionsRetryConfig"]+ )+ assert "description" not in job, "the template's description is not inherited"+ assert iot_client.get_job_document(jobId=plain)["document"] == _DOCUMENT++ # A member the request names replaces the template's whole.+ iot_client.create_job(+ jobId=overridden, targets=[thing_arn], jobTemplateArn=template_arn,+ document='{"own": true}', timeoutConfig={"inProgressTimeoutInMinutes": 99},+ jobExecutionsRetryConfig={"criteriaList": [+ {"failureType": "ALL", "numberOfRetries": 3}]},+ )+ job = iot_client.describe_job(jobId=overridden)["job"]+ assert job["timeoutConfig"] == {"inProgressTimeoutInMinutes": 99}+ assert job["jobExecutionsRetryConfig"] == {"criteriaList": [+ {"failureType": "ALL", "numberOfRetries": 3}]}+ assert job["jobExecutionsRolloutConfig"]["maximumPerMinute"] == 50+ assert iot_client.get_job_document(jobId=overridden)["document"] == (+ '{"own": true}'+ )++ # Deleting the template leaves the jobs made from it alone.+ iot_client.delete_job_template(jobTemplateId=template_id)+ assert iot_client.describe_job(jobId=plain)["job"]["jobTemplateArn"] == (+ template_arn+ )++ mw_arn = iot_client.create_job_template(+ jobTemplateId=mw_template, description="mw", document=_DOCUMENT,+ maintenanceWindows=[{"startTime": "cron(0 2 ? * MON *)",+ "durationInMinutes": 60}],+ )["jobTemplateArn"]+ job_arn = template_arn.replace(f":jobtemplate/{template_id}", f":job/{plain}")+ for arn, status, code, message in (+ (template_arn, 404, "ResourceNotFoundException",+ f"Job Template {template_id} cannot be found."),+ (job_arn, 400, "InvalidRequestException",+ "Resource type should be jobtemplate but found invalid resource type job"),+ (mw_arn, 400, "InvalidRequestException",+ "TargetSelection is invalid. MaintenanceWindow cannot be used with "+ "SNAPSHOT job."),+ ):+ with pytest.raises(ClientError) as ei:+ iot_client.create_job(jobId=_unique("job"), targets=[thing_arn],+ jobTemplateArn=arn)+ assert _error(ei) == (status, code, message), arn+ finally:+ _delete_templates(iot_client, template_id, mw_template)+ _cleanup(iot_client, jobs=[plain, overridden], things=[thing])+++def test_iot_job_templates_are_scoped_and_persisted():+ """A template is visible to its own account and region only, travels+ through get_state / load_persisted_state, and reset() drops it."""+ from ministack.services import iot as iot_module++ template_id = _unique("tmpl")+ a = _account_client("iot", "111111111111")+ b = _account_client("iot", "222222222222")+ a_eu = _account_client("iot", "111111111111", region="eu-west-1")+ try:+ a.create_job_template(jobTemplateId=template_id, description="a",+ document=_DOCUMENT)+ for other in (b, a_eu):+ with pytest.raises(ClientError) as ei:+ other.describe_job_template(jobTemplateId=template_id)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ assert template_id not in {+ t["jobTemplateId"] for t in other.list_job_templates()["jobTemplates"]+ }+ finally:+ _delete_templates(a, template_id)++ record = {"jobTemplateId": template_id, "description": "restored"}+ iot_module._job_templates[template_id] = record+ state = iot_module.get_state()+ iot_module.reset()+ assert template_id not in iot_module._job_templates+ try:+ iot_module.load_persisted_state(state)+ assert iot_module._job_templates[template_id] == record+ finally:+ iot_module.reset()++# ---------------------------------------------------------------------------# Device lifecycle: start-next → update (optimistic concurrency) → job done# ---------------------------------------------------------------------------