Skip to content

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

feat(location): trackers, device positions and AWS::Location::Tracker (#1664)

iot-rocket7bbd8ee2c1de
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c4e5e120..f8829868 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.
+- **Amazon Location — trackers and device positions, with `AWS::Location::Tracker`** — the service did not exist. `CreateTracker`, `DescribeTracker`, `UpdateTracker`, `ListTrackers` and `DeleteTracker` manage trackers; `BatchUpdateDevicePosition`, `GetDevicePosition`, `BatchGetDevicePosition` and `GetDevicePositionHistory` serve device positions, with the modeled wire shapes (`geo` signing scope, ISO 8601 timestamps, `Position` as the `[lon, lat]` pair, per-entry `Errors` for out-of-range coordinates, `NextToken` paging, the last 24 hours as the history default). `PositionFiltering` applies: `TimeBased` (the default) stores one sample per 30 seconds per device, `DistanceBased` ignores a move under 30 m and `AccuracyBased` a move under the two updates' measured accuracy, and a filtered update is not an error. The documented request constraints are checked before the tracker is looked up, so an invalid request naming a tracker that does not exist answers the `ValidationException`, not the 404, and `TrackerName` is held to its 1..100 length and to the ASCII the service-side Java `[-._\w]+` means, in the URL as well as in a body; `Accuracy` is the modeled `PositionalAccuracy`, whose required `Horizontal` runs 0..10000000 metres and can no longer arrive negative under the `AccuracyBased` filter it feeds; every `DeviceId` is the modeled `Id`, in an update, in a `DeviceIds` list and in the URL alike; a `GetDevicePositionHistory` window bound that is not a timestamp is refused instead of falling back to the 24-hour default. Positions are kept in memory, the newest 100 per device, rather than for the service's 30 days; `KmsKeyId`, `EventBridgeEnabled` and `Tags` are stored without effect; no consumers, geofences, maps, places or routes. The CloudFormation resource `Ref`s the name, exposes `Arn`/`TrackerArn`/`CreateTime`/`UpdateTime`, updates in place and receives the stack tags. Contributed by @iot-rocket.
- **AWS Signer — synchronous `StartSigningJob` with the S3 side effect** — the `signer` API did not exist. `StartSigningJob`, `DescribeSigningJob`, `ListSigningJobs`, `PutSigningProfile` and `GetSigningProfile` are served natively (REST-JSON). Signing is synchronous and synthetic: Start validates the source object against the local S3 store, writes a JSON marker (source reference + SHA-256 of the source bytes) to `destination.prefix + jobId` (`.zip` appended for a `.zip` source on the Lambda platform, as measured) and returns the job already `Succeeded`; a missing source, destination bucket or profile is `ResourceNotFoundException` at Start with no job recorded. `clientRequestToken` replays the first response. Jobs carry the profile's signing material and a `signatureExpiresAt`; list filters and the documented input constraints are enforced, and `ListSigningJobs` pages with a `nextToken` that is bound to the filters it was minted with. The unsigned path rules leave path-style S3 traffic for a bucket named `signing-jobs` alone unless the request looks like signer's own surface, and a job records the IAM principal that started it rather than the account root. `signatureValidityPeriod` follows the model, where both members are optional, and the documented constraints on `overrides`, `signingMaterial`, `tags`, `jobInvoker` and `profileOwner` are enforced instead of stored as sent. State persists with `PERSIST_STATE=1`. 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.
diff --git a/README.md b/README.md
index 2efecc66..4a775177 100644
--- a/README.md
+++ b/README.md
@@ -445,6 +445,7 @@ subnet = ec2.create_subnet(
| **Cost & Usage Reports** | DeleteReportDefinition, DescribeReportDefinitions, ListTagsForResource, ModifyReportDefinition, PutReportDefinition, TagResource, UntagResource | 7 of 7 spec ops |
| **Inspector2** | Enable, Disable, ListFindings, BatchGetFindingDetails, ListCoverage, ListCoverageStatistics, ListFindingAggregations, SearchVulnerabilities, TagResource, UntagResource, ListTagsForResource, CreateFilter, ListFilters, DeleteFilter | 14 operations; deterministic stub vulnerability findings for ECR images, Lambda functions, and EC2 instances; filtering, sorting, pagination |
| **AmazonMQ** | CreateBroker, ListBrokers, DescribeBrokers, DeleteBrokers, UpdateBroker, RebootBroker, DescribeBrokerEngineTypes, DescribeBrokerInstanceOptions, CreateTags, ListTags, DeleteTags, CreateUser, DeleteUser, ListUsers, UpdateUser, DescribeUser | 16 of 24 spec ops; No real container support |
+| **Amazon Location (trackers)** | CreateTracker, DescribeTracker, UpdateTracker, ListTrackers, DeleteTracker, BatchUpdateDevicePosition, GetDevicePosition, BatchGetDevicePosition, GetDevicePositionHistory | Tracker control plane + in-memory device-position store; signs with credential scope `geo` (the client is named `location`); ISO 8601 `SampleTime`/`ReceivedTime`, `Position` as the modeled `[lon, lat]` double pair, out-of-range coordinates as per-entry `Errors`; `GetDevicePositionHistory` ascending, defaulting to the last 24 h; `ListTrackers` and the history page at `MaxResults` 1..100 with `NextToken`; every sample is stored (no position filtering, no 30-day expiry), newest 100 per device; `KmsKeyId`/`PositionFiltering`/`EventBridgeEnabled`/`Tags` stored without effect; no consumers, geofences, maps, places or routes; CFN `AWS::Location::Tracker` supported |
@@ -560,6 +561,7 @@ subnet = ec2.create_subnet(
| `AWS::AutoScaling::ScheduledAction` | Action ARN | Arn, ScheduledActionName |
| `AWS::Scheduler::Schedule` | Schedule name | Arn |
| `AWS::Scheduler::ScheduleGroup` | Group name | Arn |
+| `AWS::Location::Tracker` | Tracker name | Arn, TrackerArn, CreateTime, UpdateTime |
| `AWS::CloudFormation::WaitCondition` | Condition ID | Data, Id |
| `AWS::CloudFormation::WaitConditionHandle` | Signal URL | Id |
| `AWS::CloudFormation::Stack` (nested) | Child stack ARN | `Outputs.<Name>` — each child stack Output |
diff --git a/ministack/app.py b/ministack/app.py
index 27f0f2d6..2f3daab3 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -376,6 +376,7 @@ SERVICE_REGISTRY = {
"kms": {"module": "kms"},
"lambda": {"module": "lambda_svc"},
"lambda-microvms": {"module": "lambda_microvms"},
+ "location": {"module": "location"},
"logs": {"module": "cloudwatch_logs", "aliases": ("cloudwatch-logs",)},
"mediaconnect": {"module": "mediaconnect"},
"opensearch": {"module": "opensearch", "aliases": ("es", "elasticsearch")},
@@ -485,6 +486,7 @@ _state_map = {
"iot": "iot",
"inspector2": "inspector2",
"dsql": "dsql",
+ "location": "location",
"mediaconnect": "mediaconnect",
"mq": "mq",
"signer": "signer",
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index 7106b0c0..6a2cb651 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -79,6 +79,7 @@ SERVICE_TO_IAM_NAMESPACE: dict[str, str] = {
"kms": "kms",
"lambda": "lambda",
"lambda-microvms": "lambda",
+ "location": "geo",
"logs": "logs",
"mediaconnect": "mediaconnect",
"monitoring": "cloudwatch",
@@ -444,6 +445,7 @@ _BOTOCORE_SERVICE_MAP: dict[str, list[str]] = {
"iot-jobs-data": ["iot-jobs-data"],
"iotwireless": ["iotwireless"],
"kafka": ["kafka"],
+ "location": ["location"],
"mediaconnect": ["mediaconnect"],
"mq": ["mq"],
"airflow": ["mwaa"],
@@ -1230,6 +1232,15 @@ def extract_resource_arn(service: str, method: str, path: str,
return f"arn:aws:pipes:{region}:{account_id}:pipe/{parts[pi + 1]}"
return "*"
+ if service == "location":
+ # /tracking/v0/trackers/{TrackerName}[/...]; the ARN service is geo.
+ parts = [p for p in path.split("/") if p]
+ if "trackers" in parts:
+ ti = parts.index("trackers")
+ if ti + 1 < len(parts):
+ return f"arn:aws:geo:{region}:{account_id}:tracker/{parts[ti + 1]}"
+ return "*"
+
if service == "mq":
parts = [p for p in path.split("/") if p]
if "brokers" in parts:
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 2ca1996e..3dabc203 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -424,6 +424,19 @@ SERVICE_PATTERNS = {
"host_patterns": [r"^mediaconnect\."],
"credential_scope": "mediaconnect",
},
+ # Amazon Location: the client is named `location` but the endpoint prefix
+ # and credential scope are `geo` (botocore signingName), and the modeled
+ # per-operation host prefixes put `cp.tracking.` / `tracking.` in front of
+ # it — so the host reads `cp.tracking.geo.{region}.{host}`. `geo` starts
+ # its own label there, so the token still matches once
+ # `_anchored_host_pattern` anchors it at a label start; no other service's
+ # host carries a `geo` label, so ordering is not sensitive. Under an
+ # endpoint override the host carries no `geo.` at all and routing relies
+ # on the `"geo"` entry in the credential-scope map below.
+ "location": {
+ "host_patterns": [r"geo\."],
+ "credential_scope": "geo",
+ },
"tagging": {
"target_prefixes": ["ResourceGroupsTaggingAPI_20170126"],
"host_patterns": [r"tagging\."],
@@ -753,6 +766,11 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"appconfigdata": "appconfigdata",
"scheduler": "scheduler",
"eks": "eks",
+ # Amazon Location signs with scope `geo`, not `location`
+ # (botocore signingName). With an endpoint override the host
+ # has no `geo.` in it, so this entry is the primary routing
+ # signal for the location service.
+ "geo": "location",
"mediaconnect": "mediaconnect",
"tagging": "tagging",
"resource-groups": "resource-groups",
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 84bbd12b..b0e88a2a 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -426,6 +426,11 @@ _CUSTOM_NAME_REPLACEMENT = {
"name": "ThingGroupName",
"requires_replacement": lambda old, new: old.get("ParentGroupName") != new.get("ParentGroupName"),
},
+ # KmsKeyId is "Update requires: Replacement" in the resource reference.
+ "AWS::Location::Tracker": {
+ "name": "TrackerName",
+ "requires_replacement": lambda old, new: old.get("KmsKeyId") != new.get("KmsKeyId"),
+ },
}
@@ -624,6 +629,7 @@ _STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {
"AWS::KMS::Key": ("Tags", "list"),
"AWS::Kinesis::Stream": ("Tags", "list"),
"AWS::Lambda::Function": ("Tags", "list"),
+ "AWS::Location::Tracker": ("Tags", "list"),
"AWS::Logs::LogGroup": ("Tags", "list"),
"AWS::OpenSearchService::Domain": ("Tags", "list"),
"AWS::RDS::DBInstance": ("Tags", "list"),
@@ -8523,6 +8529,105 @@ def _scheduler_schedule_update(physical_id, old_props, new_props, stack_name):
schedule[prop] = new_props[prop]
return physical_id, {"Arn": _sched._schedule_arn(group, physical_id)}
+
+# --- Amazon Location (AWS::Location::Tracker) ---
+
+# The properties the resource reference marks "No interruption", applied
+# through UpdateTracker, with the value a property reverts to when the
+# template drops it: the service's CreateTracker defaults, or None for a
+# member a fresh create leaves absent (it is removed from the record).
+# TrackerName and KmsKeyId require replacement; Tags are reconciled on the
+# tracker record.
+_LOCATION_TRACKER_UPDATABLE = {
+ "Description": "",
+ "PositionFiltering": "TimeBased",
+ "EventBridgeEnabled": False,
+ "KmsKeyEnableGeospatialQueries": None,
+}
+
+
+def _location_tracker_body(name, props):
+ """The CreateTracker request for a template's properties: both sides are
+ PascalCase, only Tags changes shape (CloudFormation's Key/Value list, the
+ API's map)."""
+ body = {"TrackerName": name}
+ for prop in ("Description", "PositionFiltering", "EventBridgeEnabled",
+ "KmsKeyId", "KmsKeyEnableGeospatialQueries"):
+ if prop in props:
+ body[prop] = props[prop]
+ if "Tags" in props:
+ body["Tags"] = _tag_map(props["Tags"])
+ return body
+
+
+def _location_tracker_attrs(rec):
+ import ministack.services.location as _location
+ return {
+ "Arn": rec["TrackerArn"],
+ "TrackerArn": rec["TrackerArn"],
+ "CreateTime": _location._iso(rec["CreateTime"]),
+ "UpdateTime": _location._iso(rec["UpdateTime"]),
+ }
+
+
+def _location_tracker_create(logical_id, props, stack_name):
+ import ministack.services.location as _location
+ name = props.get("TrackerName") or _physical_name(stack_name, logical_id, max_len=100)
+ resp = _location._create_tracker(_location_tracker_body(name, props))
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::Location::Tracker create failed: {resp[2]!r}")
+ return name, _location_tracker_attrs(_location._trackers[name])
+
+
+def _location_tracker_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Description, PositionFiltering, EventBridgeEnabled and
+ KmsKeyEnableGeospatialQueries update in place through UpdateTracker and a
+ Tags change is reconciled on the record. TrackerName and KmsKeyId require
+ replacement
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-tracker.html):
+ a renamed tracker is created before the old one, with its device
+ positions, is removed; a KmsKeyId change re-creates an auto-named
+ tracker under its deterministic physical name (the name is reused, so
+ the predecessor cannot be retained, as for a DynamoDB table), and with
+ an explicit, unchanged TrackerName it is refused by the
+ _CUSTOM_NAME_REPLACEMENT rule."""
+ import ministack.services.location as _location
+ name = new_props.get("TrackerName") or _physical_name(
+ stack_name, logical_id or physical_id, max_len=100
+ )
+ rec = _location._trackers.get(physical_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ name, physical_id if rec is not None else None,
+ _location_tracker_create, _location_tracker_delete,
+ )
+ if replaced is not None:
+ return replaced
+ if old_props.get("KmsKeyId") != new_props.get("KmsKeyId"):
+ _location_tracker_delete(physical_id, old_props)
+ return _location_tracker_create(logical_id or physical_id, new_props, stack_name)
+ changes = {}
+ for prop, default in _LOCATION_TRACKER_UPDATABLE.items():
+ if prop in new_props:
+ changes[prop] = new_props[prop]
+ elif prop in old_props:
+ if default is None:
+ rec.pop(prop, None)
+ else:
+ changes[prop] = default
+ resp = _location._update_tracker(name, changes)
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::Location::Tracker update failed: {resp[2]!r}")
+ _reconcile_tag_map(rec.setdefault("Tags", {}), old_props, new_props)
+ return name, _location_tracker_attrs(rec)
+
+
+def _location_tracker_delete(physical_id, props):
+ import ministack.services.location as _location
+ _location._delete_tracker(physical_id)
+
+
_RESOURCE_HANDLERS = {
"AWS::OpenSearchService::Domain": {
"create": _opensearch_domain_create,
@@ -8923,6 +9028,13 @@ _RESOURCE_HANDLERS = {
# EventBridge Scheduler
"AWS::Scheduler::Schedule": {"create": _scheduler_schedule_create, "update": _scheduler_schedule_update, "delete": _scheduler_schedule_delete},
"AWS::Scheduler::ScheduleGroup": {"create": _scheduler_group_create, "delete": _scheduler_group_delete},
+ # Amazon Location
+ "AWS::Location::Tracker": {
+ "create": _location_tracker_create,
+ "update": _location_tracker_update,
+ "update_with_logical_id": True,
+ "delete": _location_tracker_delete,
+ },
# EKS
"AWS::EKS::Cluster": {"create": _eks_cluster_create, "delete": _eks_cluster_delete},
"AWS::EKS::Nodegroup": {"create": _eks_nodegroup_create, "delete": _eks_nodegroup_delete},
diff --git a/ministack/services/location.py b/ministack/services/location.py
new file mode 100644
index 00000000..fa64c9e9
--- /dev/null
+++ b/ministack/services/location.py
@@ -0,0 +1,974 @@
+# 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).
+"""
+Amazon Location Service emulator — trackers only.
+REST/JSON protocol — /tracking/v0/* paths.
+
+Routing note: the SDK client is named ``location`` but signs with credential
+scope ``geo`` (botocore signingName), and the modeled endpoint host prefixes
+(``cp.tracking.`` for the tracker control plane, ``tracking.`` for the device
+position data plane) sit in front of the ``geo.{region}`` endpoint — so a
+request arrives with host ``cp.tracking.geo.{region}.{host}`` or, under an
+endpoint override, with only the ``geo`` credential scope to go by. See
+``SERVICE_PATTERNS["location"]`` and the ``"geo"`` scope-map entry in
+``core/router.py``.
+
+Wire traps, verified against the botocore ``location`` 2020-11-19 model:
+ * ``SampleTime`` / ``ReceivedTime`` / ``CreateTime`` / ``UpdateTime`` are
+ ``timestamp`` shapes with an explicit ``timestampFormat: iso8601`` — the
+ SDK SENDS ISO8601 strings, and responses here emit ISO8601 UTC strings,
+ which botocore's lenient timestamp parser turns back into datetimes (it
+ also accepts epoch numbers, so both are tolerated on the way in; the
+ store keeps a canonical epoch-seconds float).
+ * ``Position`` is a modeled double list of exactly two members,
+ ``[longitude, latitude]`` — not an object.
+
+Supports:
+ Trackers: CreateTracker, DescribeTracker, UpdateTracker, ListTrackers,
+ DeleteTracker
+ Positions: BatchUpdateDevicePosition, GetDevicePosition,
+ BatchGetDevicePosition, GetDevicePositionHistory
+
+Scope boundaries (metadata-only control plane + in-memory position store):
+ * ``KmsKeyId``, ``KmsKeyEnableGeospatialQueries``, ``PositionFiltering``,
+ ``EventBridgeEnabled`` and ``Tags`` are stored and echoed but have no
+ behavior — no KMS encryption and no EventBridge position events. The
+ deprecated ``PricingPlan`` always reads ``RequestBasedUsage`` (documented,
+ and on the live DescribeTracker of 2026-08-26); ``PricingPlanDataSource``
+ is not returned, because it was absent from that live describe although
+ the reference says "Always returns an empty string". Position
+ filtering is a stated divergence: real ``TimeBased`` filtering stores at
+ most one position per 30 seconds per device and retains position data
+ for 30 days; MiniStack stores every accepted sample and instead bounds
+ per-device history at the newest 100 samples (oldest dropped first).
+ * ``ListTrackers`` and ``GetDevicePositionHistory`` page at ``MaxResults``
+ (1..100, default 100) with a ``NextToken`` carrying the sort position of
+ the last item returned.
+ * The documented member constraints are refused with a
+ ``ValidationException`` before the request is processed — before the
+ tracker is looked up, so an invalid request naming a tracker that does
+ not exist answers 400, the way a real request-validation layer sitting in
+ front of the operation does, not 404: ``Description``
+ 0..1000, ``KmsKeyId`` 1..2048, ``Tags`` at most 50 entries with keys
+ 1..128 and values 0..256 on the tag pattern, ``PositionProperties`` at
+ most 4 entries with keys 1..20 and values 1..150, ``Accuracy`` a
+ structure whose required ``Horizontal`` runs 0..10000000, and every
+ ``DeviceId`` — in an update, in a ``DeviceIds`` list or in the path — the
+ modeled ``Id``: 1..100 on ``[-._\\p{L}\\p{N}]+``. The message wordings are
+ unmeasured.
+ * ``BatchUpdateDevicePosition`` answers a structurally invalid entry (a
+ required member missing, ``Position`` not two numbers) with a
+ request-level ``ValidationException``; the per-entry ``Errors`` list is
+ kept for the measured value-range case. ``BatchGetDevicePosition`` omits
+ a device without a position and returns ``Errors: []``, as the live
+ service did (2026-08-26).
+ * No geofence-collection consumers (``AssociateTrackerConsumer`` et al.),
+ and no maps / places / routes APIs.
+ * ``GetDevicePositionHistory`` returns samples in ascending ``SampleTime``
+ order.
+"""
+
+import base64
+import copy
+import datetime
+import json
+import logging
+import math
+import re
+import time
+import unicodedata
+import urllib.parse
+
+from ministack.core.persistence import load_state
+from ministack.core.responses import (
+ AccountRegionScopedDict,
+ error_response_json,
+ get_account_id,
+ get_region,
+ json_response,
+)
+
+logger = logging.getLogger("location")
+
+# Newest samples kept per device for GetDevicePositionHistory (oldest dropped).
+_HISTORY_LIMIT = 100
+
+# ---------------------------------------------------------------------------
+# State
+# ---------------------------------------------------------------------------
+
+# TrackerName -> tracker record. Each record carries its own device-position
+# store under "positions": {DeviceId: {"latest": <position>, "history": [...]}}
+# where a position is {"DeviceId", "SampleTime": float, "ReceivedTime": float,
+# "Position": [lon, lat], "Seq": int, "Accuracy"?, "PositionProperties"?}.
+_trackers = AccountRegionScopedDict()
+
+# A monotonic counter stamped on every stored sample as "Seq". It is the last
+# component of the history sort key, so two samples that share SampleTime and
+# ReceivedTime still have a total order. Without it a NextToken pointing at one
+# of them would resume with a strict ">" that also excludes the other, and the
+# sample behind the page boundary would never be returned.
+_sequence = 0
+
+
+def _next_sequence():
+ global _sequence
+ _sequence += 1
+ return _sequence
+
+
+def reset():
+ global _sequence
+ _trackers.clear()
+ _sequence = 0
+
+
+def get_state():
+ return {
+ "trackers": copy.deepcopy(_trackers),
+ }
+
+
+def restore_state(data):
+ global _sequence
+ if not data:
+ return
+ _trackers.update(data.get("trackers", {}))
+ # Keep the counter above every restored sample, so a sample stored after
+ # the restore still sorts behind the restored ones.
+ for rec in _trackers.all_values():
+ for device in rec.get("positions", {}).values():
+ for pos in device.get("history", []):
+ _sequence = max(_sequence, pos.get("Seq", 0))
+
+
+try:
+ _restored = load_state("location")
+ if _restored:
+ restore_state(_restored)
+except Exception:
+ logger.exception("Failed to restore persisted location state; continuing fresh")
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _now():
+ return time.time()
+
+
+def _tracker_arn(name):
+ return f"arn:aws:geo:{get_region()}:{get_account_id()}:tracker/{name}"
+
+
+def _error(status, code, message):
+ return error_response_json(code, message, status)
+
+
+def _validation(message):
+ return _error(400, "ValidationException", message)
+
+
+def _constraint(value, field, constraint):
+ """The request-surface ValidationException shape: one violated member
+ constraint. The exact wordings are unmeasured on Amazon Location; the
+ shape is the one the AWS SDKs render for every service."""
+ return _validation(
+ f"1 validation error detected: Value '{value}' at '{field}' failed to "
+ f"satisfy constraint: {constraint}"
+ )
+
+
+def _not_found(name):
+ # This wording was measured on GetDevicePosition against a missing tracker
+ # (2026-08-26). The other tracker operations reuse it; their texts were not
+ # measured.
+ return _error(404, "ResourceNotFoundException", f"Tracker not found: {name}.")
+
+
+def _parse_timestamp(value):
+ """Accept the model's ISO8601 string or an epoch number; return an
+ epoch-seconds float, or None when the value is absent or unparseable."""
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return float(value)
+ if isinstance(value, str):
+ try:
+ parsed = datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=datetime.timezone.utc)
+ return parsed.timestamp()
+ return None
+
+
+def _iso(ts):
+ """Epoch-seconds float -> the model's iso8601 wire form (millisecond
+ precision, `Z` suffix — what real Location emits)."""
+ return (
+ datetime.datetime.fromtimestamp(ts, tz=datetime.timezone.utc)
+ .strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ )
+
+
+def _is_number(value):
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
+
+
+def _max_results(body):
+ """``MaxResults`` (1..100, default 100) as ``(value, error_response)``."""
+ value = body.get("MaxResults")
+ if value is None:
+ return 100, None
+ if not _is_number(value) or int(value) != value:
+ return None, _validation("MaxResults must be an integer")
+ value = int(value)
+ if value > 100:
+ return None, _constraint(
+ value, "maxResults", "Member must have value less than or equal to 100"
+ )
+ if value < 1:
+ return None, _constraint(
+ value, "maxResults", "Member must have value greater than or equal to 1"
+ )
+ return value, None
+
+
+def _time_bound(body, member, default):
+ """A history window bound as ``(value, error_response)``: the documented
+ default when the member is absent, and a ValidationException when it is
+ there but not a timestamp. Substituting the default for an unparseable
+ one would answer a window the caller never asked for, in the same 200 as
+ a window it did."""
+ value = body.get(member)
+ if value is None:
+ return default, None
+ parsed = _parse_timestamp(value)
+ if parsed is None:
+ return None, _validation(f"{member} must be a timestamp")
+ return parsed, None
+
+
+def _encode_token(key):
+ """Tokens carry the sort position of the last item returned, not an
+ index: an offset would skip an item whenever one was deleted between
+ pages and repeat one whenever one was created."""
+ raw = json.dumps(list(key)).encode("utf-8")
+ return base64.urlsafe_b64encode(raw).decode("ascii")
+
+
+def _decode_token(token, casts):
+ """The sort key a token carries, or None when the token is not ours."""
+ try:
+ raw = json.loads(base64.urlsafe_b64decode(token.encode("ascii")).decode("utf-8"))
+ if not isinstance(raw, list) or len(raw) != len(casts):
+ return None
+ return tuple(cast(item) for cast, item in zip(casts, raw))
+ except Exception:
+ return None
+
+
+_INVALID_TOKEN = "The NextToken that you provided is invalid."
+
+
+# The model's ResourceName shape: pattern [-._\w]+, length 1-100 (the length
+# is checked separately so the two constraints report distinctly). The pattern
+# is a Java regex, where \w is [a-zA-Z0-9_]; Python's \w also matches every
+# Unicode letter and digit, so re.ASCII is what makes the two agree. The
+# CreateTracker reference spells the same thing out: a tracker name may
+# "contain only alphanumeric characters (A-Z, a-z, 0-9), hyphens (-), periods
+# (.), and underscores (_)".
+_TRACKER_NAME_RE = re.compile(r"[-._\w]+", re.ASCII)
+
+_POSITION_FILTERING = ("TimeBased", "DistanceBased", "AccuracyBased")
+
+# CreateTracker request members stored verbatim and echoed by DescribeTracker.
+# The deprecated PricingPlan / PricingPlanDataSource are not among them:
+# DescribeTracker documents PricingPlan as "Always returns RequestBasedUsage"
+# and PricingPlanDataSource as "No longer used. Always returns an empty
+# string" — but the live DescribeTracker of 2026-08-26 had no
+# PricingPlanDataSource member at all, and the measurement is what is followed.
+_STORED_OPTIONALS = (
+ "Description", "Tags", "PositionFiltering", "EventBridgeEnabled",
+ "KmsKeyId", "KmsKeyEnableGeospatialQueries",
+)
+
+# Response members the live service always materializes (probed 2026-08-26):
+# DescribeTracker carries these even when CreateTracker omitted them.
+_CREATE_DEFAULTS = {
+ "Description": "",
+ "PricingPlan": "RequestBasedUsage",
+ "Tags": {},
+ "PositionFiltering": "TimeBased",
+ "EventBridgeEnabled": False,
+}
+
+# UpdateTracker's request members that the emulator stores (PricingPlan and
+# PricingPlanDataSource are validated and ignored, as deprecated on AWS).
+_MUTABLE_FIELDS = (
+ "Description", "PositionFiltering", "EventBridgeEnabled",
+ "KmsKeyEnableGeospatialQueries",
+)
+
+
+# The tag key/value pattern of the CreateTracker reference,
+# ``([\p{L}\p{Z}\p{N}_.,:/=+\-@]*)``. The stdlib ``re`` has no Unicode property
+# classes, so the three categories are checked through unicodedata instead:
+# letters (L*), separators (Z*) and numbers (N*), plus these literals.
+_TAG_LITERALS = frozenset("_.,:/=+-@")
+
+
+def _tag_text_ok(value):
+ return all(
+ unicodedata.category(ch)[0] in ("L", "Z", "N") or ch in _TAG_LITERALS
+ for ch in value
+ )
+
+
+# The model's Id shape (DeviceId everywhere it appears), pattern
+# ``([-._\p{L}\p{N}]+)``: the same missing Unicode property classes as the tag
+# pattern above, so letters (L*) and numbers (N*) go through unicodedata too.
+# It carries no separator class, so a device id may not contain a space.
+_DEVICE_ID_LITERALS = frozenset("-._")
+
+
+def _device_id_ok(value):
+ return all(
+ unicodedata.category(ch)[0] in ("L", "N") or ch in _DEVICE_ID_LITERALS
+ for ch in value
+ )
+
+
+def _validate_string_length(body, member, field, minimum, maximum):
+ """A documented string length constraint, checked before the request is
+ processed. The wordings are unmeasured (see ``_constraint``)."""
+ value = body.get(member)
+ if value is None:
+ return None
+ if not isinstance(value, str):
+ return _constraint(value, field, "Member must be a string")
+ if len(value) > maximum:
+ return _constraint(
+ value, field, f"Member must have length less than or equal to {maximum}"
+ )
+ if len(value) < minimum:
+ return _constraint(
+ value, field, f"Member must have length greater than or equal to {minimum}"
+ )
+ return None
+
+
+def _validate_string_map(value, field, max_entries, key_len, value_len, pattern=False):
+ """A documented string-to-string map constraint (Tags on CreateTracker,
+ PositionProperties on a device position update). Wordings unmeasured."""
+ if value is None:
+ return None
+ if not isinstance(value, dict):
+ return _constraint(value, field, "Member must be a map")
+ if len(value) > max_entries:
+ return _constraint(
+ len(value), field,
+ f"Member must have length less than or equal to {max_entries}",
+ )
+ for key, item in value.items():
+ for text, kind, (minimum, maximum) in (
+ (key, "keys", key_len), (item, "values", value_len)
+ ):
+ if not isinstance(text, str):
+ return _constraint(text, field, f"Map {kind} must be a string")
+ if len(text) > maximum:
+ return _constraint(
+ text, field,
+ f"Map {kind} must have length less than or equal to {maximum}",
+ )
+ if len(text) < minimum:
+ return _constraint(
+ text, field,
+ f"Map {kind} must have length greater than or equal to {minimum}",
+ )
+ if pattern and not _tag_text_ok(text):
+ return _constraint(
+ text, field,
+ f"Map {kind} must satisfy regular expression pattern: "
+ r"([\p{L}\p{Z}\p{N}_.,:/=+\-@]*)",
+ )
+ return None
+
+
+def _validate_device_id(value, field):
+ """The model's Id shape: a 1..100 string on ``[-._\\p{L}\\p{N}]+``. Every
+ reference that carries a device id documents it — DevicePositionUpdate,
+ BatchGetDevicePosition, GetDevicePosition, GetDevicePositionHistory —
+ including the ones that take it from the path. Wordings unmeasured."""
+ if not isinstance(value, str):
+ return _constraint(value, field, "Member must be a string")
+ if len(value) > 100:
+ return _constraint(
+ value, field, "Member must have length less than or equal to 100"
+ )
+ if not value:
+ return _constraint(
+ value, field, "Member must have length greater than or equal to 1"
+ )
+ if not _device_id_ok(value):
+ return _constraint(
+ value, field,
+ "Member must satisfy regular expression pattern: "
+ r"([-._\p{L}\p{N}]+)",
+ )
+ return None
+
+
+def _validate_accuracy(value, field):
+ """A documented PositionalAccuracy: the structure's ``Horizontal`` is
+ required and a double in 0..10000000 (API_PositionalAccuracy reference).
+ Wordings unmeasured (see ``_constraint``)."""
+ if value is None:
+ return None
+ if not isinstance(value, dict):
+ return _constraint(value, field, "Member must be a structure")
+ horizontal = value.get("Horizontal")
+ if not _is_number(horizontal):
+ return _constraint(horizontal, f"{field}.horizontal", "Member must not be null")
+ if horizontal > 10000000:
+ return _constraint(
+ horizontal, f"{field}.horizontal",
+ "Member must have value less than or equal to 10000000",
+ )
+ if horizontal < 0:
+ return _constraint(
+ horizontal, f"{field}.horizontal",
+ "Member must have value greater than or equal to 0",
+ )
+ return None
+
+
+def _validate_tracker_name(name):
+ """The model's ResourceName shape: a 1..100 string on ``[-._\\w]+``. Every
+ operation documents it, the path ones included, so a malformed name in the
+ path is a request-validation 400 and never reaches the lookup."""
+ if not isinstance(name, str):
+ return _constraint(name, "trackerName", "Member must be a string")
+ if len(name) > 100:
+ return _constraint(
+ name, "trackerName", "Member must have length less than or equal to 100"
+ )
+ if not _TRACKER_NAME_RE.fullmatch(name):
+ # An unvalidated name with e.g. "/" would be unaddressable through
+ # the path-parameter routes below.
+ return _constraint(
+ name, "trackerName",
+ "Member must satisfy regular expression pattern: [-._\\w]+",
+ )
+ return None
+
+
+def _validate_settings(body):
+ """The members CreateTracker and UpdateTracker share. botocore enforces
+ required members and the minimum of a length or a numeric range
+ client-side, so those shapes only arrive over the raw wire, while a
+ maximum, an enum value or a pattern from a real SDK call reaches this.
+ Everything here runs before the request is processed."""
+ err = _validate_string_length(body, "Description", "description", 0, 1000)
+ if err is not None:
+ return err
+ filtering = body.get("PositionFiltering")
+ if filtering is not None and filtering not in _POSITION_FILTERING:
+ return _constraint(
+ filtering, "positionFiltering",
+ "Member must satisfy enum value set: [TimeBased, DistanceBased, AccuracyBased]",
+ )
+ plan = body.get("PricingPlan")
+ if plan is not None and plan != "RequestBasedUsage":
+ # The model's enum still carries MobileAssetTracking and
+ # MobileAssetManagement, but the member is deprecated: "No longer used.
+ # If included, the only allowed value is RequestBasedUsage."
+ # (CreateTracker reference.) An enum-set message naming one member
+ # would be misleading, so the refusal says what happened to the rest.
+ # Wording unmeasured.
+ return _validation(
+ f"PricingPlan '{plan}' is no longer accepted. The only allowed "
+ f"value is RequestBasedUsage."
+ )
+ return None
+
+
+def _tracker_view(rec):
+ """DescribeTracker response — required members plus stored optionals."""
+ view = {
+ "TrackerName": rec["TrackerName"],
+ "TrackerArn": rec["TrackerArn"],
+ "Description": rec["Description"],
+ "PricingPlan": rec["PricingPlan"],
+ "CreateTime": _iso(rec["CreateTime"]),
+ "UpdateTime": _iso(rec["UpdateTime"]),
+ }
+ for field in _STORED_OPTIONALS:
+ if field != "Description" and field in rec:
+ view[field] = rec[field]
+ return view
+
+
+def _position_view(pos):
+ view = {
+ "DeviceId": pos["DeviceId"],
+ "SampleTime": _iso(pos["SampleTime"]),
+ "ReceivedTime": _iso(pos["ReceivedTime"]),
+ "Position": pos["Position"],
+ }
+ if "Accuracy" in pos:
+ view["Accuracy"] = pos["Accuracy"]
+ if "PositionProperties" in pos:
+ view["PositionProperties"] = pos["PositionProperties"]
+ return view
+
+
+# ---------------------------------------------------------------------------
+# Tracker handlers
+# ---------------------------------------------------------------------------
+
+def _create_tracker(body):
+ name = body.get("TrackerName", "")
+ if not name:
+ return _validation("TrackerName is required.")
+ err = _validate_tracker_name(name)
+ if err is not None:
+ return err
+ err = _validate_settings(body)
+ if err is not None:
+ return err
+ # CreateTracker-only members (UpdateTracker takes neither).
+ err = _validate_string_length(body, "KmsKeyId", "kmsKeyId", 1, 2048)
+ if err is not None:
+ return err
+ err = _validate_string_map(
+ body.get("Tags"), "tags", 50, (1, 128), (0, 256), pattern=True
+ )
+ if err is not None:
+ return err
+ if name in _trackers:
+ # Live-service wording, probed 2026-08-26.
+ return _error(409, "ConflictException",
+ f"Tracker already exists: {name}.")
+ now = _now()
+ rec = {
+ "TrackerName": name,
+ "TrackerArn": _tracker_arn(name),
+ "CreateTime": now,
+ "UpdateTime": now,
+ "positions": {},
+ }
+ rec.update(copy.deepcopy(_CREATE_DEFAULTS))
+ for field in _STORED_OPTIONALS:
+ if field in body:
+ rec[field] = body[field]
+ _trackers[name] = rec
+ return json_response({
+ "TrackerName": name,
+ "TrackerArn": rec["TrackerArn"],
+ "CreateTime": _iso(now),
+ })
+
+
+def _describe_tracker(name):
+ rec = _trackers.get(name)
+ if rec is None:
+ return _not_found(name)
+ return json_response(_tracker_view(rec))
+
+
+def _update_tracker(name, body):
+ err = _validate_settings(body)
+ if err is not None:
+ return err
+ rec = _trackers.get(name)
+ if rec is None:
+ return _not_found(name)
+ for field in _MUTABLE_FIELDS:
+ if field in body:
+ rec[field] = body[field]
+ rec["UpdateTime"] = _now()
+ return json_response({
+ "TrackerName": name,
+ "TrackerArn": rec["TrackerArn"],
+ "UpdateTime": _iso(rec["UpdateTime"]),
+ })
+
+
+def _list_trackers(body):
+ max_results, err = _max_results(body)
+ if err is not None:
+ return err
+ cursor = None
+ token = body.get("NextToken")
+ if token:
+ cursor = _decode_token(token, (str,))
+ if cursor is None:
+ return _validation(_INVALID_TOKEN)
+ # Sorted by name: a total order the token can resume from.
+ records = sorted(_trackers.values(), key=lambda r: r["TrackerName"])
+ if cursor is not None:
+ records = [r for r in records if r["TrackerName"] > cursor[0]]
+ page = records[:max_results]
+ result = {"Entries": [
+ {
+ "TrackerName": rec["TrackerName"],
+ "Description": rec["Description"],
+ "PricingPlan": rec["PricingPlan"],
+ "CreateTime": _iso(rec["CreateTime"]),
+ "UpdateTime": _iso(rec["UpdateTime"]),
+ }
+ for rec in page
+ ]}
+ if len(records) > max_results:
+ result["NextToken"] = _encode_token((page[-1]["TrackerName"],))
+ return json_response(result)
+
+
+def _delete_tracker(name):
+ if name not in _trackers:
+ return _not_found(name)
+ del _trackers[name]
+ return json_response({})
+
+
+# ---------------------------------------------------------------------------
+# Device position handlers
+# ---------------------------------------------------------------------------
+
+def _parse_update(index, update):
+ """A DevicePositionUpdate's required members, or the ValidationException
+ for a structurally invalid entry. botocore refuses to send one, so the
+ raw-wire answer of the live service is unmeasured; the request-level
+ 400 follows the model (DeviceId, SampleTime and Position are required)."""
+ member = f"updates.{index + 1}.member"
+ if not isinstance(update, dict):
+ return None, _constraint(update, member, "Member must be a structure")
+ device_id = update.get("DeviceId")
+ if device_id is None:
+ return None, _constraint(device_id, f"{member}.deviceId", "Member must not be null")
+ err = _validate_device_id(device_id, f"{member}.deviceId")
+ if err is not None:
+ return None, err
+ sample_time = _parse_timestamp(update.get("SampleTime"))
+ if sample_time is None:
+ return None, _constraint(
+ update.get("SampleTime"), f"{member}.sampleTime", "Member must not be null"
+ )
+ position = update.get("Position")
+ if (not isinstance(position, list) or len(position) != 2
+ or not all(_is_number(c) for c in position)):
+ return None, _constraint(
+ position, f"{member}.position", "Member must have length equal to 2"
+ )
+ # Accuracy: a PositionalAccuracy, whose Horizontal is required and runs
+ # 0..10000000 metres. It is not decoration — under AccuracyBased it is the
+ # filter's threshold, and a negative one would lower it.
+ err = _validate_accuracy(update.get("Accuracy"), f"{member}.accuracy")
+ if err is not None:
+ return None, err
+ # PositionProperties: at most 4 entries, keys 1..20, values 1..150
+ # (DevicePositionUpdate reference).
+ err = _validate_string_map(
+ update.get("PositionProperties"), f"{member}.positionProperties",
+ 4, (1, 20), (1, 150),
+ )
+ if err is not None:
+ return None, err
+ return (device_id, sample_time, position), None
+
+
+# The filtering thresholds the CreateTracker reference documents: TimeBased
+# stores "only one update per 30 seconds ... for each unique device ID",
+# DistanceBased ignores an update when "the device has moved less than 30 m
+# (98.4 ft)", and AccuracyBased ignores it when the device "has moved less
+# than the measured accuracy" (the reference's own example adds the two
+# horizontal accuracies: 5 m and 10 m ignore a move under 15 m).
+_TIME_FILTER_SECONDS = 30.0
+_DISTANCE_FILTER_METRES = 30.0
+_EARTH_RADIUS_METRES = 6371008.8
+
+
+def _metres_between(a, b):
+ """Great-circle distance between two [lon, lat] pairs, in metres."""
+ lon1, lat1 = math.radians(a[0]), math.radians(a[1])
+ lon2, lat2 = math.radians(b[0]), math.radians(b[1])
+ dlon, dlat = lon2 - lon1, lat2 - lat1
+ h = (math.sin(dlat / 2) ** 2
+ + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2)
+ return 2 * _EARTH_RADIUS_METRES * math.asin(min(1.0, math.sqrt(h)))
+
+
+def _horizontal_accuracy(accuracy):
+ """The Horizontal member of a PositionalAccuracy, or None."""
+ if isinstance(accuracy, dict) and _is_number(accuracy.get("Horizontal")):
+ return float(accuracy["Horizontal"])
+ return None
+
+
+def _is_filtered_out(mode, previous, sample_time, position, accuracy):
+ """Whether the tracker's PositionFiltering drops this update.
+
+ The comparison is against the newest sample the device already has. A
+ dropped update is not an error: the reference says such updates are
+ "neither evaluated against linked geofence collections, nor stored", and
+ BatchUpdateDevicePosition reports nothing for them. Unmeasured: an update
+ whose SampleTime is older than the stored one, which the reference does
+ not describe; MiniStack treats it by the same distance in time.
+ """
+ if previous is None:
+ return False
+ if mode == "TimeBased":
+ # SampleTime is epoch seconds here (see _parse_timestamp).
+ return abs(sample_time - previous["SampleTime"]) < _TIME_FILTER_SECONDS
+ moved = _metres_between(previous["Position"], position)
+ if mode == "DistanceBased":
+ return moved < _DISTANCE_FILTER_METRES
+ if mode == "AccuracyBased":
+ previous_accuracy = _horizontal_accuracy(previous.get("Accuracy"))
+ current_accuracy = _horizontal_accuracy(accuracy)
+ if previous_accuracy is None and current_accuracy is None:
+ # BatchUpdateDevicePosition: "If PositionFiltering is set to
+ # AccuracyBased filtering, Amazon Location uses the default value
+ # { "Horizontal": 0} when accuracy is not provided on a
+ # DevicePositionUpdate." A threshold of 0 keeps every update,
+ # which is what returning here does.
+ return False
+ threshold = (previous_accuracy or 0.0) + (current_accuracy or 0.0)
+ return moved < threshold
+ return False
+
+
+def _batch_update_positions(name, body):
+ updates = body.get("Updates")
+ if not isinstance(updates, list) or not updates:
+ return _constraint(
+ updates, "updates", "Member must have length greater than or equal to 1"
+ )
+ if len(updates) > 10:
+ return _constraint(
+ len(updates), "updates", "Member must have length less than or equal to 10"
+ )
+ parsed = []
+ for index, update in enumerate(updates):
+ members, err = _parse_update(index, update)
+ if err is not None:
+ return err
+ parsed.append((update, *members))
+ rec = _trackers.get(name)
+ if rec is None:
+ return _not_found(name)
+ errors = []
+ # One receive time for the whole batch: the request arrived once, and a
+ # per-entry clock read would make the order of two samples that share a
+ # SampleTime depend on the clock resolution. Unmeasured.
+ received = _now()
+ for update, device_id, sample_time, position in parsed:
+ problem = None
+ if not -90.0 <= position[1] <= 90.0:
+ # Live-service wording, probed 2026-08-26.
+ problem = "latitude must be between -90 and 90 degrees"
+ elif not -180.0 <= position[0] <= 180.0:
+ # Unmeasured: the latitude text with the longitude range.
+ problem = "longitude must be between -180 and 180 degrees"
+ if problem:
+ errors.append({
+ "DeviceId": device_id,
+ "SampleTime": _iso(sample_time),
+ "Error": {"Code": "ValidationError", "Message": problem},
+ })
+ continue
+ device = rec["positions"].setdefault(device_id, {"latest": None, "history": []})
+ if _is_filtered_out(rec.get("PositionFiltering", "TimeBased"),
+ device["latest"], sample_time, position,
+ update.get("Accuracy")):
+ continue
+ pos = {
+ "DeviceId": device_id,
+ "SampleTime": sample_time,
+ "ReceivedTime": received,
+ "Position": [float(position[0]), float(position[1])],
+ "Seq": _next_sequence(),
+ }
+ if "Accuracy" in update:
+ pos["Accuracy"] = update["Accuracy"]
+ if "PositionProperties" in update:
+ pos["PositionProperties"] = update["PositionProperties"]
+ history = device["history"]
+ history.append(pos)
+ history.sort(key=_history_key)
+ del history[:-_HISTORY_LIMIT]
+ device["latest"] = history[-1]
+ return json_response({"Errors": errors})
+
+
+def _history_key(pos):
+ # "Seq" makes the key a total order: samples that share both timestamps
+ # would otherwise be one point for a NextToken, and the second one would
+ # be lost across a page boundary.
+ return (pos["SampleTime"], pos["ReceivedTime"], pos["Seq"])
+
+
+def _get_device_position(name, device_id):
+ err = _validate_device_id(device_id, "deviceId")
+ if err is not None:
+ return err
+ rec = _trackers.get(name)
+ if rec is None:
+ return _not_found(name)
+ device = rec["positions"].get(device_id)
+ if device is None or device.get("latest") is None:
+ # Live-service wording, probed 2026-08-26.
+ return _error(404, "ResourceNotFoundException",
+ "records not found for given deviceId")
+ return json_response(_position_view(device["latest"]))
+
+
+def _batch_get_positions(name, body):
+ device_ids = body.get("DeviceIds")
+ if not isinstance(device_ids, list) or not device_ids:
+ return _constraint(
+ device_ids, "deviceIds", "Member must have length greater than or equal to 1"
+ )
+ if len(device_ids) > 10:
+ return _constraint(
+ len(device_ids), "deviceIds", "Member must have length less than or equal to 10"
+ )
+ for index, device_id in enumerate(device_ids):
+ # The list's member is the Id shape too: an element that breaks it is
+ # refused, not quietly left out of the response as a device without a
+ # position would be.
+ err = _validate_device_id(device_id, f"deviceIds.{index + 1}.member")
+ if err is not None:
+ return err
+ rec = _trackers.get(name)
+ if rec is None:
+ return _not_found(name)
+ # A device without a position is left out and Errors stays empty, as the
+ # live service answered (probed 2026-08-26, one found + one missing).
+ found = []
+ for device_id in device_ids:
+ device = rec["positions"].get(device_id)
+ if device is not None and device.get("latest") is not None:
+ found.append(_position_view(device["latest"]))
+ return json_response({"DevicePositions": found, "Errors": []})
+
+
+def _get_position_history(name, device_id, body):
+ err = _validate_device_id(device_id, "deviceId")
+ if err is not None:
+ return err
+ max_results, err = _max_results(body)
+ if err is not None:
+ return err
+ cursor = None
+ token = body.get("NextToken")
+ if token:
+ cursor = _decode_token(token, (float, float, int))
+ if cursor is None:
+ return _validation(_INVALID_TOKEN)
+ # Documented defaults when the members are omitted: the 24 hours up to now.
+ start, err = _time_bound(body, "StartTimeInclusive", _now() - 24 * 3600)
+ if err is not None:
+ return err
+ end, err = _time_bound(body, "EndTimeExclusive", _now())
+ if err is not None:
+ return err
+ rec = _trackers.get(name)
+ if rec is None:
+ return _not_found(name)
+ device = rec["positions"].get(device_id, {})
+ positions = [
+ pos for pos in device.get("history", [])
+ if start <= pos["SampleTime"] < end
+ ]
+ if cursor is not None:
+ positions = [pos for pos in positions if _history_key(pos) > cursor]
+ page = positions[:max_results]
+ result = {"DevicePositions": [_position_view(pos) for pos in page]}
+ if len(positions) > max_results:
+ result["NextToken"] = _encode_token(_history_key(page[-1]))
+ return json_response(result)
+
+
+# ---------------------------------------------------------------------------
+# Request Router
+# ---------------------------------------------------------------------------
+
+# Every route but CreateTracker and ListTrackers carries {TrackerName} in the
+# path, where it is the same modeled ResourceName as in a request body.
+_PATH_NAME_RE = re.compile(r"^/tracking/v0/trackers/([^/]+)")
+
+_TRACKER_RE = re.compile(r"^/tracking/v0/trackers/([^/]+)$")
+_POSITIONS_RE = re.compile(r"^/tracking/v0/trackers/([^/]+)/positions$")
+_GET_POSITIONS_RE = re.compile(r"^/tracking/v0/trackers/([^/]+)/get-positions$")
+_DEVICE_LATEST_RE = re.compile(
+ r"^/tracking/v0/trackers/([^/]+)/devices/([^/]+)/positions/latest$"
+)
+_DEVICE_HISTORY_RE = re.compile(
+ r"^/tracking/v0/trackers/([^/]+)/devices/([^/]+)/list-positions$"
+)
+
+
+async def handle_request(method, path, headers, body_bytes, query_params):
+ try:
+ body = json.loads(body_bytes) if body_bytes else {}
+ except json.JSONDecodeError:
+ return _validation("Could not deserialize the request body as JSON.")
+
+ # POST /tracking/v0/trackers -- CreateTracker
+ if path == "/tracking/v0/trackers" and method == "POST":
+ return _create_tracker(body)
+
+ # POST /tracking/v0/list-trackers -- ListTrackers
+ if path == "/tracking/v0/list-trackers" and method == "POST":
+ return _list_trackers(body)
+
+ # The tracker name of every route below comes out of the path, and the
+ # path is not the request-validation layer: a name that is too long or off
+ # the pattern is a ValidationException here, not a lookup that misses and
+ # answers 404.
+ m = _PATH_NAME_RE.match(path)
+ if m:
+ err = _validate_tracker_name(urllib.parse.unquote(m.group(1)))
+ if err is not None:
+ return err
+
+ # POST /tracking/v0/trackers/{TrackerName}/positions -- BatchUpdateDevicePosition
+ m = _POSITIONS_RE.match(path)
+ if m and method == "POST":
+ return _batch_update_positions(urllib.parse.unquote(m.group(1)), body)
+
+ # POST /tracking/v0/trackers/{TrackerName}/get-positions -- BatchGetDevicePosition
+ m = _GET_POSITIONS_RE.match(path)
+ if m and method == "POST":
+ return _batch_get_positions(urllib.parse.unquote(m.group(1)), body)
+
+ # GET /tracking/v0/trackers/{T}/devices/{D}/positions/latest -- GetDevicePosition
+ m = _DEVICE_LATEST_RE.match(path)
+ if m and method == "GET":
+ return _get_device_position(
+ urllib.parse.unquote(m.group(1)), urllib.parse.unquote(m.group(2))
+ )
+
+ # POST /tracking/v0/trackers/{T}/devices/{D}/list-positions -- GetDevicePositionHistory
+ m = _DEVICE_HISTORY_RE.match(path)
+ if m and method == "POST":
+ return _get_position_history(
+ urllib.parse.unquote(m.group(1)), urllib.parse.unquote(m.group(2)), body
+ )
+
+ # /tracking/v0/trackers/{TrackerName}
+ # -- DescribeTracker / UpdateTracker / DeleteTracker
+ m = _TRACKER_RE.match(path)
+ if m:
+ name = urllib.parse.unquote(m.group(1))
+ if method == "GET":
+ return _describe_tracker(name)
+ if method == "PATCH":
+ return _update_tracker(name, body)
+ if method == "DELETE":
+ return _delete_tracker(name)
+
+ return _validation(f"No route for {method} {path}")
diff --git a/tests/conftest.py b/tests/conftest.py
index 69c02fdb..bbd70eb2 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -748,6 +748,15 @@ def translate():
return make_client("translate")
[email protected](scope="session")
+def location():
+ # The location model puts `cp.tracking.` / `tracking.` host prefixes in
+ # front of the endpoint; against localhost those subdomains need not
+ # resolve, so disable injection (same as the logs fixture) — routing then
+ # rides on the `geo` credential scope.
+ return make_client("location", additional_config_kwargs={"inject_host_prefix": False})
+
+
class FakeDockerContainer:
"""Container double for tests that observe lifecycle without a daemon."""
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index a4263de3..d9bac510 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -6511,6 +6511,161 @@ def test_cfn_scheduler_schedule(cfn):
assert stack["StackStatus"] == "DELETE_COMPLETE"
+def test_cfn_location_tracker(cfn, location):
+ """AWS::Location::Tracker provisions through the location service (so it is
+ readable back through the real API) and the stack tags reach its Tags;
+ Description and a tag change update in place; a KmsKeyId change on the
+ custom-named tracker is refused as on AWS; a TrackerName change is a
+ replacement, after which the old tracker is gone."""
+ stack_name = f"cfn-loc-{_uuid_mod.uuid4().hex[:8]}"
+ first, second = f"{stack_name}-a", f"{stack_name}-b"
+
+ def template(name, description, kms_key_id=None):
+ props = {
+ "TrackerName": name,
+ "Description": description,
+ "Tags": [{"Key": "env", "Value": "test"}],
+ }
+ if kms_key_id:
+ props["KmsKeyId"] = kms_key_id
+ return json.dumps({
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Tracker": {"Type": "AWS::Location::Tracker", "Properties": props},
+ },
+ "Outputs": {
+ "Name": {"Value": {"Ref": "Tracker"}},
+ "Arn": {"Value": {"Fn::GetAtt": ["Tracker", "Arn"]}},
+ "TrackerArn": {"Value": {"Fn::GetAtt": ["Tracker", "TrackerArn"]}},
+ "UpdateTime": {"Value": {"Fn::GetAtt": ["Tracker", "UpdateTime"]}},
+ },
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(first, "v1"),
+ Tags=[{"Key": "owner", "Value": "team-a"}])
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Name") == first
+ assert _output(stack, "Arn").endswith(f":tracker/{first}")
+ # The resource exposes both Arn and TrackerArn, carrying the same value.
+ assert _output(stack, "TrackerArn") == _output(stack, "Arn")
+ assert _output(stack, "UpdateTime").endswith("Z")
+
+ described = location.describe_tracker(TrackerName=first)
+ assert described["Description"] == "v1"
+ assert described["TrackerArn"] == _output(stack, "Arn")
+ assert described["Tags"] == {
+ "env": "test", "owner": "team-a", **_system_tags(stack, "Tracker"),
+ }
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(first, "v2"),
+ Tags=[{"Key": "owner", "Value": "team-b"}])
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ resources = cfn.list_stack_resources(StackName=stack_name)["StackResourceSummaries"]
+ assert resources[0]["PhysicalResourceId"] == first
+ described = location.describe_tracker(TrackerName=first)
+ assert described["Description"] == "v2"
+ assert _template_tags(described["Tags"]) == {"env": "test", "owner": "team-b"}
+
+ # KmsKeyId requires replacement, which AWS refuses for a custom-named
+ # resource; the tracker stays as it was.
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=template(first, "v2", kms_key_id="alias/probe"),
+ Tags=[{"Key": "owner", "Value": "team-b"}])
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ assert "custom-named resource requires replacing" in _stack_event_reasons(cfn, stack_name)
+ assert "KmsKeyId" not in location.describe_tracker(TrackerName=first)
+
+ # A rename is a replacement: the new tracker is created, the old one removed.
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(second, "v2"),
+ Tags=[{"Key": "owner", "Value": "team-b"}])
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Name") == second
+ assert location.describe_tracker(TrackerName=second)["Description"] == "v2"
+ with pytest.raises(ClientError):
+ location.describe_tracker(TrackerName=first)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ with pytest.raises(ClientError):
+ location.describe_tracker(TrackerName=second)
+
+
+def test_cfn_location_tracker_generated_name(cfn, location):
+ """Without TrackerName the tracker gets the stack-derived physical name;
+ PositionFiltering, EventBridgeEnabled and KmsKeyEnableGeospatialQueries
+ update in place and revert to what a fresh create has (the last one
+ absent) when the template drops them; a KmsKeyId change replaces the
+ auto-named tracker under the same name, so its positions are gone."""
+ stack_name = f"cfn-loc-gen-{_uuid_mod.uuid4().hex[:8]}"
+
+ def template(props):
+ return json.dumps({
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Tracker": {"Type": "AWS::Location::Tracker", "Properties": props},
+ },
+ "Outputs": {"Name": {"Value": {"Ref": "Tracker"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template({}))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ name = _output(stack, "Name")
+ assert name.startswith(f"{stack_name}-Tracker-")
+ described = location.describe_tracker(TrackerName=name)
+ assert described["PositionFiltering"] == "TimeBased"
+ assert described["EventBridgeEnabled"] is False
+ assert "KmsKeyEnableGeospatialQueries" not in described
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template({
+ "Description": "in place",
+ "PositionFiltering": "DistanceBased",
+ "EventBridgeEnabled": True,
+ "KmsKeyEnableGeospatialQueries": True,
+ }))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Name") == name
+ described = location.describe_tracker(TrackerName=name)
+ assert described["Description"] == "in place"
+ assert described["PositionFiltering"] == "DistanceBased"
+ assert described["EventBridgeEnabled"] is True
+ assert described["KmsKeyEnableGeospatialQueries"] is True
+
+ # Dropping the properties reverts them to what a fresh create has.
+ cfn.update_stack(StackName=stack_name, TemplateBody=template({}))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ described = location.describe_tracker(TrackerName=name)
+ assert described["Description"] == ""
+ assert described["PositionFiltering"] == "TimeBased"
+ assert described["EventBridgeEnabled"] is False
+ assert "KmsKeyEnableGeospatialQueries" not in described
+
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": "veh-1", "Position": [1.0, 1.0],
+ "SampleTime": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}],
+ )
+ # KmsKeyId requires replacement: the auto-named tracker is re-created
+ # under the same physical name, without its positions.
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=template({"KmsKeyId": "alias/probe"}))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Name") == name
+ assert location.describe_tracker(TrackerName=name)["KmsKeyId"] == "alias/probe"
+ with pytest.raises(ClientError):
+ location.get_device_position(TrackerName=name, DeviceId="veh-1")
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def test_cfn_eventbus_basic(cfn, eb):
"""Test basic EventBus create and delete."""
template = {
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index a92bdd61..caaf6c6f 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -1034,6 +1034,12 @@ class TestResourceArn:
from ministack.core.iam_actions import extract_resource_arn
assert extract_resource_arn("pipes", "GET", "/v1/pipes/my-pipe", {}, b"", {}, "us-east-1", "123") == "arn:aws:pipes:us-east-1:123:pipe/my-pipe"
+ def test_location_tracker(self):
+ from ministack.core.iam_actions import extract_resource_arn
+ assert extract_resource_arn("location", "GET", "/tracking/v0/trackers/fleet", {}, b"", {}, "us-east-1", "123") == "arn:aws:geo:us-east-1:123:tracker/fleet"
+ assert extract_resource_arn("location", "POST", "/tracking/v0/trackers/fleet/positions", {}, b"", {}, "us-east-1", "123") == "arn:aws:geo:us-east-1:123:tracker/fleet"
+ assert extract_resource_arn("location", "POST", "/tracking/v0/list-trackers", {}, b"", {}, "us-east-1", "123") == "*"
+
def test_mq_broker(self):
from ministack.core.iam_actions import extract_resource_arn
assert "mq" in extract_resource_arn("mq", "GET", "/v1/brokers/my-broker", {}, b"", {}, "us-east-1", "123")
diff --git a/tests/test_location.py b/tests/test_location.py
new file mode 100644
index 00000000..91783b97
--- /dev/null
+++ b/tests/test_location.py
@@ -0,0 +1,1087 @@
+# 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).
+"""
+Integration tests for the Amazon Location Service emulator (trackers only).
+
+The SDK signs these requests with credential scope `geo` (botocore
+signingName), not `location` — the tests going through the boto3 client also
+exercise that routing path, since the `location` fixture disables the modeled
+`cp.tracking.` / `tracking.` host-prefix injection.
+"""
+import datetime
+import json
+import os
+import urllib.error
+import urllib.request
+import uuid
+
+import pytest
+from botocore.exceptions import ClientError
+
+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
+
+
+def _uid(prefix="trk"):
+ return f"{prefix}-{uuid.uuid4().hex[:8]}"
+
+
+# Millisecond-aligned (the wire form truncates to ms) and one hour in the
+# past, so samples land inside GetDevicePositionHistory's default window
+# (the 24 hours up to now) while offsets stay deterministic within a run.
+_TS_BASE = datetime.datetime.now(datetime.timezone.utc).replace(
+ microsecond=0
+) - datetime.timedelta(hours=1)
+
+
+def _ts(offset_seconds=0):
+ return _TS_BASE + datetime.timedelta(seconds=offset_seconds)
+
+
+def _raw_post(path, payload=None, raw=None):
+ """POST over the raw wire (for shapes botocore refuses to send), signed
+ with the `geo` credential scope the real SDK uses. `raw` sends the bytes
+ unchanged, for a body that is not JSON at all."""
+ req = urllib.request.Request(
+ f"{ENDPOINT}{path}",
+ data=raw if raw is not None else json.dumps(payload).encode(),
+ method="POST",
+ headers={
+ "Content-Type": "application/json",
+ "Authorization": (
+ "AWS4-HMAC-SHA256 "
+ "Credential=test/20260826/us-east-1/geo/aws4_request, "
+ "SignedHeaders=host, Signature=fake"
+ ),
+ },
+ )
+ try:
+ with urllib.request.urlopen(req) as resp:
+ return resp.status, json.loads(resp.read() or b"{}")
+ except urllib.error.HTTPError as exc:
+ return exc.code, json.loads(exc.read() or b"{}")
+
+
+# ---------------------------------------------------------------------------
+# Tracker CRUD
+# ---------------------------------------------------------------------------
+
+def test_location_tracker_crud_round_trip(location):
+ name = _uid()
+ created = location.create_tracker(
+ TrackerName=name,
+ Description="fleet trackers",
+ PositionFiltering="TimeBased",
+ EventBridgeEnabled=False,
+ Tags={"team": "iot"},
+ )
+ assert created["TrackerName"] == name
+ assert created["TrackerArn"].startswith("arn:aws:geo:us-east-1:")
+ assert created["TrackerArn"].endswith(f":tracker/{name}")
+ # Timestamps must be wire-correct: botocore parses them into datetimes.
+ assert isinstance(created["CreateTime"], datetime.datetime)
+
+ described = location.describe_tracker(TrackerName=name)
+ assert described["TrackerName"] == name
+ assert described["TrackerArn"] == created["TrackerArn"]
+ assert described["Description"] == "fleet trackers"
+ assert described["PositionFiltering"] == "TimeBased"
+ assert described["EventBridgeEnabled"] is False
+ assert described["Tags"] == {"team": "iot"}
+ assert isinstance(described["CreateTime"], datetime.datetime)
+ assert isinstance(described["UpdateTime"], datetime.datetime)
+
+ entries = location.list_trackers()["Entries"]
+ entry = next(e for e in entries if e["TrackerName"] == name)
+ assert entry["Description"] == "fleet trackers"
+ assert isinstance(entry["CreateTime"], datetime.datetime)
+ assert isinstance(entry["UpdateTime"], datetime.datetime)
+
+ location.delete_tracker(TrackerName=name)
+ with pytest.raises(ClientError) as excinfo:
+ location.describe_tracker(TrackerName=name)
+ assert excinfo.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_location_describe_materializes_defaults(location):
+ name = _uid()
+ location.create_tracker(TrackerName=name)
+ # The live service (probed 2026-08-26) materializes these members even
+ # when CreateTracker omitted them; Description is a required response
+ # member — empty string when unset.
+ described = location.describe_tracker(TrackerName=name)
+ assert described["Description"] == ""
+ assert described["Tags"] == {}
+ assert described["EventBridgeEnabled"] is False
+ assert described["PositionFiltering"] == "TimeBased"
+ # The deprecated PricingPlan "Always returns RequestBasedUsage" (API
+ # reference) and was present on the live describe (probed 2026-08-26).
+ assert described["PricingPlan"] == "RequestBasedUsage"
+ assert "PricingPlanDataSource" not in described
+ entry = next(e for e in location.list_trackers()["Entries"] if e["TrackerName"] == name)
+ assert entry["PricingPlan"] == "RequestBasedUsage"
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_tracker_name_validated(location):
+ # A name with "/" would be unaddressable via the path routes.
+ with pytest.raises(ClientError) as excinfo:
+ location.create_tracker(TrackerName="bad/name")
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ValidationException"
+ assert "trackerName" in err["Message"]
+ assert "[-._\\w]+" in err["Message"]
+ with pytest.raises(ClientError) as excinfo:
+ location.create_tracker(TrackerName="x" * 101)
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ValidationException"
+ assert "length less than or equal to 100" in err["Message"]
+
+
+def test_location_tracker_name_is_ascii(location):
+ """The pattern [-._\\w]+ is a Java regex service-side, where \\w is ASCII.
+ The CreateTracker reference spells it out — a name may "contain only
+ alphanumeric characters (A-Z, a-z, 0-9), hyphens (-), periods (.), and
+ underscores (_)" — so a Unicode letter is refused, not stored."""
+ for name in ("Trackeré", "トラッカー", "trk-µ"):
+ with pytest.raises(ClientError) as excinfo:
+ location.create_tracker(TrackerName=name)
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ValidationException"
+ assert "[-._\\w]+" in err["Message"]
+ with pytest.raises(ClientError):
+ location.describe_tracker(TrackerName=name)
+
+
+def test_location_path_tracker_name_validated(location):
+ """The name in the URL is the same modeled ResourceName as the one in a
+ request body — "Length Constraints: Minimum length of 1. Maximum length
+ of 100. Pattern: [-._\\w]+" on every operation page. A name that breaks
+ it is a ValidationException, not the 404 of a lookup that could never
+ have matched."""
+ sample = {"DeviceId": "veh-1", "SampleTime": _ts(0), "Position": [1.0, 1.0]}
+ for name in ("x" * 101, "bad?name"):
+ calls = (
+ lambda n: location.describe_tracker(TrackerName=n),
+ lambda n: location.update_tracker(TrackerName=n, Description="x"),
+ lambda n: location.delete_tracker(TrackerName=n),
+ lambda n: location.batch_update_device_position(
+ TrackerName=n, Updates=[sample]),
+ lambda n: location.batch_get_device_position(
+ TrackerName=n, DeviceIds=["veh-1"]),
+ lambda n: location.get_device_position(TrackerName=n, DeviceId="veh-1"),
+ lambda n: location.get_device_position_history(
+ TrackerName=n, DeviceId="veh-1"),
+ )
+ for call in calls:
+ with pytest.raises(ClientError) as excinfo:
+ call(name)
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ValidationException", (name, err)
+ assert "trackerName" in err["Message"]
+
+
+def test_location_duplicate_tracker_conflicts(location):
+ name = _uid()
+ location.create_tracker(TrackerName=name)
+ with pytest.raises(ClientError) as excinfo:
+ location.create_tracker(TrackerName=name)
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ConflictException"
+ # Live-service wording, probed 2026-08-26.
+ assert err["Message"] == f"Tracker already exists: {name}."
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_unknown_tracker_operations_404(location):
+ # "Tracker not found: X." was measured on GetDevicePosition only
+ # (2026-08-26), so only that call pins the text.
+ with pytest.raises(ClientError) as excinfo:
+ location.get_device_position(TrackerName="no-such-tracker", DeviceId="d1")
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ResourceNotFoundException"
+ assert err["Message"] == "Tracker not found: no-such-tracker."
+ # The wording of the other operations is unmeasured: code only.
+ with pytest.raises(ClientError) as excinfo:
+ location.describe_tracker(TrackerName="no-such-tracker")
+ assert excinfo.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ with pytest.raises(ClientError) as excinfo:
+ location.update_tracker(TrackerName="no-such-tracker", Description="x")
+ assert excinfo.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ with pytest.raises(ClientError) as excinfo:
+ location.delete_tracker(TrackerName="no-such-tracker")
+ assert excinfo.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ with pytest.raises(ClientError) as excinfo:
+ location.batch_update_device_position(
+ TrackerName="no-such-tracker",
+ Updates=[{"DeviceId": "d1", "SampleTime": _ts(), "Position": [0.0, 0.0]}],
+ )
+ assert excinfo.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_location_invalid_request_beats_the_missing_tracker(location):
+ """An invalid member is refused before the tracker is looked up: AWS
+ validates the request in front of the operation, so a bad request naming
+ a tracker that does not exist answers 400, not the 404 of the lookup."""
+ missing = "no-such-tracker"
+ with pytest.raises(ClientError) as excinfo:
+ location.update_tracker(TrackerName=missing, PositionFiltering="Bogus")
+ assert excinfo.value.response["Error"]["Code"] == "ValidationException"
+ with pytest.raises(ClientError) as excinfo:
+ location.batch_update_device_position(
+ TrackerName=missing,
+ Updates=[{
+ "DeviceId": "veh-1", "SampleTime": _ts(0), "Position": [1.0, 1.0],
+ "PositionProperties": {f"p{i}": "v" for i in range(5)},
+ }],
+ )
+ assert excinfo.value.response["Error"]["Code"] == "ValidationException"
+ with pytest.raises(ClientError) as excinfo:
+ location.batch_get_device_position(
+ TrackerName=missing, DeviceIds=[f"d{i}" for i in range(11)]
+ )
+ assert excinfo.value.response["Error"]["Code"] == "ValidationException"
+ with pytest.raises(ClientError) as excinfo:
+ location.get_device_position_history(
+ TrackerName=missing, DeviceId="veh-1", MaxResults=101
+ )
+ assert excinfo.value.response["Error"]["Code"] == "ValidationException"
+
+
+def test_location_update_tracker_round_trip(location):
+ name = _uid()
+ location.create_tracker(TrackerName=name, Description="v1")
+ updated = location.update_tracker(
+ TrackerName=name,
+ Description="v2",
+ PositionFiltering="DistanceBased",
+ EventBridgeEnabled=True,
+ KmsKeyEnableGeospatialQueries=True,
+ )
+ assert updated["TrackerName"] == name
+ assert updated["TrackerArn"].endswith(f":tracker/{name}")
+ assert isinstance(updated["UpdateTime"], datetime.datetime)
+
+ described = location.describe_tracker(TrackerName=name)
+ assert described["Description"] == "v2"
+ assert described["PositionFiltering"] == "DistanceBased"
+ assert described["EventBridgeEnabled"] is True
+ assert described["KmsKeyEnableGeospatialQueries"] is True
+ assert described["UpdateTime"] >= described["CreateTime"]
+
+ # Omitted members keep their values (PATCH semantics, not replacement).
+ location.update_tracker(TrackerName=name, Description="v3")
+ described = location.describe_tracker(TrackerName=name)
+ assert described["Description"] == "v3"
+ assert described["PositionFiltering"] == "DistanceBased"
+
+ with pytest.raises(ClientError) as excinfo:
+ location.update_tracker(TrackerName="no-such-tracker", Description="x")
+ assert excinfo.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ location.delete_tracker(TrackerName=name)
+
+
+# ---------------------------------------------------------------------------
+# Device positions
+# ---------------------------------------------------------------------------
+
+def test_location_batch_update_then_get_position(location):
+ name = _uid()
+ location.create_tracker(TrackerName=name)
+ resp = location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{
+ "DeviceId": "veh-1",
+ "SampleTime": _ts(0),
+ "Position": [11.5761, 48.1371],
+ "Accuracy": {"Horizontal": 5.0},
+ "PositionProperties": {"speed": "12.5"},
+ }],
+ )
+ assert resp["Errors"] == []
+
+ pos = location.get_device_position(TrackerName=name, DeviceId="veh-1")
+ assert pos["DeviceId"] == "veh-1"
+ # Position round-trips as the modeled [lon, lat] double list.
+ assert pos["Position"] == [11.5761, 48.1371]
+ assert pos["PositionProperties"] == {"speed": "12.5"}
+ assert pos["Accuracy"] == {"Horizontal": 5.0}
+ # Timestamps are wire-correct iso8601: boto3 parses them into datetimes,
+ # and SampleTime survives the round-trip exactly.
+ assert pos["SampleTime"] == _ts(0)
+ assert isinstance(pos["ReceivedTime"], datetime.datetime)
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_time_based_filtering_stores_one_sample_per_30_seconds(location):
+ """TimeBased is the default: "If your update frequency is more often than
+ 30 seconds, only one update per 30 seconds is stored for each unique
+ device ID"."""
+ name = _uid()
+ location.create_tracker(TrackerName=name)
+ assert location.describe_tracker(
+ TrackerName=name)["PositionFiltering"] == "TimeBased"
+
+ for offset in (0, 10, 29, 30, 61):
+ resp = location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": "veh-1", "SampleTime": _ts(offset),
+ "Position": [11.5761 + offset / 1000.0, 48.1371]}],
+ )
+ # A filtered update is not an error: it is simply not stored.
+ assert resp["Errors"] == []
+
+ history = location.get_device_position_history(
+ TrackerName=name, DeviceId="veh-1")["DevicePositions"]
+ assert [p["SampleTime"] for p in history] == [_ts(0), _ts(30), _ts(61)]
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_distance_based_filtering_ignores_moves_under_30_m(location):
+ """DistanceBased: "If the device has moved less than 30 m (98.4 ft),
+ location updates are ignored"."""
+ name = _uid()
+ location.create_tracker(TrackerName=name, PositionFiltering="DistanceBased")
+ # 0.0001 degrees of latitude is about 11 m, 0.0005 about 56 m.
+ for offset, lat in ((0, 48.1371), (60, 48.1372), (120, 48.1376)):
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": "veh-1", "SampleTime": _ts(offset),
+ "Position": [11.5761, lat]}],
+ )
+
+ history = location.get_device_position_history(
+ TrackerName=name, DeviceId="veh-1")["DevicePositions"]
+ assert [p["SampleTime"] for p in history] == [_ts(0), _ts(120)]
+ assert [p["Position"][1] for p in history] == [48.1371, 48.1376]
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_accuracy_based_filtering_ignores_moves_under_the_accuracy(location):
+ """AccuracyBased, with the reference's own example: two consecutive
+ updates of 5 m and 10 m horizontal accuracy ignore the second when the
+ device has moved less than 15 m."""
+ name = _uid()
+ location.create_tracker(TrackerName=name, PositionFiltering="AccuracyBased")
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": "veh-1", "SampleTime": _ts(0),
+ "Position": [11.5761, 48.1371],
+ "Accuracy": {"Horizontal": 5.0}}],
+ )
+ # About 11 m north, under the 15 m the two accuracies add up to.
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": "veh-1", "SampleTime": _ts(60),
+ "Position": [11.5761, 48.1372],
+ "Accuracy": {"Horizontal": 10.0}}],
+ )
+ # About 56 m north, above it.
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": "veh-1", "SampleTime": _ts(120),
+ "Position": [11.5761, 48.1376],
+ "Accuracy": {"Horizontal": 10.0}}],
+ )
+
+ history = location.get_device_position_history(
+ TrackerName=name, DeviceId="veh-1")["DevicePositions"]
+ assert [p["SampleTime"] for p in history] == [_ts(0), _ts(120)]
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_filtering_is_per_device_and_survives_an_update_tracker(location):
+ """The 30 second window is per unique device id, and UpdateTracker can
+ switch the mode of an existing tracker."""
+ name = _uid()
+ location.create_tracker(TrackerName=name)
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[
+ {"DeviceId": "veh-1", "SampleTime": _ts(0), "Position": [11.5761, 48.1371]},
+ {"DeviceId": "veh-2", "SampleTime": _ts(1), "Position": [11.5761, 48.1371]},
+ ],
+ )
+ for device in ("veh-1", "veh-2"):
+ assert location.get_device_position(
+ TrackerName=name, DeviceId=device)["SampleTime"] in (_ts(0), _ts(1))
+
+ location.update_tracker(TrackerName=name, PositionFiltering="DistanceBased")
+ assert location.describe_tracker(
+ TrackerName=name)["PositionFiltering"] == "DistanceBased"
+ # One second later but 56 m away: TimeBased would have dropped it,
+ # DistanceBased keeps it.
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": "veh-1", "SampleTime": _ts(1),
+ "Position": [11.5761, 48.1376]}],
+ )
+ history = location.get_device_position_history(
+ TrackerName=name, DeviceId="veh-1")["DevicePositions"]
+ assert len(history) == 2
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_get_position_unknown_device_404(location):
+ name = _uid()
+ location.create_tracker(TrackerName=name)
+ with pytest.raises(ClientError) as excinfo:
+ location.get_device_position(TrackerName=name, DeviceId="never-reported")
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ResourceNotFoundException"
+ # Live-service wording, probed 2026-08-26.
+ assert err["Message"] == "records not found for given deviceId"
+ location.delete_tracker(TrackerName=name)
+
+
+# The history tests below need every sample they send to be stored. All three
+# filtering modes drop something, and the only configuration that keeps every
+# sample is AccuracyBased on updates that carry no Accuracy: the reference
+# ignores an update when the device "has moved less than the measured
+# accuracy", and nothing measured it. TimeBased, the default, would collapse
+# samples closer together than 30 seconds.
+_KEEP_EVERY_SAMPLE = {"PositionFiltering": "AccuracyBased"}
+
+
+def test_location_position_history_in_order(location):
+ name = _uid()
+ location.create_tracker(TrackerName=name, **_KEEP_EVERY_SAMPLE)
+ # Delivered out of order — history must come back ascending by SampleTime.
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[
+ {"DeviceId": "veh-1", "SampleTime": _ts(30), "Position": [3.0, 3.0]},
+ {"DeviceId": "veh-1", "SampleTime": _ts(10), "Position": [1.0, 1.0]},
+ ],
+ )
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": "veh-1", "SampleTime": _ts(20), "Position": [2.0, 2.0]}],
+ )
+
+ history = location.get_device_position_history(
+ TrackerName=name, DeviceId="veh-1"
+ )["DevicePositions"]
+ assert [p["SampleTime"] for p in history] == [_ts(10), _ts(20), _ts(30)]
+
+ # The latest position is the newest sample, not the last write.
+ latest = location.get_device_position(TrackerName=name, DeviceId="veh-1")
+ assert latest["SampleTime"] == _ts(30)
+ assert latest["Position"] == [3.0, 3.0]
+
+ # Start is inclusive, End exclusive.
+ window = location.get_device_position_history(
+ TrackerName=name, DeviceId="veh-1",
+ StartTimeInclusive=_ts(10), EndTimeExclusive=_ts(30),
+ )["DevicePositions"]
+ assert [p["SampleTime"] for p in window] == [_ts(10), _ts(20)]
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_batch_get_omits_missing_devices(location):
+ """A device without a position is left out and Errors stays empty: the
+ live service's answer to one found + one missing (probed 2026-08-26)."""
+ name = _uid()
+ location.create_tracker(TrackerName=name)
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[
+ {"DeviceId": "veh-1", "SampleTime": _ts(0), "Position": [1.0, 1.0]},
+ {"DeviceId": "veh-2", "SampleTime": _ts(0), "Position": [2.0, 2.0]},
+ ],
+ )
+ resp = location.batch_get_device_position(
+ TrackerName=name, DeviceIds=["veh-1", "ghost", "veh-2"]
+ )
+ assert {p["DeviceId"] for p in resp["DevicePositions"]} == {"veh-1", "veh-2"}
+ assert resp["Errors"] == []
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_batch_update_rejects_malformed_entries(location):
+ """An entry missing a required member fails the whole request with a
+ ValidationException (the model marks DeviceId, SampleTime and Position
+ required); nothing of the batch is stored. botocore refuses to send such
+ an entry, so this goes over the raw wire, which also exercises the
+ numeric epoch SampleTime spelling the lenient timestamp parser accepts
+ alongside the model's iso8601 strings."""
+ name = _uid()
+ location.create_tracker(TrackerName=name)
+ status, body = _raw_post(
+ f"/tracking/v0/trackers/{name}/positions",
+ {"Updates": [
+ {"DeviceId": "veh-ok", "SampleTime": _ts(0).timestamp(),
+ "Position": [11.0, 48.0]},
+ {"DeviceId": "veh-bad", "SampleTime": _ts(0).timestamp()},
+ ]},
+ )
+ assert status == 400
+ assert body["__type"].endswith("ValidationException") or body.get("code") == "ValidationException" \
+ or "ValidationException" in json.dumps(body)
+ assert "updates.2.member.position" in json.dumps(body)
+ with pytest.raises(ClientError):
+ location.get_device_position(TrackerName=name, DeviceId="veh-ok")
+
+ # The epoch spelling alone is accepted.
+ status, body = _raw_post(
+ f"/tracking/v0/trackers/{name}/positions",
+ {"Updates": [{"DeviceId": "veh-ok", "SampleTime": _ts(0).timestamp(),
+ "Position": [11.0, 48.0]}]},
+ )
+ assert status == 200 and body["Errors"] == []
+ pos = location.get_device_position(TrackerName=name, DeviceId="veh-ok")
+ assert pos["SampleTime"] == _ts(0)
+
+ # Batch size: 1..10 entries, checked before any entry is stored.
+ for updates in ([], [{"DeviceId": f"v{i}", "SampleTime": _ts(0).timestamp(),
+ "Position": [1.0, 1.0]} for i in range(11)]):
+ status, body = _raw_post(f"/tracking/v0/trackers/{name}/positions",
+ {"Updates": updates})
+ assert status == 400, body
+ with pytest.raises(ClientError):
+ location.get_device_position(TrackerName=name, DeviceId="v0")
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_batch_update_rejects_out_of_range_positions(location):
+ """Out-of-range coordinates become per-entry Errors items while the call
+ itself stays 200 — with the live service's wording for latitude (probed
+ 2026-08-26)."""
+ name = _uid()
+ location.create_tracker(TrackerName=name)
+ resp = location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[
+ {"DeviceId": "veh-ok", "SampleTime": _ts(0), "Position": [11.0, 48.0]},
+ {"DeviceId": "veh-lat", "SampleTime": _ts(0), "Position": [0.0, 91.0]},
+ {"DeviceId": "veh-lon", "SampleTime": _ts(0), "Position": [-181.0, 0.0]},
+ ],
+ )
+ errors = {e["DeviceId"]: e for e in resp["Errors"]}
+ assert set(errors) == {"veh-lat", "veh-lon"}
+ assert errors["veh-lat"]["Error"] == {
+ "Code": "ValidationError",
+ "Message": "latitude must be between -90 and 90 degrees",
+ }
+ # Only the latitude text was measured; the longitude wording is the
+ # emulator's, so only the code is pinned.
+ assert errors["veh-lon"]["Error"]["Code"] == "ValidationError"
+ assert isinstance(errors["veh-lat"]["SampleTime"], datetime.datetime)
+ # The in-range sibling entry still landed; the rejected ones did not.
+ assert location.get_device_position(
+ TrackerName=name, DeviceId="veh-ok"
+ )["Position"] == [11.0, 48.0]
+ with pytest.raises(ClientError):
+ location.get_device_position(TrackerName=name, DeviceId="veh-lat")
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_history_bounded_to_newest_100(location):
+ """Per-device history keeps the newest 100 samples. A stated divergence:
+ the service retains 30 days of positions, MiniStack the newest 100 per
+ device."""
+ name = _uid()
+ location.create_tracker(TrackerName=name, **_KEEP_EVERY_SAMPLE)
+ # The modeled Updates list caps at 10 entries per call.
+ for chunk_start in range(0, 105, 10):
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[
+ {"DeviceId": "veh-1", "SampleTime": _ts(i), "Position": [1.0, 1.0]}
+ for i in range(chunk_start, min(chunk_start + 10, 105))
+ ],
+ )
+ history = location.get_device_position_history(
+ TrackerName=name, DeviceId="veh-1"
+ )["DevicePositions"]
+ assert len(history) == 100
+ # The oldest five were dropped.
+ assert history[0]["SampleTime"] == _ts(5)
+ assert history[-1]["SampleTime"] == _ts(104)
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_history_default_window_is_last_24_hours(location):
+ """With StartTimeInclusive/EndTimeExclusive omitted, the documented
+ defaults apply: the 24 hours up to now."""
+ name = _uid()
+ location.create_tracker(TrackerName=name, **_KEEP_EVERY_SAMPLE)
+ old = _ts(-24 * 3600) # 25 hours ago — outside the default window
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[
+ {"DeviceId": "veh-1", "SampleTime": old, "Position": [1.0, 1.0]},
+ {"DeviceId": "veh-1", "SampleTime": _ts(0), "Position": [2.0, 2.0]},
+ ],
+ )
+ history = location.get_device_position_history(
+ TrackerName=name, DeviceId="veh-1"
+ )["DevicePositions"]
+ assert [p["SampleTime"] for p in history] == [_ts(0)]
+ # An explicit window reaches the older sample.
+ history = location.get_device_position_history(
+ TrackerName=name, DeviceId="veh-1",
+ StartTimeInclusive=_ts(-26 * 3600), EndTimeExclusive=_ts(1),
+ )["DevicePositions"]
+ assert [p["SampleTime"] for p in history] == [old, _ts(0)]
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_history_rejects_an_unparseable_window(location):
+ """A window bound that is not a timestamp is a ValidationException. The
+ 24-hour default belongs to the member being absent; substituting it for
+ an unparseable one answers a window the caller never asked for, and does
+ it in the same 200 as a window it did. The shapes are ones botocore
+ refuses to send, so they go over the raw wire."""
+ name = _uid()
+ location.create_tracker(TrackerName=name, **_KEEP_EVERY_SAMPLE)
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": "veh-1", "SampleTime": _ts(0), "Position": [1.0, 1.0]}],
+ )
+ history = f"/tracking/v0/trackers/{name}/devices/veh-1/list-positions"
+ for payload in (
+ {"StartTimeInclusive": "yesterday"},
+ {"EndTimeExclusive": "2026-13-45T99:00:00Z"},
+ {"StartTimeInclusive": True},
+ {"EndTimeExclusive": {"Not": "a timestamp"}},
+ ):
+ status, body = _raw_post(history, payload)
+ assert status == 400, body
+ assert next(iter(payload)) in json.dumps(body)
+
+ # A bound the parser does understand still answers over the same wire.
+ status, body = _raw_post(history, {"StartTimeInclusive": _ts(-60).timestamp()})
+ assert status == 200, body
+ assert len(body["DevicePositions"]) == 1
+ location.delete_tracker(TrackerName=name)
+
+
+# ---------------------------------------------------------------------------
+# Request validation and paging
+# ---------------------------------------------------------------------------
+
+def test_location_tracker_settings_validated(location):
+ """PositionFiltering is an enum and PricingPlan may only be
+ RequestBasedUsage (API reference, CreateTracker and UpdateTracker);
+ botocore does not check either client-side."""
+ name = _uid()
+ with pytest.raises(ClientError) as excinfo:
+ location.create_tracker(TrackerName=name, PositionFiltering="Bogus")
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ValidationException"
+ assert "positionFiltering" in err["Message"]
+ # MobileAssetTracking is still in the model's enum but no longer allowed,
+ # so the message says that instead of naming a one-member enum set. The
+ # wording is the emulator's, not measured.
+ with pytest.raises(ClientError) as excinfo:
+ location.create_tracker(TrackerName=name, PricingPlan="MobileAssetTracking")
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ValidationException"
+ assert "no longer accepted" in err["Message"]
+ assert "RequestBasedUsage" in err["Message"]
+ with pytest.raises(ClientError):
+ location.describe_tracker(TrackerName=name)
+
+ location.create_tracker(TrackerName=name, PricingPlan="RequestBasedUsage")
+ with pytest.raises(ClientError) as excinfo:
+ location.update_tracker(TrackerName=name, PositionFiltering="Bogus")
+ assert excinfo.value.response["Error"]["Code"] == "ValidationException"
+ assert location.describe_tracker(TrackerName=name)["PositionFiltering"] == "TimeBased"
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_description_length_validated(location):
+ """Description is 0..1000 (CreateTracker reference). It is refused before
+ the tracker is created. The message wording is unmeasured."""
+ name = _uid()
+ with pytest.raises(ClientError) as excinfo:
+ location.create_tracker(TrackerName=name, Description="x" * 1001)
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ValidationException"
+ assert "description" in err["Message"]
+ with pytest.raises(ClientError):
+ location.describe_tracker(TrackerName=name)
+
+ # The bound itself passes, and UpdateTracker checks it too.
+ location.create_tracker(TrackerName=name, Description="x" * 1000)
+ with pytest.raises(ClientError) as excinfo:
+ location.update_tracker(TrackerName=name, Description="x" * 1001)
+ assert excinfo.value.response["Error"]["Code"] == "ValidationException"
+ assert location.describe_tracker(TrackerName=name)["Description"] == "x" * 1000
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_kms_key_id_length_validated(location):
+ """KmsKeyId is 1..2048 (CreateTracker reference). botocore enforces the
+ minimum lengths client-side but no maximum, so the empty value goes over
+ the raw wire. Wording unmeasured."""
+ name = _uid()
+ with pytest.raises(ClientError) as excinfo:
+ location.create_tracker(TrackerName=name, KmsKeyId="k" * 2049)
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ValidationException"
+ assert "kmsKeyId" in err["Message"]
+ status, body = _raw_post(
+ "/tracking/v0/trackers", {"TrackerName": name, "KmsKeyId": ""}
+ )
+ assert status == 400, body
+ assert "kmsKeyId" in json.dumps(body)
+ with pytest.raises(ClientError):
+ location.describe_tracker(TrackerName=name)
+
+ location.create_tracker(TrackerName=name, KmsKeyId="k" * 2048)
+ assert location.describe_tracker(TrackerName=name)["KmsKeyId"] == "k" * 2048
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_tags_validated(location):
+ """Tags: at most 50 entries, keys 1..128, values 0..256, both on the
+ pattern ([\\p{L}\\p{Z}\\p{N}_.,:/=+\\-@]*) (CreateTracker reference).
+ Wordings unmeasured."""
+ name = _uid()
+ cases = (
+ {f"k{i}": "v" for i in range(51)}, # more than 50 entries
+ {"k" * 129: "v"}, # key longer than 128
+ {"k?": "v"}, # key off the pattern
+ {"k": "v" * 257}, # value longer than 256
+ {"k": "v#"}, # value off the pattern
+ )
+ for tags in cases:
+ with pytest.raises(ClientError) as excinfo:
+ location.create_tracker(TrackerName=name, Tags=tags)
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ValidationException"
+ assert "tags" in err["Message"]
+ with pytest.raises(ClientError):
+ location.describe_tracker(TrackerName=name)
+
+ # A key shorter than 1 is a minimum, which botocore refuses to send.
+ status, body = _raw_post(
+ "/tracking/v0/trackers", {"TrackerName": name, "Tags": {"": "v"}}
+ )
+ assert status == 400, body
+ assert "tags" in json.dumps(body)
+ with pytest.raises(ClientError):
+ location.describe_tracker(TrackerName=name)
+
+ # The bounds themselves pass: 50 entries, a 128-character key, an empty
+ # value, and the separators and literals the pattern allows.
+ tags = {f"k{i}": "v" for i in range(48)}
+ tags["k" * 128] = ""
+ tags["fleet name"] = "iot-rocket.local/eu=1,2:3+4@5_6"
+ location.create_tracker(TrackerName=name, Tags=tags)
+ assert location.describe_tracker(TrackerName=name)["Tags"] == tags
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_position_properties_validated(location):
+ """PositionProperties: at most 4 entries, keys 1..20, values 1..150
+ (DevicePositionUpdate reference). The whole batch is refused before
+ anything is stored. Wordings unmeasured."""
+ name = _uid()
+ location.create_tracker(TrackerName=name)
+ cases = (
+ {f"p{i}": "v" for i in range(5)}, # more than 4 entries
+ {"p" * 21: "v"}, # key longer than 20
+ {"p": "v" * 151}, # value longer than 150
+ )
+ for properties in cases:
+ with pytest.raises(ClientError) as excinfo:
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{
+ "DeviceId": "veh-1", "SampleTime": _ts(0),
+ "Position": [1.0, 1.0], "PositionProperties": properties,
+ }],
+ )
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ValidationException"
+ assert "positionProperties" in err["Message"]
+ with pytest.raises(ClientError):
+ location.get_device_position(TrackerName=name, DeviceId="veh-1")
+
+ # The minimum lengths are the ones botocore refuses to send: raw wire.
+ for properties in ({"": "v"}, {"p": ""}):
+ status, body = _raw_post(
+ f"/tracking/v0/trackers/{name}/positions",
+ {"Updates": [{"DeviceId": "veh-1", "SampleTime": _ts(0).timestamp(),
+ "Position": [1.0, 1.0], "PositionProperties": properties}]},
+ )
+ assert status == 400, body
+ assert "positionProperties" in json.dumps(body)
+ with pytest.raises(ClientError):
+ location.get_device_position(TrackerName=name, DeviceId="veh-1")
+
+ properties = {"p" * 20: "v" * 150, "a": "1", "b": "2", "c": "3"}
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": "veh-1", "SampleTime": _ts(0),
+ "Position": [1.0, 1.0], "PositionProperties": properties}],
+ )
+ stored = location.get_device_position(TrackerName=name, DeviceId="veh-1")
+ assert stored["PositionProperties"] == properties
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_accuracy_validated(location):
+ """Accuracy is a PositionalAccuracy, whose Horizontal is required and runs
+ "Minimum value of 0. Maximum value of 10000000" (API_PositionalAccuracy
+ reference). Under AccuracyBased it is the filter's own threshold, so an
+ unchecked negative value would move the threshold instead of being
+ refused. Nothing of the batch is stored. Wordings unmeasured.
+
+ Every invalid shape here is one botocore refuses to send — it checks the
+ numeric range client-side as well as the required member — so they go
+ over the raw wire, which is where another SDK or a hand-built request
+ would arrive anyway."""
+ name = _uid()
+ location.create_tracker(TrackerName=name, PositionFiltering="AccuracyBased")
+ accuracies = (
+ {"Horizontal": -1.0}, # below the minimum, and under AccuracyBased
+ # a threshold-lowering value
+ {"Horizontal": 10000000.5}, # above the maximum
+ {}, # Horizontal is required
+ {"Horizontal": "5"}, # a double, not a string
+ 5.0, # not a structure
+ )
+ for accuracy in accuracies:
+ status, body = _raw_post(
+ f"/tracking/v0/trackers/{name}/positions",
+ {"Updates": [{"DeviceId": "veh-1", "SampleTime": _ts(0).timestamp(),
+ "Position": [1.0, 1.0], "Accuracy": accuracy}]},
+ )
+ assert status == 400, body
+ assert "accuracy" in json.dumps(body)
+ with pytest.raises(ClientError):
+ location.get_device_position(TrackerName=name, DeviceId="veh-1")
+
+ # The bounds themselves pass and round-trip.
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": "veh-1", "SampleTime": _ts(0),
+ "Position": [1.0, 1.0], "Accuracy": {"Horizontal": 0.0}}],
+ )
+ assert location.get_device_position(
+ TrackerName=name, DeviceId="veh-1")["Accuracy"] == {"Horizontal": 0.0}
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_device_id_validated(location):
+ """DeviceId is the modeled Id — "Length Constraints: Minimum length of 1.
+ Maximum length of 100" on DevicePositionUpdate, BatchGetDevicePosition,
+ GetDevicePosition and GetDevicePositionHistory alike, on the pattern
+ ([-._\\p{L}\\p{N}]+). botocore checks neither the maximum nor the pattern,
+ so both reach the emulator from an ordinary SDK call. Wordings
+ unmeasured."""
+ name = _uid()
+ location.create_tracker(TrackerName=name)
+ for device_id in ("d" * 101, "veh 1"):
+ with pytest.raises(ClientError) as excinfo:
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": device_id, "SampleTime": _ts(0),
+ "Position": [1.0, 1.0]}],
+ )
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ValidationException"
+ assert "deviceId" in err["Message"]
+ for read in (location.get_device_position,
+ location.get_device_position_history):
+ with pytest.raises(ClientError) as excinfo:
+ read(TrackerName=name, DeviceId=device_id)
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ValidationException", (device_id, err)
+ assert "deviceId" in err["Message"]
+ with pytest.raises(ClientError) as excinfo:
+ location.batch_get_device_position(
+ TrackerName=name, DeviceIds=[device_id])
+ assert excinfo.value.response["Error"]["Code"] == "ValidationException"
+
+ # The bounds themselves pass, Unicode letters included: unlike the tracker
+ # name, the Id pattern is written with \p{L}\p{N} and takes them.
+ for device_id in ("d" * 100, "gerät-1"):
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": device_id, "SampleTime": _ts(0),
+ "Position": [1.0, 1.0]}],
+ )
+ stored = location.get_device_position(TrackerName=name, DeviceId=device_id)
+ assert stored["DeviceId"] == device_id
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_batch_get_device_ids_bounded(location):
+ name = _uid()
+ location.create_tracker(TrackerName=name)
+ with pytest.raises(ClientError) as excinfo:
+ location.batch_get_device_position(
+ TrackerName=name, DeviceIds=[f"d{i}" for i in range(11)]
+ )
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ValidationException"
+ assert "deviceIds" in err["Message"]
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_batch_get_rejects_invalid_device_ids(location):
+ """The list's member is an Id too, so an element that breaks it is
+ refused — not dropped from the response, which is what a device that has
+ no position looks like. botocore refuses to send a non-string element:
+ raw wire."""
+ name = _uid()
+ location.create_tracker(TrackerName=name)
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": "veh-1", "SampleTime": _ts(0), "Position": [1.0, 1.0]}],
+ )
+ for device_ids in (["veh-1", 5], ["veh-1", ""], ["veh-1", "d" * 101],
+ ["veh-1", "veh 2"]):
+ status, body = _raw_post(
+ f"/tracking/v0/trackers/{name}/get-positions", {"DeviceIds": device_ids}
+ )
+ assert status == 400, body
+ assert "deviceIds.2.member" in json.dumps(body)
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_list_trackers_pages(location):
+ """ListTrackers pages at MaxResults with a NextToken; MaxResults outside
+ 1..100 and a foreign token are ValidationExceptions."""
+ prefix = _uid("page")
+ names = sorted(f"{prefix}-{i}" for i in range(3))
+ for name in names:
+ location.create_tracker(TrackerName=name)
+ try:
+ seen, token, pages = [], None, 0
+ while True:
+ kwargs = {"MaxResults": 2}
+ if token:
+ kwargs["NextToken"] = token
+ resp = location.list_trackers(**kwargs)
+ assert len(resp["Entries"]) <= 2
+ seen.extend(e["TrackerName"] for e in resp["Entries"])
+ pages += 1
+ token = resp.get("NextToken")
+ if not token:
+ break
+ assert pages < 500
+ assert len(seen) == len(set(seen))
+ assert [n for n in seen if n.startswith(prefix)] == names
+
+ with pytest.raises(ClientError) as excinfo:
+ location.list_trackers(MaxResults=500)
+ err = excinfo.value.response["Error"]
+ assert err["Code"] == "ValidationException"
+ assert "maxResults" in err["Message"]
+ status, body = _raw_post("/tracking/v0/list-trackers", {"MaxResults": 0})
+ assert status == 400
+ with pytest.raises(ClientError) as excinfo:
+ location.list_trackers(NextToken="not-a-token")
+ assert excinfo.value.response["Error"]["Code"] == "ValidationException"
+ finally:
+ for name in names:
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_position_history_pages(location):
+ """GetDevicePositionHistory pages at MaxResults, ascending across pages,
+ and refuses a foreign token."""
+ name = _uid()
+ location.create_tracker(TrackerName=name, **_KEEP_EVERY_SAMPLE)
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[{"DeviceId": "veh-1", "SampleTime": _ts(i), "Position": [1.0, 1.0]}
+ for i in range(5)],
+ )
+ first = location.get_device_position_history(
+ TrackerName=name, DeviceId="veh-1", MaxResults=2)
+ assert [p["SampleTime"] for p in first["DevicePositions"]] == [_ts(0), _ts(1)]
+ second = location.get_device_position_history(
+ TrackerName=name, DeviceId="veh-1", MaxResults=2, NextToken=first["NextToken"])
+ assert [p["SampleTime"] for p in second["DevicePositions"]] == [_ts(2), _ts(3)]
+ third = location.get_device_position_history(
+ TrackerName=name, DeviceId="veh-1", MaxResults=2, NextToken=second["NextToken"])
+ assert [p["SampleTime"] for p in third["DevicePositions"]] == [_ts(4)]
+ assert "NextToken" not in third
+ with pytest.raises(ClientError) as excinfo:
+ location.get_device_position_history(
+ TrackerName=name, DeviceId="veh-1", NextToken="not-a-token")
+ assert excinfo.value.response["Error"]["Code"] == "ValidationException"
+ with pytest.raises(ClientError):
+ location.get_device_position_history(
+ TrackerName=name, DeviceId="veh-1", MaxResults=101)
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_position_history_pages_over_equal_timestamps(location):
+ """Two samples of one device can share SampleTime and ReceivedTime: they
+ are sent in one batch, and the batch is received once. A NextToken resumes
+ with a strict `>`, so a sort key of the two timestamps alone would drop the
+ second one whenever the page boundary falls between them."""
+ name = _uid()
+ location.create_tracker(TrackerName=name, **_KEEP_EVERY_SAMPLE)
+ location.batch_update_device_position(
+ TrackerName=name,
+ Updates=[
+ {"DeviceId": "veh-1", "SampleTime": _ts(0), "Position": [1.0, 1.0]},
+ {"DeviceId": "veh-1", "SampleTime": _ts(0), "Position": [2.0, 2.0]},
+ {"DeviceId": "veh-1", "SampleTime": _ts(1), "Position": [3.0, 3.0]},
+ ],
+ )
+ seen, token, pages = [], None, 0
+ while True:
+ kwargs = {"TrackerName": name, "DeviceId": "veh-1", "MaxResults": 1}
+ if token:
+ kwargs["NextToken"] = token
+ resp = location.get_device_position_history(**kwargs)
+ seen.extend(resp["DevicePositions"])
+ pages += 1
+ token = resp.get("NextToken")
+ if not token:
+ break
+ assert pages < 10
+ assert [p["SampleTime"] for p in seen] == [_ts(0), _ts(0), _ts(1)]
+ # The two tied samples really do share both timestamps, so only the
+ # sequence number separates them; their order between each other is not
+ # asserted.
+ assert seen[0]["ReceivedTime"] == seen[1]["ReceivedTime"]
+ assert {tuple(p["Position"]) for p in seen[:2]} == {(1.0, 1.0), (2.0, 2.0)}
+ location.delete_tracker(TrackerName=name)
+
+
+def test_location_raw_wire_requests_rejected(location):
+ """Request shapes botocore refuses to send, over the raw wire. Each is a
+ 400 and nothing is stored. The wordings are unmeasured."""
+ name = _uid()
+ location.create_tracker(TrackerName=name)
+ positions = f"/tracking/v0/trackers/{name}/positions"
+
+ # MaxResults is a modeled integer.
+ status, body = _raw_post("/tracking/v0/list-trackers", {"MaxResults": 2.5})
+ assert status == 400, body
+ assert "MaxResults" in json.dumps(body)
+
+ # An Updates entry that is not a structure.
+ status, body = _raw_post(positions, {"Updates": ["veh-1"]})
+ assert status == 400, body
+ assert "updates.1.member" in json.dumps(body)
+
+ # An Updates entry without the required DeviceId.
+ status, body = _raw_post(positions, {"Updates": [
+ {"SampleTime": _ts(0).timestamp(), "Position": [1.0, 1.0]}]})
+ assert status == 400, body
+ assert "updates.1.member.deviceId" in json.dumps(body)
+
+ # A body that is not JSON at all.
+ status, body = _raw_post(positions, raw=b"{not json")
+ assert status == 400, body
+ assert "deserialize" in json.dumps(body)
+
+ # A path that maps to no operation.
+ status, body = _raw_post(f"/tracking/v0/trackers/{name}/bogus", {})
+ assert status == 400, body
+ assert "No route for" in json.dumps(body)
+
+ with pytest.raises(ClientError):
+ location.get_device_position(TrackerName=name, DeviceId="veh-1")
+ location.delete_tracker(TrackerName=name)
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index 0e080db3..74dfcc42 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -870,6 +870,31 @@ def test_translate_round_trip_fails_a_job_left_mid_flight():
_round_trip("translate", "translate", populate, observe)
+def test_location_round_trip():
+ def populate(mod):
+ mod._trackers["trk-test"] = {
+ "TrackerName": "trk-test",
+ "TrackerArn": "arn:aws:geo:us-east-1:000000000000:tracker/trk-test",
+ "CreateTime": 1000.0,
+ "UpdateTime": 1000.0,
+ "positions": {
+ "dev-1": {
+ "latest": {"DeviceId": "dev-1", "SampleTime": 1000.0,
+ "ReceivedTime": 1000.5, "Position": [11.0, 48.0]},
+ "history": [{"DeviceId": "dev-1", "SampleTime": 1000.0,
+ "ReceivedTime": 1000.5, "Position": [11.0, 48.0]}],
+ },
+ },
+ }
+
+ def observe(mod):
+ rec = mod._trackers["trk-test"]
+ assert rec["TrackerArn"].endswith(":tracker/trk-test")
+ assert rec["positions"]["dev-1"]["latest"]["Position"] == [11.0, 48.0]
+
+ _round_trip("location", "location", populate, observe)
+
+
def test_cloudformation_round_trip():
"""CloudFormation stack metadata (stacks, events, exports, change sets)
survives a PERSIST_STATE stop/restore cycle — otherwise ListStacks /
diff --git a/tests/test_router.py b/tests/test_router.py
index 5045842f..45916101 100644
--- a/tests/test_router.py
+++ b/tests/test_router.py
@@ -449,3 +449,28 @@ def test_ministack_host_env_is_a_served_suffix(monkeypatch):
def test_container_hostname_is_a_served_suffix(monkeypatch):
monkeypatch.setenv("HOSTNAME", "core-7f3a")
assert detect_service("GET", "/status", {"host": "sns.core-7f3a:4566"}, {}) == "sns"
+
+
+def test_location_credential_scope_routes():
+ """Amazon Location signs with credential scope `geo`, not `location`
+ (botocore signingName). Under an endpoint override the host carries no
+ `geo.` — the scope map is the only routing signal left."""
+ assert detect_service(
+ "POST", "/tracking/v0/trackers", _sigv4_headers("geo"), {}
+ ) == "location"
+
+
+ "host",
+ [
+ # The modeled per-operation host prefixes in front of geo.{region}:
+ # `cp.tracking.` on the tracker control plane...
+ "cp.tracking.geo.us-east-1.localhost:4566",
+ # ...and `tracking.` on the device-position data plane.
+ "tracking.geo.us-east-1.localhost:4566",
+ ],
+)
+def test_location_host_routes(host):
+ assert detect_service(
+ "POST", "/tracking/v0/trackers", {"host": host}, {}
+ ) == "location"