Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(cloudtrail): return AWS's trail and trail status shapes (#2195)
iot-rocketdab6b1553f4a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1bf583cd..736e0f5b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **CloudTrail — trail read-backs and recording switched on at runtime** — `GetTrail` and `DescribeTrails` returned the stored `IsLogging`, `_StartedAt` and `_StoppedAt` keys and empty `S3KeyPrefix` and `SnsTopicName` members, and `GetTrailStatus` left out the six deprecated string members and moved `StopLoggingTime` when a stopped trail was stopped again; they now answer in AWS's shapes, with the start and stop times in milliseconds, and keep the last stop time. Recording switched on through `/_ministack/config` began only after the first CloudTrail API call and now starts with the next request. Contributed by @iot-rocket.- **ACM / Signer — certificate key and in-use refusals** — `ImportCertificate` accepted a call without a `PrivateKey` and now answers AWS's `ValidationException`; `DeleteCertificate` removed a certificate an Active Signer signing profile uses and now answers `ResourceInUseException`, with those profiles listed in `DescribeCertificate`'s `InUseBy`; `CancelSigningProfile` answered 200 with `{}` and now answers 204 with an empty body, as on AWS. Contributed by @iot-rocket.- **IoT — not-found messages match AWS** — a call naming a thing, thing type, thing group, certificate, CA certificate, principal, policy, policy version, job, job execution, job target or provisioning template that does not exist answered `ResourceNotFoundException` with a generic `<Resource> '<name>' not found`, and the device jobs plane (HTTP and MQTT `/rejected`) with `No job execution found for thing … and job …`; each now carries the wording AWS uses for that operation, with the same error code and status. Contributed by @iot-rocket.- **IoT Jobs — terminal job executions on the device plane** — a device's `DescribeJobExecution` (HTTP and the MQTT `get` topic) of a SUCCEEDED, FAILED, REJECTED, TIMED_OUT, CANCELED or REMOVED execution answered with the execution; it now answers `TerminalStateException` (410) and `TerminalStateReached` over MQTT, as AWS does. `UpdateJobExecution` and `CancelJobExecution` of a terminal execution now refuse with AWS's messages (over MQTT `InvalidStateTransition` with the `executionState`), a refused status such as QUEUED is checked first, and a device that reports SUCCEEDED or FAILED straight from QUEUED now stamps `startedAt`. Contributed by @iot-rocket.diff --git a/ministack/app.py b/ministack/app.pyindex 595cec44..c495dcc3 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1478,6 +1478,8 @@ async def _handle_admin_config_request(path: str, method: str, body: bytes):mod_name, var_name = key.rsplit(".", 1)try:mod = __import__(f"ministack.services.{mod_name}", fromlist=[var_name])+ # Registered so request hooks such as CloudTrail recording see the module.+ _loaded_modules.setdefault(mod_name, mod)if key in ("stepfunctions._SFN_WAIT_SCALE","translate._JOB_RUN_SECONDS",diff --git a/ministack/services/cloudtrail.py b/ministack/services/cloudtrail.pyindex e94bc57c..699ffc43 100644--- a/ministack/services/cloudtrail.py+++ b/ministack/services/cloudtrail.py@@ -46,6 +46,9 @@ _DEFAULT_EVENT_SELECTORS = [{"ReadWriteType": "All", "IncludeManagementEvents": True, "DataResources": [], "ExcludeManagementEventSources": []}]+# Logging state kept on the trail record for GetTrailStatus; not part of the Trail shape.+_TRAIL_STATE_KEYS = frozenset({"IsLogging", "_StartedAt", "_StoppedAt"})+_SCRUB_KEYS = frozenset({"secretaccesskey",@@ -499,6 +502,11 @@ def _delete_trail(body: dict):return _ok({})+def _trail_view(trail: dict) -> dict:+ """The trail record as the Trail shape: no logging state and no unset members."""+ return {k: v for k, v in trail.items() if k not in _TRAIL_STATE_KEYS and v != ""}++def _get_trail(body: dict):raw = body.get("Name", "").strip()if not raw:@@ -511,7 +519,7 @@ def _get_trail(body: dict):return _err("CloudTrailARNInvalidException", str(exc))if trail is None:return _err("TrailNotFoundException", f"Unknown trail: {name!r}", 404)- return _ok({"Trail": trail})+ return _ok({"Trail": _trail_view(trail)})def _describe_trails(body: dict):@@ -540,7 +548,7 @@ def _describe_trails(body: dict):):resolved.append(trail)all_trails = resolved- return _ok({"trailList": all_trails})+ return _ok({"trailList": [_trail_view(trail) for trail in all_trails]})def _get_trail_status(body: dict):@@ -558,7 +566,21 @@ def _get_trail_status(body: dict):"StartLoggingTime": trail.get("_StartedAt"),"StopLoggingTime": trail.get("_StoppedAt"),}- return _ok({k: v for k, v in status.items() if v is not None})+ status = {k: v for k, v in status.items() if v is not None}+ # The deprecated string members; nothing is delivered here, so the attempt times stay empty.+ status.update(+ LatestDeliveryAttemptSucceeded="",+ LatestDeliveryAttemptTime="",+ LatestNotificationAttemptSucceeded="",+ LatestNotificationAttemptTime="",+ TimeLoggingStarted=_iso_time(status.get("StartLoggingTime")),+ TimeLoggingStopped=_iso_time(status.get("StopLoggingTime")),+ )+ return _ok(status)+++def _iso_time(epoch) -> str:+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(epoch)) if epoch is not None else ""def _start_logging(body: dict):@@ -569,7 +591,7 @@ def _start_logging(body: dict):if error:return errortrail["IsLogging"] = True- trail["_StartedAt"] = int(time.time())+ trail["_StartedAt"] = round(time.time(), 3)return _ok({})@@ -580,8 +602,10 @@ def _stop_logging(body: dict):_name, _home_region, trail, error = _find_mutable_trail(raw)if error:return error+ # Only a running trail records a stop; stopping a stopped trail keeps the last time.+ if trail.get("IsLogging", True):+ trail["_StoppedAt"] = round(time.time(), 3)trail["IsLogging"] = False- trail["_StoppedAt"] = int(time.time())return _ok({})diff --git a/tests/test_cloudtrail.py b/tests/test_cloudtrail.pyindex 68687d8e..52c60ccc 100644--- a/tests/test_cloudtrail.py+++ b/tests/test_cloudtrail.py@@ -13,6 +13,7 @@ Tests are split into two sections:import jsonimport os+import timefrom datetime import datetime, timedelta, timezoneimport boto3@@ -37,6 +38,16 @@ MANAGEMENT_ADVANCED_SELECTORS = []+EMPTY_DEPRECATED_STATUS = {+ "LatestDeliveryAttemptSucceeded": "",+ "LatestDeliveryAttemptTime": "",+ "LatestNotificationAttemptSucceeded": "",+ "LatestNotificationAttemptTime": "",+ "TimeLoggingStarted": "",+ "TimeLoggingStopped": "",+}++def _client(service, region=REGION):return boto3.client(service,@@ -53,6 +64,21 @@ def _uid():return uuid.uuid4().hex[:8]+def _raw_body(client, method, **params):+ """Call an operation and return its JSON body before the SDK drops unmodeled members."""+ bodies = []+ event = f"before-parse.cloudtrail.{client.meta.method_to_api_mapping[method]}"+ handler_id = f"raw-body-{_uid()}"+ client.meta.events.register(+ event, lambda response_dict, **_: bodies.append(json.loads(response_dict["body"])), unique_id=handler_id+ )+ try:+ getattr(client, method)(**params)+ finally:+ client.meta.events.unregister(event, unique_id=handler_id)+ return bodies[0]++@pytest.fixture(scope="module")def ct():return _client("cloudtrail")@@ -114,6 +140,27 @@ def test_get_trail(ct):assert "TrailARN" in resp["Trail"]+def test_get_trail_and_describe_trails_return_the_trail_shape(ct):+ name = f"trail-shape-{_uid()}"+ created = ct.create_trail(Name=name, S3BucketName="bucket")+ ct.start_logging(Name=name)+ ct.stop_logging(Name=name)+ expected = {+ "Name": name,+ "S3BucketName": "bucket",+ "IncludeGlobalServiceEvents": True,+ "IsMultiRegionTrail": False,+ "LogFileValidationEnabled": False,+ "HomeRegion": REGION,+ "TrailARN": created["TrailARN"],+ "HasCustomEventSelectors": False,+ "HasInsightSelectors": False,+ "IsOrganizationTrail": False,+ }+ assert _raw_body(ct, "get_trail", Name=name)["Trail"] == expected+ assert _raw_body(ct, "describe_trails", trailNameList=[name])["trailList"] == [expected]++def test_get_trail_by_arn(ct):name = f"trail-get-arn-{_uid()}"created = ct.create_trail(Name=name, S3BucketName="bucket")@@ -352,15 +399,30 @@ def test_new_trail_is_not_logging_until_started(ct):ct.create_trail(Name=name, S3BucketName="bucket")status = ct.get_trail_status(Name=name)status.pop("ResponseMetadata")- assert status == {"IsLogging": False}+ assert status == {"IsLogging": False, **EMPTY_DEPRECATED_STATUS}ct.start_logging(Name=name)status = ct.get_trail_status(Name=name)status.pop("ResponseMetadata")- assert status.keys() == {"IsLogging", "StartLoggingTime"}+ assert status.keys() == {"IsLogging", "StartLoggingTime", *EMPTY_DEPRECATED_STATUS}assert status["IsLogging"] is True+def test_get_trail_status_returns_the_deprecated_string_members(ct):+ name = f"trail-deprecated-{_uid()}"+ ct.create_trail(Name=name, S3BucketName="bucket")+ ct.start_logging(Name=name)+ ct.stop_logging(Name=name)+ status = ct.get_trail_status(Name=name)+ assert {key: status[key] for key in EMPTY_DEPRECATED_STATUS} == {+ **EMPTY_DEPRECATED_STATUS,+ "TimeLoggingStarted": status["StartLoggingTime"].strftime("%Y-%m-%dT%H:%M:%SZ"),+ "TimeLoggingStopped": status["StopLoggingTime"].strftime("%Y-%m-%dT%H:%M:%SZ"),+ }+ raw = _raw_body(ct, "get_trail_status", Name=name)+ assert all(isinstance(raw[key], float) for key in ("StartLoggingTime", "StopLoggingTime"))++def test_get_trail_status_not_found(ct):with pytest.raises(ClientError):ct.get_trail_status(Name=f"nonexistent-{_uid()}")@@ -405,6 +467,24 @@ def test_restarted_trail_keeps_stop_logging_time(ct):assert status["StartLoggingTime"] >= stopped["StartLoggingTime"]+def test_stop_logging_records_a_stop_only_on_a_logging_trail(ct):+ name = f"trail-stop-{_uid()}"+ ct.create_trail(Name=name, S3BucketName="bucket")+ ct.stop_logging(Name=name)+ status = ct.get_trail_status(Name=name)+ assert "StopLoggingTime" not in status+ assert status["TimeLoggingStopped"] == ""++ ct.start_logging(Name=name)+ ct.stop_logging(Name=name)+ stopped = ct.get_trail_status(Name=name)+ time.sleep(1.1)+ ct.stop_logging(Name=name)+ status = ct.get_trail_status(Name=name)+ assert status["StopLoggingTime"] == stopped["StopLoggingTime"]+ assert status["TimeLoggingStopped"] == stopped["TimeLoggingStopped"]++def test_list_trails_returns_summaries(ct):name = f"trail-list-{_uid()}"ct.create_trail(Name=name, S3BucketName="bucket")@@ -987,6 +1067,25 @@ def test_cloudtrail_calls_not_self_recorded(ct):assert len(after) == len(before)+def test_recording_enabled_through_config_records_before_any_cloudtrail_call(monkeypatch):+ import asyncio++ import ministack.app as app+ from ministack.core.responses import AccountRegionScopedDict+ from ministack.services import cloudtrail++ monkeypatch.delenv("CLOUDTRAIL_RECORDING", raising=False)+ monkeypatch.setattr(app, "_loaded_modules", {})+ monkeypatch.setattr(cloudtrail, "_recording_enabled", False)+ monkeypatch.setattr(cloudtrail, "_events", AccountRegionScopedDict())+ body = json.dumps({"cloudtrail._recording_enabled": "true"}).encode()+ asyncio.run(app._handle_admin_config_request("/_ministack/config", "POST", body))++ headers = {"x-amz-target": "AmazonSQS.ListQueues"}+ app._maybe_record_cloudtrail("sqs", "POST", "/", headers, b"{}", {}, "req-1", REGION)+ assert [event["EventName"] for event in cloudtrail._get_event_queue()] == ["ListQueues"]++def test_recording_disabled_no_new_events(ct, s3):"""Disabling recording stops new events from being appended."""requests.post(