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(iotwireless): GetPositionEstimate (#1662)
iot-rocket12a8a44c3658
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 72fe4dc6..7f3cfb75 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added- **CloudFormation — the `Rules` section is evaluated** — a template's rules were ignored; they now run after the parameters resolve and before any resource is touched, on `CreateStack`, `UpdateStack` and `CreateChangeSet`: a rule whose `RuleCondition` is false is skipped, a false `Assert` refuses the operation with its `AssertDescription` as a `ValidationError`, and the CDK's `CheckBootstrapVersion` rule therefore refuses an outdated bootstrap version instead of passing silently. `Fn::And`, `Fn::Or`, `Fn::Not`, `Fn::Equals`, `Fn::If`, `Fn::Contains`, `Fn::EachMemberEquals`, `Fn::EachMemberIn` and `Ref` are evaluated; `Fn::RefAll`, `Fn::ValueOf` and `Fn::ValueOfAll` are served from the EC2 store for the VPC, subnet and security-group id types, and a rule over any other type is skipped with a warning. A function outside the rule set is refused as a template format error. Contributed by @iot-rocket.- **CloudFormation — the `AWS::Include` transform** — an embedded `Fn::Transform` naming `AWS::Include` was carried into the stack as a literal key; it is now replaced by the contents of the S3 object its `Location` points to (JSON or plain YAML, a key-value object) before the template is validated: next to a sibling resource inside `Resources`, as a whole `Properties` map, inside one next to other properties, in `Mappings`, or in `Outputs`. A location that is not an `s3://` URI, a snippet with a YAML shorthand tag, a missing object, a snippet that is not an object and a nested include are refused before a stack exists, with the sentence a real account answers where one is known. `UsePreviousTemplate` and a change set without a body reuse the stored processed template, so a snippet edited in S3 since the deploy is not picked up, as on AWS. Contributed by @iot-rocket.+- **IoT Wireless — `GetPositionEstimate`** — the service was absent. `POST /position-estimate` now answers the way the API is shaped: the output structure declares a `payload` blob, so the HTTP body is the raw GeoJSON `Point` and boto3 hands the caller a `StreamingBody`, not a JSON envelope. The estimate is synthetic and deterministic (the canonical `Ip.IpAddress` hashes onto lon [-180, 180) / lat [-60, 60)); `properties` carry the two accuracy fields plus `timestamp`, which is always there: AWS documents the request's `Timestamp` as the time the position is resolved and the receive time as its substitute when the caller sends none, so a request that carries a `Timestamp` answers byte-identical bytes. `WiFiAccessPoints`, `CellTowers` and `Gnss` are accepted and ignored, while `AdvancedConfiguration.WiFiCellular.ConfidencePercent` drives the reported `horizontalConfidenceLevel` over 100, within the 50 to 99 the model allows. Refusals carry the live service's wording: no measurement, an unparseable address, a `Timestamp` that is not a Unix timestamp or a `ConfidencePercent` out of range is `ValidationException`; an address that is not globally routable, or is multicast, is `ResourceNotFoundException` `Cannot find position for the IP address <ip>`, as is a well-formed request whose only measurements are WLAN/cell/GNSS, which AWS documents that class for. Stateless. Contributed by @iot-rocket.### Fixed- **CloudFormation — the template and stack quotas are enforced** — a template of any size, with any number of resources, parameters, outputs or mappings, and a stack name of any shape were accepted, so a template that a real account refuses deployed. `CreateStack`, `UpdateStack`, `CreateChangeSet`, `ValidateTemplate` and `GetTemplateSummary` now refuse a `TemplateBody` over 51,200 bytes and a template behind `TemplateURL` over 1,000,000 bytes; the engine refuses more than 500 resources, 200 parameters, 200 outputs, 200 mappings or 200 attributes in a mapping, a name over 255 characters, a description over 1,024 bytes and a parameter default or value over 4,096 bytes; `CreateStack` and a `CREATE` change set refuse a stack name that is not alphanumeric-and-hyphens starting with a letter or longer than 128 characters, joined with an oversized body into the one message the API's parameter validation gives. All of it before a stack record exists, with the messages of the API's parameter validation and the template format errors. `ValidateTemplate` also takes `TemplateURL` now. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex 4018a27c..834979aa 100644--- a/README.md+++ b/README.md@@ -597,6 +597,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i| **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}`; the remaining AWS terminal statuses (`TIMED_OUT`, `REMOVED`) are modeled and counted in `jobProcessDetails` but nothing sets them — there are no execution timeouts, and 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 Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, ListThingGroupsForThing, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, 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 | 52 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 |+| **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 the two accuracy values of one live call (`horizontalAccuracy` 1000000, `horizontalConfidenceLevel` 0.67, measured on a call that sent no `AdvancedConfiguration`, so that is the default level — `AdvancedConfiguration.WiFiCellular.ConfidencePercent` is the caller's say over it and drives the reported level over 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` with the live service's verbatim wording; 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, naming the IP-only scope — AWS documents that class for a measurement it cannot solve, 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, 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 || **OpenSearch Service** | CreateDomain, DescribeDomain, DescribeDomains, DeleteDomain, ListDomainNames, UpdateDomainConfig, DescribeDomainConfig, DescribeDomainChangeProgress, ListVersions, GetCompatibleVersions, AddTags, ListTags, RemoveTags | Management plane on `/2021-01-01/*` (`boto3.client("opensearch")`, SigV4 scope `es`). Default data plane is a stub endpoint (`<domain>.ministack.local:9200`) — set `OPENSEARCH_DATAPLANE=1` to spawn one real `opensearchproject/opensearch` container per `CreateDomain` (same pattern as ElastiCache/RDS); `DescribeDomain.Endpoint` then points at that container and `_cluster/health`/`/_search` work end-to-end. Add `OPENSEARCH_DASHBOARDS=1` (with dataplane on) to also spawn a per-domain `opensearch-dashboards` sidecar; `DescribeDomain.DashboardEndpoint` is populated. ARNs follow `arn:aws:es:<region>:<account>:domain/<name>`; Terraform `aws_opensearch_domain` resource compatible. |diff --git a/ministack/app.py b/ministack/app.pyindex b526fc9e..d73202f8 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -371,6 +371,7 @@ SERVICE_REGISTRY = {"iot": {"module": "iot"},"iot-data": {"module": "iot_data"},"iot-jobs-data": {"module": "iot_jobs_data"},+ "iotwireless": {"module": "iotwireless"},"kinesis": {"module": "kinesis"},"kms": {"module": "kms"},"lambda": {"module": "lambda_svc"},diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex 95303340..6c757b0e 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -73,6 +73,7 @@ SERVICE_TO_IAM_NAMESPACE: dict[str, str] = {"iot": "iot","iot-data": "iot","iot-jobs-data": "iot",+ "iotwireless": "iotwireless","kafka": "kafka","kinesis": "kinesis","kms": "kms",@@ -440,6 +441,7 @@ _BOTOCORE_SERVICE_MAP: dict[str, list[str]] = {"iot": ["iot"],"iot-data": ["iot-data"],"iot-jobs-data": ["iot-jobs-data"],+ "iotwireless": ["iotwireless"],"kafka": ["kafka"],"mediaconnect": ["mediaconnect"],"mq": ["mq"],diff --git a/ministack/core/router.py b/ministack/core/router.pyindex 9f8d006c..25057017 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -304,6 +304,19 @@ SERVICE_PATTERNS = {"host_patterns": [r"transfer\."],"credential_scope": "transfer",},+ # IoT Wireless (endpoint prefix `api.iotwireless.{region}`). The bare+ # token is anchored at a label boundary, so it matches the `api.` host+ # too. Kept above the iot family for reading order, but there is no+ # actual overlap: the host never contains the literal `iot.` segment the+ # control plane's `iot\.` regex needs (`iot` is followed by `w`) — a+ # router test pins that anyway. The SDK signs with credential scope+ # `iotwireless` (botocore signingName), which the scope early-return+ # resolves via this key.+ "iotwireless": {+ "host_patterns": [r"iotwireless\."],+ "credential_scope": "iotwireless",+ "path_prefixes": ["/position-estimate"],+ },# IoT Jobs data plane (iot-jobs-data API) MUST come before "iot-data" and# "iot": its host also matches the `iot\.` regex, so first-match-wins# routing would otherwise swallow it — and on the `iot` control plane@@ -1103,6 +1116,12 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->return "bedrock-runtime"if path_lower.startswith("/v1/apis") or path_lower.startswith("/v1/tags/arn:aws:appsync"):return "appsync"+ # IoT Wireless GetPositionEstimate — boto3 signs (scope `iotwireless`)+ # and the host pattern also matches, but an unsigned caller (curl) must+ # still resolve by path. POST-only and exact, so an S3 object named+ # `position-estimate` keeps routing to S3 on GET/PUT.+ if method == "POST" and path_lower == "/position-estimate":+ return "iotwireless"if path_lower.startswith("/key-value-stores/"):return "cloudfront-keyvaluestore"if path_lower.startswith("/2020-05-31/"):diff --git a/ministack/services/iotwireless.py b/ministack/services/iotwireless.pynew file mode 100644index 00000000..9d1bed54--- /dev/null+++ b/ministack/services/iotwireless.py@@ -0,0 +1,317 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).+"""IoT Wireless HTTP API (``iotwireless`` AWS service).++Implements ``GetPositionEstimate`` (``POST /position-estimate``), the+device-location resolver of AWS IoT Wireless (endpoint prefix+``api.iotwireless``, REST-JSON, SigV4 scope ``iotwireless``).++Wire shape worth stating up front: the output structure declares+``"payload": "GeoJsonPayload"``, so the HTTP response body IS the raw GeoJSON+blob, not a JSON envelope, and boto3 hands the caller a ``StreamingBody``.+Answering ``{"GeoJsonPayload": ...}`` would break every SDK client.++Resolver scope: the real service resolves WLAN, cell-tower, GNSS and IP+measurements through third-party solvers. MiniStack resolves from ``Ip``+only. ``WiFiAccessPoints``, ``CellTowers`` and ``Gnss`` are accepted and+ignored, and none of them moves the estimate. The estimate is synthetic+and deterministic: the canonical+form of ``Ip.IpAddress`` is hashed (SHA-256) onto lon [-180, 180) / lat+[-60, 60), 4 decimals, so the same address always answers the same estimate+and a consumer test can assert on it.++The blob's ``properties`` carry the two accuracy fields with the values of+the single live call recorded for this work (eu-west-1, 2026-08-26):+``horizontalAccuracy`` 1000000 and ``horizontalConfidenceLevel`` 0.67. That+call asked for nothing, so 0.67 is the default level;+``AdvancedConfiguration.WiFiCellular.ConfidencePercent`` is the caller's own+say over it and drives the reported level, over 100, within the 50 to 99 the+model allows. The+``timestamp`` property is always there: AWS documents the request's+``Timestamp`` as the time at which the position is resolved and says "if not+specified, the time at which the request was received will be used", so the+caller's value is echoed when there is one and the receive time stands in+otherwise. That is the one part of the payload that is not a function of the+request; send a ``Timestamp`` and the same request answers byte-identical+GeoJSON. The live payload's ``country`` is left out for determinism, as are+the ``city`` / ``state`` / ``postalCode`` properties the developer guide+lists for IP lookups (documented divergence).++Refusals mirror the live service verbatim (measured eu-west-1 2026-08-26).+An input with no resolver hint answers ``ValidationException`` ``"1+validation error detected: Request must have at least 1 valid position+measurement."``, and an ``IpAddress`` that ``ipaddress.ip_address()``+refuses answers ``ValidationException`` ``"1 validation error detected: IP+Address is not valid."``. A valid address the resolver cannot place answers+``ResourceNotFoundException`` ``"Cannot find position for the IP address+<ip>"``, which is how the real service refuses an address its geo database+has no entry for (measured with TEST-NET 203.0.113.7). MiniStack+approximates that refusal class deterministically by refusing every address+that is not globally routable or is multicast and resolving every other one+(documented divergence), following the running interpreter's ``ipaddress``+view: private, loopback, link-local, reserved, TEST-NET and multicast+addresses do not resolve.++An input whose only hints are WLAN/cell/GNSS measurements is well formed and+unresolvable, so it answers ``ResourceNotFoundException`` too, with a+message naming the IP-only scope: AWS documents that class for "no location+information was found or solved ... insufficient data in the measurement+data input", where the real service would run the third-party solvers.++An IPv4-mapped IPv6 address hashes as its IPv4 form. A malformed JSON body+is a ``ValidationException``, as is a ``Timestamp`` that is not a Unix+timestamp (a raw HTTP caller can send one; an SDK cannot) and a+``ConfidencePercent`` outside the range the model allows.+"""++from __future__ import annotations++import hashlib+import ipaddress+import json+import logging+from datetime import datetime, timezone++from ministack.core.responses import error_response_json++logger = logging.getLogger("iotwireless")+++# ---------------------------------------------------------------------------+# Persistence (no state: the estimate is a pure function of the request)+# ---------------------------------------------------------------------------+++def get_state() -> dict:+ return {}+++def restore_state(data: dict | None) -> None:+ return None+++def reset() -> None:+ return None+++# ---------------------------------------------------------------------------+# Dispatcher+# ---------------------------------------------------------------------------+++async def handle_request(+ method: str, path: str, headers: dict, body: bytes, query_params: dict+) -> tuple:+ if method == "POST" and path == "/position-estimate":+ return _get_position_estimate(body)+ return error_response_json(+ "ValidationException", f"No route for {method} {path}", 400+ )+++# ---------------------------------------------------------------------------+# GetPositionEstimate+# ---------------------------------------------------------------------------++# The members the real service treats as resolver input. At least one must be+# present: the developer guide lists "the payload contains only the timestamp+# information" as one of the causes of the documented 400, so `Timestamp` and+# `AdvancedConfiguration` alone do not count. Presence is what matters, not+# the value, so an empty `Ip` reaches the address validator below.+_HINT_MEMBERS = ("WiFiAccessPoints", "CellTowers", "Ip", "Gnss")++# The values of the one live call recorded for this work (eu-west-1,+# 2026-08-26). Fixed, because the estimate is synthetic: there is no solver+# behind it whose accuracy could vary per address. That call sent no+# `AdvancedConfiguration`, so 0.67 is what the service reports when the+# caller asks for nothing; a caller that does ask drives the level itself.+_HORIZONTAL_ACCURACY = 1000000+_HORIZONTAL_CONFIDENCE_LEVEL = 0.67++# `AdvancedConfiguration.WiFiCellular.ConfidencePercent`, as the model+# constrains it: an integer, 50 to 99 inclusive.+_CONFIDENCE_PERCENT_MIN = 50+_CONFIDENCE_PERCENT_MAX = 99++# What a member reader answers when the request's value is not one the member+# accepts, so the caller gets the documented 400 instead of the value.+_INVALID = object()+++def _validation(message: str) -> tuple:+ return error_response_json("ValidationException", message, 400)+++def _get_position_estimate(body: bytes) -> tuple:+ if body:+ try:+ payload = json.loads(body)+ except ValueError:+ return _validation("Request body is not valid JSON")+ if not isinstance(payload, dict):+ return _validation("Request body must be a JSON object")+ else:+ payload = {}++ if not any(member in payload for member in _HINT_MEMBERS):+ # Measured verbatim on the live service.+ return _validation(+ "1 validation error detected: Request must have at least 1 valid "+ "position measurement."+ )+ resolved_at = _resolved_timestamp(payload)+ if resolved_at is _INVALID:+ # The input is checked before the resolver runs, so a Timestamp that+ # is not a timestamp is the documented 400 whatever the address does.+ return _validation(+ "Timestamp must be a Unix timestamp, in seconds since the epoch"+ )+ confidence_level = _confidence_level(payload)+ if confidence_level is _INVALID:+ return _validation(+ "AdvancedConfiguration.WiFiCellular.ConfidencePercent must be an "+ f"integer from {_CONFIDENCE_PERCENT_MIN} to "+ f"{_CONFIDENCE_PERCENT_MAX}"+ )+ if "Ip" not in payload:+ # A WLAN/cell/GNSS-only request is well formed, MiniStack simply has+ # no solver behind it. AWS reserves 400 for malformed input and+ # documents 404 for exactly this outcome: "no location information+ # was found or solved ... due to cases such as insufficient data in+ # the measurement data input", so the scope limit refuses like the+ # address the resolver cannot place, not like bad JSON.+ return error_response_json(+ "ResourceNotFoundException",+ "MiniStack resolves position from Ip only: provide Ip.IpAddress "+ "(WiFiAccessPoints/CellTowers/Gnss are accepted but not resolved)",+ 404,+ )+ ip_member = payload["Ip"]+ raw = ip_member.get("IpAddress") if isinstance(ip_member, dict) else None+ try:+ address = ipaddress.ip_address(str(raw))+ except ValueError:+ # Measured verbatim on the live service.+ return _validation("1 validation error detected: IP Address is not valid.")+ # ::ffff:1.2.3.4 is the same address as 1.2.3.4; hash the IPv4 form.+ address = getattr(address, "ipv4_mapped", None) or address+ canonical = str(address)+ if not address.is_global or address.is_multicast:+ # The real service refuses an address its geo database cannot place+ # (measured with TEST-NET 203.0.113.7); MiniStack approximates that+ # refusal class deterministically with the global-routability test+ # (multicast groups are global in `ipaddress` but have no place).+ return error_response_json(+ "ResourceNotFoundException",+ f"Cannot find position for the IP address {canonical}",+ 404,+ )++ lon, lat = _coordinates_for(canonical)+ properties = {+ "horizontalAccuracy": _HORIZONTAL_ACCURACY,+ "horizontalConfidenceLevel": confidence_level,+ "timestamp": resolved_at,+ }+ geojson = {+ "coordinates": [lon, lat],+ "type": "Point",+ "properties": properties,+ }+ logger.info(+ "IoT Wireless: resolved %s to (%s, %s)", canonical, lon, lat+ )+ # Raw payload blob: the output shape's `payload` trait, see module+ # docstring. No JSON envelope.+ blob = json.dumps(geojson, ensure_ascii=False).encode("utf-8")+ return 200, {"Content-Type": "application/octet-stream"}, blob+++def _resolved_timestamp(payload: dict):+ """The value for ``properties.timestamp``, or ``_INVALID``.++ AWS documents the request's ``Timestamp`` as "the time when the position+ information will be resolved", in Unix timestamp format, and adds "if not+ specified, the time at which the request was received will be used". The+ developer guide lists the payload as carrying "the timestamp information,+ which corresponds to the date and time at which the location was+ resolved" and both documented sample payloads have it, as did the one+ live call recorded for this work, so the property is never left out.++ The member is modelled as a timestamp, and rest-json puts one on the wire+ as the Unix number, so a value that is not that number is not a timestamp+ and the request is refused. A string is read as the same number spelled+ the JSON way, which is all a hand-written request can add; an ISO-8601+ string is not a Unix timestamp and does not pass.++ The caller's value is rendered the way the live payload reports the+ resolve time, as an ISO-8601 string. The substituted receive time stands+ in for a member in Unix timestamp format, so it is taken at whole-second+ resolution.+ """+ if "Timestamp" not in payload:+ return _render_timestamp(datetime.now(timezone.utc).replace(microsecond=0))+ value = payload["Timestamp"]+ if isinstance(value, str):+ try:+ value = float(value)+ except ValueError:+ return _INVALID+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ return _INVALID+ try:+ return _render_timestamp(datetime.fromtimestamp(value, timezone.utc))+ except (OSError, OverflowError, ValueError):+ # Out of the range a date can be built from, NaN, an infinity.+ return _INVALID+++def _render_timestamp(moment: datetime) -> str:+ return moment.isoformat().replace("+00:00", "Z")+++def _confidence_level(payload: dict):+ """The value for ``properties.horizontalConfidenceLevel``, or ``_INVALID``.++ ``AdvancedConfiguration.WiFiCellular.ConfidencePercent`` is documented as+ "confidence level for WiFi and cellular position estimates, expressed as+ a percentage", so a value the caller supplies IS the level the payload+ reports, over 100. The model constrains it to an integer from 50 to 99+ inclusive and a value outside that is refused rather than clamped.++ Omitted, the level stays the 0.67 of the one live call, which sent no+ ``AdvancedConfiguration`` at all. AWS documents the member's own default+ as 68, and a caller who sends ``ConfidencePercent: 68`` gets 0.68 here;+ what 0.67 records is what the service answered a request that asked for+ nothing, which is the thing an emulator has to reproduce.+ """+ advanced = payload.get("AdvancedConfiguration")+ if advanced is None:+ return _HORIZONTAL_CONFIDENCE_LEVEL+ if not isinstance(advanced, dict):+ return _INVALID+ wifi_cellular = advanced.get("WiFiCellular")+ if wifi_cellular is None:+ return _HORIZONTAL_CONFIDENCE_LEVEL+ if not isinstance(wifi_cellular, dict):+ return _INVALID+ percent = wifi_cellular.get("ConfidencePercent")+ if percent is None:+ return _HORIZONTAL_CONFIDENCE_LEVEL+ if isinstance(percent, bool) or not isinstance(percent, int):+ return _INVALID+ if not _CONFIDENCE_PERCENT_MIN <= percent <= _CONFIDENCE_PERCENT_MAX:+ return _INVALID+ return percent / 100+++def _coordinates_for(canonical_ip: str) -> tuple[float, float]:+ """Synthetic deterministic estimate: SHA-256 of the canonical IP mapped+ onto lon [-180, 180) / lat [-60, 60), rounded to 4 decimals. The upper+ bounds are clamped: a raw value in [179.99995, 180) (or [59.99995, 60))+ would otherwise round to exactly 180.0 / 60.0 and break the documented+ half-open interval."""+ digest = hashlib.sha256(canonical_ip.encode("utf-8")).digest()+ lon = int.from_bytes(digest[:8], "big") / 2**64 * 360.0 - 180.0+ lat = int.from_bytes(digest[8:16], "big") / 2**64 * 120.0 - 60.0+ return min(round(lon, 4), 179.9999), min(round(lat, 4), 59.9999)diff --git a/tests/conftest.py b/tests/conftest.pyindex f26c53a6..ece36eee 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -563,6 +563,11 @@ def iot_jobs_data():return make_client("iot-jobs-data")[email protected](scope="session")+def iotwireless():+ return make_client("iotwireless")++@pytest.fixture(scope="session")def wafv2():return make_client("wafv2")diff --git a/tests/test_iotwireless.py b/tests/test_iotwireless.pynew file mode 100644index 00000000..9888e6c2--- /dev/null+++ b/tests/test_iotwireless.py@@ -0,0 +1,412 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).+"""IoT Wireless GetPositionEstimate tests.++The response is NOT a JSON envelope: the output shape declares+``"payload": "GeoJsonPayload"``, so the HTTP body is the raw GeoJSON blob and+boto3 hands back a ``StreamingBody`` under the ``GeoJsonPayload`` key. Every+happy-path test here reads that stream and parses it, pinning the wire shape.++Happy-path addresses must be globally routable: the resolver mirrors the+real service's refusal of an address its geo database cannot place (measured+with TEST-NET 203.0.113.7) by refusing every non-global address, so the+documentation ranges (TEST-NET, 10/8, ::1) are exactly the ones that DON'T+resolve.+"""+import json+import urllib.error+import urllib.request+from datetime import datetime, timezone++import pytest+from botocore.exceptions import ClientError+from conftest import ENDPOINT++# One instant, so the rendered `properties.timestamp` is a fixed string.+_TIMESTAMP = datetime(2026, 8, 26, 14, 6, 11, tzinfo=timezone.utc)+_TIMESTAMP_RENDERED = "2026-08-26T14:06:11Z"++# The members that are accepted but never resolve the position, with the+# sample values of the AWS developer guide's payload. `CellTowers` is an+# object keyed by radio type, not an array. `AdvancedConfiguration` is not+# here: `ConfidencePercent` is the caller's say over the reported confidence+# level, so it does move the payload (see its own tests below).+_NON_IP_MEMBERS = {+ "WiFiAccessPoints": [{"MacAddress": "A0:EC:F9:1E:32:C1", "Rss": -75}],+ "CellTowers": {+ "Gsm": [{"Mcc": 262, "Mnc": 1, "Lac": 5126, "GeranCid": 16504}]+ },+ "Gnss": {"Payload": "8295D1B1B1B1B1B1B1"},+ "Timestamp": _TIMESTAMP,+}+++def _raw(path, body, method="POST"):+ """Unsigned raw HTTP (no Authorization header, like curl); returns+ (status, content-type, body bytes)."""+ req = urllib.request.Request(+ f"{ENDPOINT}{path}", data=body, method=method,+ headers={"content-type": "application/json"},+ )+ try:+ with urllib.request.urlopen(req, timeout=5) as resp:+ return resp.status, resp.headers.get("content-type"), resp.read()+ except urllib.error.HTTPError as e:+ return e.code, e.headers.get("content-type"), e.read()+++def _estimate_bytes(client, ip, **members):+ response = client.get_position_estimate(Ip={"IpAddress": ip}, **members)+ return response["GeoJsonPayload"].read()+++def _estimate_without_timestamp(client, ip, **members):+ """The parsed blob with `properties.timestamp` removed. Without a+ `Timestamp` in the request that property carries the receive time, so it+ is the one part of the payload that is not a function of the request."""+ document = json.loads(_estimate_bytes(client, ip, **members))+ document["properties"].pop("timestamp")+ return document+++def test_iotwireless_position_estimate_is_geojson_point_blob(iotwireless):+ """The streamed blob parses as a GeoJSON Point with in-range coordinates."""+ document = json.loads(_estimate_bytes(iotwireless, "1.2.3.4"))+ assert document["type"] == "Point"+ lon, lat = document["coordinates"]+ assert -180 <= lon < 180+ assert -60 <= lat < 60+++def test_iotwireless_accuracy_properties_carry_the_measured_values(iotwireless):+ """The two accuracy properties carry the values of the one live call+ (eu-west-1, 2026-08-26), which sent no `AdvancedConfiguration`."""+ properties = json.loads(_estimate_bytes(iotwireless, "1.2.3.4"))["properties"]+ assert properties["horizontalAccuracy"] == 1000000+ assert properties["horizontalConfidenceLevel"] == 0.67++[email protected]("percent,level", [(50, 0.5), (68, 0.68), (99, 0.99)])+def test_iotwireless_confidence_percent_drives_the_confidence_level(+ iotwireless, percent, level+):+ """`ConfidencePercent` is documented as the confidence level of the+ estimate expressed as a percentage, so the caller's value is the level+ the payload reports, over 100. 68 is the default AWS documents for the+ member, and asking for it gets it."""+ properties = json.loads(_estimate_bytes(+ iotwireless, "1.2.3.4",+ AdvancedConfiguration={"WiFiCellular": {"ConfidencePercent": percent}},+ ))["properties"]+ assert properties["horizontalConfidenceLevel"] == level++[email protected]("percent", [100, 1000])+def test_iotwireless_confidence_percent_above_the_range_is_refused(+ iotwireless, percent+):+ """The model constrains the member to 50..99 inclusive. botocore checks+ the minimum client-side but not the maximum, so a value above the range+ is the one an SDK caller can still put on the wire; the below-minimum+ half is covered by the raw-wire test."""+ with pytest.raises(ClientError) as excinfo:+ iotwireless.get_position_estimate(+ Ip={"IpAddress": "1.2.3.4"},+ AdvancedConfiguration={"WiFiCellular": {"ConfidencePercent": percent}},+ )+ error = excinfo.value.response["Error"]+ assert error["Code"] == "ValidationException"+ assert error["Message"] == (+ "AdvancedConfiguration.WiFiCellular.ConfidencePercent must be an "+ "integer from 50 to 99"+ )+++def test_iotwireless_same_ip_answers_identical_bytes(iotwireless):+ """With a `Timestamp` the whole blob is a function of the request, so a+ consumer test can assert on the bytes."""+ first = _estimate_bytes(iotwireless, "5.6.7.8", Timestamp=_TIMESTAMP)+ second = _estimate_bytes(iotwireless, "5.6.7.8", Timestamp=_TIMESTAMP)+ assert first == second+++def test_iotwireless_same_ip_answers_the_same_estimate(iotwireless):+ """Without a `Timestamp` everything but the resolve time still repeats."""+ first = _estimate_without_timestamp(iotwireless, "5.6.7.8")+ second = _estimate_without_timestamp(iotwireless, "5.6.7.8")+ assert first == second+++def test_iotwireless_equivalent_ip_spellings_answer_identical_bytes(iotwireless):+ """The hash runs over the canonical address, not the raw string."""+ assert _estimate_bytes(+ iotwireless, "2600::1", Timestamp=_TIMESTAMP+ ) == _estimate_bytes(iotwireless, "2600:0:0:0:0:0:0:1", Timestamp=_TIMESTAMP)+ # An IPv4-mapped IPv6 address is the IPv4 address.+ assert _estimate_bytes(+ iotwireless, "::ffff:1.2.3.4", Timestamp=_TIMESTAMP+ ) == _estimate_bytes(iotwireless, "1.2.3.4", Timestamp=_TIMESTAMP)+++def test_iotwireless_different_ips_answer_different_coordinates(iotwireless):+ first = json.loads(_estimate_bytes(iotwireless, "5.6.7.8"))+ second = json.loads(_estimate_bytes(iotwireless, "1.2.3.4"))+ assert first["coordinates"] != second["coordinates"]++[email protected]("member", sorted(_NON_IP_MEMBERS))+def test_iotwireless_non_ip_members_do_not_move_the_estimate(iotwireless, member):+ """Each non-Ip member is accepted and none of them resolves the position.+ `Timestamp` is the one that leaves a trace: AWS documents it as the time+ the position is resolved, so it reaches `properties.timestamp`, which the+ comparison drops on both sides. Nothing else may differ."""+ with_member = _estimate_without_timestamp(+ iotwireless, "5.6.7.8", **{member: _NON_IP_MEMBERS[member]}+ )+ assert with_member == _estimate_without_timestamp(iotwireless, "5.6.7.8")+++def test_iotwireless_timestamp_is_echoed_into_the_properties(iotwireless):+ """AWS documents `Timestamp` as the time at which the position is+ resolved, and the live payload reports that time in `properties`. The+ request's value is echoed, so the blob stays a function of the input."""+ document = json.loads(+ _estimate_bytes(iotwireless, "5.6.7.8", Timestamp=_TIMESTAMP)+ )+ assert document["properties"]["timestamp"] == _TIMESTAMP_RENDERED+++def test_iotwireless_timestamp_absent_is_the_receive_time(iotwireless):+ """AWS documents the member as "if not specified, the time at which the+ request was received will be used", the developer guide describes the+ payload's `timestamp` as the time the location was resolved, and both+ documented sample payloads carry it, so it is never left out."""+ before = datetime.now(timezone.utc).replace(microsecond=0)+ document = json.loads(_estimate_bytes(iotwireless, "5.6.7.8"))+ after = datetime.now(timezone.utc)+ resolved = datetime.fromisoformat(+ document["properties"]["timestamp"].replace("Z", "+00:00")+ )+ assert before <= resolved <= after+++def test_iotwireless_coordinates_clamped_to_half_open_intervals():+ """Hashes landing in [179.99995, 180) / [59.99995, 60) would round to+ exactly 180.0 / 60.0, so the clamp keeps the documented half-open+ intervals. Both addresses were searched to hit the raw rounding edge."""+ from ministack.services.iotwireless import _coordinates_for++ lon, _ = _coordinates_for("166.199.146.1")+ assert lon == 179.9999+ _, lat = _coordinates_for("66.72.68.1")+ assert lat == 59.9999+++ "ip", ["203.0.113.7", "10.0.0.1", "::1", "224.0.0.1", "ff02::1"]+)+def test_iotwireless_unresolvable_ip_is_resource_not_found(iotwireless, ip):+ """A valid but non-global (or multicast) address is refused the way the+ real service refuses an address its geo database cannot place (measured+ verbatim with TEST-NET 203.0.113.7 in eu-west-1)."""+ with pytest.raises(ClientError) as excinfo:+ iotwireless.get_position_estimate(Ip={"IpAddress": ip})+ error = excinfo.value.response["Error"]+ assert error["Code"] == "ResourceNotFoundException"+ assert error["Message"] == f"Cannot find position for the IP address {ip}"+++def test_iotwireless_invalid_ip_is_validation_exception(iotwireless):+ """Wording measured verbatim on the live service."""+ with pytest.raises(ClientError) as excinfo:+ iotwireless.get_position_estimate(Ip={"IpAddress": "not-an-ip"})+ error = excinfo.value.response["Error"]+ assert error["Code"] == "ValidationException"+ assert error["Message"] == (+ "1 validation error detected: IP Address is not valid."+ )+++def test_iotwireless_empty_input_is_validation_exception(iotwireless):+ """No resolver hint at all. Wording measured verbatim on the live+ service."""+ with pytest.raises(ClientError) as excinfo:+ iotwireless.get_position_estimate()+ error = excinfo.value.response["Error"]+ assert error["Code"] == "ValidationException"+ assert error["Message"] == (+ "1 validation error detected: Request must have at least 1 valid "+ "position measurement."+ )+++def test_iotwireless_timestamp_only_input_is_validation_exception(iotwireless):+ """The developer guide lists "the payload contains only the timestamp+ information" as a cause of the documented 400, so `Timestamp` is not a+ measurement. Only the class is pinned; the live wording for this input+ is unmeasured."""+ with pytest.raises(ClientError) as excinfo:+ iotwireless.get_position_estimate(Timestamp=_TIMESTAMP)+ assert excinfo.value.response["Error"]["Code"] == "ValidationException"+++def test_iotwireless_non_ip_hints_alone_are_resource_not_found(iotwireless):+ """Documented divergence: MiniStack resolves from Ip only, so an input+ carrying nothing but WLAN measurements is refused with a message naming+ the IP-only scope (the real service would run the third-party solver).+ The input is well formed, and AWS documents 404 for a measurement it+ cannot solve and 400 for measurement data formatted incorrectly, so the+ scope limit refuses like the address the resolver cannot place."""+ with pytest.raises(ClientError) as excinfo:+ iotwireless.get_position_estimate(+ WiFiAccessPoints=[{"MacAddress": "A0:EC:F9:1E:32:C1", "Rss": -75}]+ )+ response = excinfo.value.response+ assert response["ResponseMetadata"]["HTTPStatusCode"] == 404+ assert response["Error"]["Code"] == "ResourceNotFoundException"+ assert "Ip only" in response["Error"]["Message"]+++# ---------------------------------------------------------------------------+# Raw wire (unsigned, like curl)+# ---------------------------------------------------------------------------++def test_iotwireless_unsigned_raw_post_answers_the_bare_geojson_blob(iotwireless):+ """No Authorization header: the POST-only path rule routes it, and the+ body is the raw GeoJSON Point with no envelope key, byte-identical to+ what the SDK client streams."""+ status, content_type, body = _raw(+ "/position-estimate",+ json.dumps({+ "Ip": {"IpAddress": "1.2.3.4"},+ # A Unix timestamp, the wire form boto3 sends the member in, so+ # the two answers are comparable byte for byte.+ "Timestamp": _TIMESTAMP.timestamp(),+ }).encode(),+ )+ assert status == 200+ assert content_type == "application/octet-stream"+ document = json.loads(body)+ assert document["type"] == "Point"+ assert "GeoJsonPayload" not in document+ assert body == _estimate_bytes(iotwireless, "1.2.3.4", Timestamp=_TIMESTAMP)+++def test_iotwireless_raw_timestamp_may_be_the_number_as_a_string(iotwireless):+ """A hand-written request may spell the Unix timestamp as a JSON string.+ That is the same timestamp, so it resolves to the instant boto3 sends the+ member as, byte for byte."""+ status, _content_type, body = _raw(+ "/position-estimate",+ json.dumps({+ "Ip": {"IpAddress": "1.2.3.4"},+ "Timestamp": str(_TIMESTAMP.timestamp()),+ }).encode(),+ )+ assert status == 200+ assert body == _estimate_bytes(iotwireless, "1.2.3.4", Timestamp=_TIMESTAMP)++[email protected]("value", [+ "2026-08-26T14:06:11Z", # ISO-8601 is not a Unix timestamp+ "not-a-timestamp",+ True,+ None,+ [],+ {},+ 1e30, # beyond the range of a date+])+def test_iotwireless_raw_timestamp_that_is_not_a_timestamp_is_refused(value):+ """AWS models `Timestamp` as a timestamp in Unix timestamp format, so a+ value that is not one is measurement data formatted incorrectly, the+ documented 400. Only raw HTTP can send this: boto3 serializes the member+ from a datetime."""+ status, _content_type, raw = _raw(+ "/position-estimate",+ json.dumps({"Ip": {"IpAddress": "1.2.3.4"}, "Timestamp": value}).encode(),+ )+ assert status == 400+ document = json.loads(raw)+ assert document["__type"] == "ValidationException"+ assert document["message"] == (+ "Timestamp must be a Unix timestamp, in seconds since the epoch"+ )++[email protected]("advanced", [+ {"WiFiCellular": {"ConfidencePercent": 49}}, # below the model minimum+ {"WiFiCellular": {"ConfidencePercent": 0}},+ {"WiFiCellular": {"ConfidencePercent": "90"}}, # an integer member+ {"WiFiCellular": {"ConfidencePercent": 90.5}},+ {"WiFiCellular": {"ConfidencePercent": True}},+ {"WiFiCellular": []},+ "not-an-object",+])+def test_iotwireless_raw_advanced_configuration_must_be_the_shape(advanced):+ """`ConfidencePercent` is modelled as an integer from 50 to 99 inside two+ structures, so a value below the range or of another type never reaches+ the confidence level. The SDK refuses all of these before the wire (it+ checks types and the documented minimum), so only raw HTTP gets here."""+ status, _content_type, raw = _raw(+ "/position-estimate",+ json.dumps({+ "Ip": {"IpAddress": "1.2.3.4"},+ "AdvancedConfiguration": advanced,+ }).encode(),+ )+ assert status == 400+ document = json.loads(raw)+ assert document["__type"] == "ValidationException"+ assert "ConfidencePercent" in document["message"]++[email protected]("ip_member", [{}, {"IpAddress": ""}])+def test_iotwireless_raw_ip_without_an_address_is_not_valid(ip_member):+ """An `Ip` member that carries no usable address is a present hint, so it+ reaches the address validator rather than the no-measurement branch. The+ SDK cannot send this (`IpAddress` is a required member), only raw HTTP+ can."""+ status, _content_type, raw = _raw(+ "/position-estimate", json.dumps({"Ip": ip_member}).encode()+ )+ assert status == 400+ document = json.loads(raw)+ assert document["__type"] == "ValidationException"+ assert document["message"] == (+ "1 validation error detected: IP Address is not valid."+ )++[email protected]("body", [+ b"[]", # a JSON array, not an object+ b'{"Ip": "1.2.3.4"}', # Ip is not an object+ b"not json",+])+def test_iotwireless_raw_malformed_input_is_validation_exception(body):+ status, _content_type, raw = _raw("/position-estimate", body)+ assert status == 400+ assert json.loads(raw)["__type"] == "ValidationException"+++def test_iotwireless_unknown_route_is_validation_exception():+ """An unknown path is 400 ValidationException "No route for ...", like+ the neighbouring REST-JSON services. The request carries the+ `iotwireless` credential scope so the router hands it to the service."""+ req = urllib.request.Request(+ f"{ENDPOINT}/no-such-operation", data=b"{}", method="POST",+ headers={+ "content-type": "application/json",+ "Authorization": (+ "AWS4-HMAC-SHA256 "+ "Credential=test/20260811/us-east-1/iotwireless/aws4_request, "+ "SignedHeaders=host, Signature=fake"+ ),+ },+ )+ try:+ with urllib.request.urlopen(req, timeout=5) as resp:+ status, raw = resp.status, resp.read()+ except urllib.error.HTTPError as e:+ status, raw = e.code, e.read()+ assert status == 400+ assert json.loads(raw)["__type"] == "ValidationException"diff --git a/tests/test_router.py b/tests/test_router.pyindex 7cee7f03..13513bf4 100644--- a/tests/test_router.py+++ b/tests/test_router.py@@ -280,6 +280,50 @@ def test_foreign_hosts_are_not_routed_by_service_token(host):assert detect_service("GET", "/status", {"host": host}, {}) == "s3"+def test_iotwireless_credential_scope_routes():+ """boto3 signs GetPositionEstimate with the `iotwireless` scope+ (botocore signingName); the scope early-return resolves it directly."""+ assert detect_service(+ "POST", "/position-estimate", _sigv4_headers("iotwireless"), {}+ ) == "iotwireless"+++ "host",+ [+ # The real endpoint prefix: api.iotwireless.{region}.+ "api.iotwireless.us-east-1.localhost:4566",+ "iotwireless.us-east-1.localhost:4566",+ ],+)+def test_iotwireless_host_routes(host):+ assert detect_service(+ "POST", "/position-estimate", {"host": host}, {}+ ) == "iotwireless"+++def test_iotwireless_host_does_not_disturb_iot_family():+ """`api.iotwireless.` never contains the literal `iot.` segment, so there+ is no overlap with the iot control-plane regex in either direction — pin+ that the iot family still resolves as before."""+ assert detect_service(+ "GET", "/things", {"host": "iot.us-east-1.localhost:4566"}, {}+ ) == "iot"+ assert detect_service(+ "GET",+ "/things/t1/jobs/$next",+ {"host": "a1b2c3.jobs.iot.us-east-1.localhost:4566"},+ {},+ ) == "iot-jobs-data"+++def test_iotwireless_unsigned_path_routes_post_only():+ """An unsigned POST resolves by path; a GET of the same path stays on the+ S3 fallback (an object may legitimately be named `position-estimate`)."""+ assert detect_service("POST", "/position-estimate", _HEADERS, {}) == "iotwireless"+ assert detect_service("GET", "/position-estimate", _HEADERS, {}) == "s3"++@pytest.mark.parametrize(("host", "expected"), [("s3.ministack:4566", "s3"),("iot.localhost:4566", "iot"),