Skip to content

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

Regionalize CloudTrail state (#1225)

Ian Oberst8d3867f99383
diff --git a/ministack/core/persistence.py b/ministack/core/persistence.py
index 4f1cb7f6..334ea89f 100644
--- a/ministack/core/persistence.py
+++ b/ministack/core/persistence.py
@@ -42,6 +42,7 @@ SERVICE_STATE_FORMAT_VERSIONS = {
"ecs": 3,
"resource_groups": 3,
"codebuild": 3,
+ "cloudtrail": 3,
"mq": 3,
"mwaa": 3,
"servicediscovery": 3,
diff --git a/ministack/services/cloudtrail.py b/ministack/services/cloudtrail.py
index d0b72473..d9802e3a 100644
--- a/ministack/services/cloudtrail.py
+++ b/ministack/services/cloudtrail.py
@@ -15,6 +15,7 @@ Supported operations:
"""
import collections
+import copy
import json
import logging
import os
@@ -22,17 +23,23 @@ import time
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.persistence import load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, get_region, new_uuid
+from ministack.core.responses import (
+ AccountRegionScopedDict,
+ AccountScopedDict,
+ get_account_id,
+ get_region,
+ new_uuid,
+)
logger = logging.getLogger("cloudtrail")
_recording_enabled: bool = os.environ.get("CLOUDTRAIL_RECORDING", "0") == "1"
_MAX_EVENTS: int = int(os.environ.get("CLOUDTRAIL_MAX_EVENTS", "10000"))
-_events = AccountScopedDict() # "events" -> deque[event_dict]
-_trails = AccountScopedDict() # trail_name -> trail_record
-_event_selectors = AccountScopedDict() # trail_name -> list[EventSelector]
-_trail_tags = AccountScopedDict() # trail_arn -> {tag_key: tag_value}
+_events = AccountRegionScopedDict() # "events" -> deque[event_dict]
+_trails = AccountRegionScopedDict() # trail_name -> trail_record, scoped to HomeRegion
+_event_selectors = AccountRegionScopedDict() # trail_name -> list[EventSelector], scoped to HomeRegion
+_trail_tags = AccountScopedDict() # trail_arn -> {tag_key: tag_value}
_SCRUB_KEYS = frozenset(
{
@@ -59,27 +66,72 @@ def reset():
def get_state():
# Trail config persists; events are ephemeral (timestamps meaningless after restart).
return {
- "trails": {k: v for k, v in _trails.items()},
- "event_selectors": {k: v for k, v in _event_selectors.items()},
- "trail_tags": {k: v for k, v in _trail_tags.items()},
+ "trails": copy.deepcopy(_trails),
+ "event_selectors": copy.deepcopy(_event_selectors),
+ "trail_tags": copy.deepcopy(_trail_tags),
}
def restore_state(data):
if not isinstance(data, dict):
return
- for k, v in data.get("trails", {}).items():
- _trails[k] = v
- for k, v in data.get("event_selectors", {}).items():
- _event_selectors[k] = v
- for k, v in data.get("trail_tags", {}).items():
- _trail_tags[k] = v
+ trail_regions = _restore_trails(data.get("trails", {}))
+ _restore_event_selectors(data.get("event_selectors", {}), trail_regions)
+ _restore_trail_tags(data.get("trail_tags", {}))
def load_persisted_state(data):
restore_state(data)
+def _restore_trails(saved) -> dict[tuple[str, str], str]:
+ trail_regions: dict[tuple[str, str], str] = {}
+ if isinstance(saved, AccountRegionScopedDict):
+ _trails.update(saved)
+ for (account_id, region, name), trail in saved.all_items():
+ trail_regions[(account_id, name)] = _trail_home_region(trail, fallback_region=region)
+ return trail_regions
+
+ for account_id, name, trail in _legacy_account_items(saved):
+ trail_copy = copy.deepcopy(trail)
+ region = _trail_home_region(trail_copy)
+ if isinstance(trail_copy, dict):
+ trail_copy.setdefault("HomeRegion", region)
+ _trails.set_scoped(account_id, region, name, trail_copy)
+ trail_regions[(account_id, name)] = region
+ return trail_regions
+
+
+def _restore_event_selectors(saved, trail_regions: dict[tuple[str, str], str]):
+ if isinstance(saved, AccountRegionScopedDict):
+ _event_selectors.update(saved)
+ return
+
+ boot_region = get_region()
+ for account_id, name, selectors in _legacy_account_items(saved):
+ region = trail_regions.get((account_id, name), boot_region)
+ _event_selectors.set_scoped(account_id, region, name, copy.deepcopy(selectors))
+
+
+def _restore_trail_tags(saved):
+ if isinstance(saved, AccountScopedDict):
+ _trail_tags.update(saved)
+ return
+ if isinstance(saved, dict):
+ for arn, tags in saved.items():
+ _trail_tags[arn] = copy.deepcopy(tags)
+
+
+def _legacy_account_items(saved):
+ if isinstance(saved, AccountScopedDict):
+ for (account_id, key), value in saved._data.items():
+ yield account_id, key, value
+ elif isinstance(saved, dict):
+ account_id = get_account_id()
+ for key, value in saved.items():
+ yield account_id, key, value
+
+
def _scrub(params: dict) -> dict:
if not isinstance(params, dict):
return {}
@@ -93,6 +145,113 @@ def _trail_arn(name: str) -> str:
return f"arn:aws:cloudtrail:{get_region()}:{get_account_id()}:trail/{name}"
+def _trail_home_region(trail: dict | None, fallback_region: str | None = None) -> str:
+ if isinstance(trail, dict):
+ if trail.get("HomeRegion"):
+ return trail["HomeRegion"]
+ arn = trail.get("TrailARN")
+ if arn:
+ try:
+ spec, _ = _parse_trail_arn(arn)
+ if spec.region:
+ return spec.region
+ except ValueError:
+ pass
+ return fallback_region or get_region()
+
+
+def _account_trail_items(account_id: str | None = None):
+ account_id = account_id or get_account_id()
+ for (trail_account_id, region, name), trail in _trails.all_items():
+ if trail_account_id == account_id:
+ yield region, name, trail
+
+
+def _visible_trail_items(*, include_shadow_trails: bool = True):
+ account_id = get_account_id()
+ region = get_region()
+ visible = []
+ seen = set()
+ for name, trail in _trails.items_scoped(account_id, region):
+ visible.append((region, name, trail))
+ seen.add(name)
+ for home_region, name, trail in _account_trail_items(account_id):
+ if home_region == region or name in seen:
+ continue
+ if include_shadow_trails and trail.get("IsMultiRegionTrail", False):
+ visible.append((home_region, name, trail))
+ seen.add(name)
+ return visible
+
+
+def _find_any_account_trail(name: str):
+ for home_region, trail_name, trail in _account_trail_items():
+ if trail_name == name:
+ return home_region, trail
+ return None, None
+
+
+def _has_peer_region_trail(name: str, home_region: str) -> bool:
+ for peer_region, trail_name, _trail in _account_trail_items():
+ if trail_name == name and peer_region != home_region:
+ return True
+ return False
+
+
+def _find_visible_trail(raw: str):
+ if raw.startswith("arn:"):
+ spec, name = _parse_trail_arn(raw)
+ if spec.account_id != get_account_id():
+ return name, None, None
+ trail = _trails.get_scoped(spec.account_id, spec.region, name)
+ if trail is None or trail.get("TrailARN") != str(spec):
+ return name, None, None
+ return name, spec.region, trail
+
+ trail = _trails.get(raw)
+ if trail is not None:
+ return raw, get_region(), trail
+
+ for home_region, name, trail in _account_trail_items():
+ if name == raw and trail.get("IsMultiRegionTrail", False):
+ return name, home_region, trail
+ return raw, None, None
+
+
+def _invalid_home_region_error(name: str, home_region: str):
+ return _err(
+ "InvalidHomeRegionException",
+ f"Trail {name!r} must be managed from its home region {home_region}.",
+ )
+
+
+def _find_mutable_trail(raw: str):
+ if raw.startswith("arn:"):
+ try:
+ spec, name = _parse_trail_arn(raw)
+ except ValueError as exc:
+ return None, None, None, _err("CloudTrailARNInvalidException", str(exc))
+ if spec.account_id != get_account_id():
+ return name, None, None, _err("TrailNotFoundException", f"Unknown trail: {raw!r}", 404)
+ trail = _trails.get_scoped(spec.account_id, spec.region, name)
+ if trail is None or trail.get("TrailARN") != str(spec):
+ return name, None, None, _err("TrailNotFoundException", f"Unknown trail: {raw!r}", 404)
+ if spec.region != get_region():
+ if trail.get("IsMultiRegionTrail", False):
+ return name, spec.region, trail, _invalid_home_region_error(name, spec.region)
+ return name, None, None, _err("TrailNotFoundException", f"Unknown trail: {raw!r}", 404)
+ return name, spec.region, trail, None
+
+ trail = _trails.get(raw)
+ if trail is not None:
+ return raw, get_region(), trail, None
+
+ home_region, trail = _find_any_account_trail(raw)
+ if trail is not None and trail.get("IsMultiRegionTrail", False):
+ return raw, home_region, trail, _invalid_home_region_error(raw, home_region)
+ return raw, None, None, _err("TrailNotFoundException", f"Unknown trail: {raw!r}", 404)
+
+
def _parse_trail_arn(arn: str):
try:
spec = parse_arn(arn)
@@ -118,7 +277,7 @@ def _trail_name_from_read_arn(arn: str) -> str | None:
spec, trail_name = _parse_trail_arn(arn)
if spec.account_id != get_account_id():
return None
- trail = _trails.get(trail_name)
+ trail = _trails.get_scoped(spec.account_id, spec.region, trail_name)
if trail is None or trail.get("TrailARN") != str(spec):
return None
return trail_name
@@ -301,7 +460,7 @@ def _validate_trail_arn(arn: str, *, require_existing: bool = False):
return _err("CloudTrailARNInvalidException", "Invalid CloudTrail trail ARN.")
if require_existing:
- trail = _trails.get(trail_name)
+ trail = _trails.get_scoped(spec.account_id, spec.region, trail_name)
if trail is None or trail.get("TrailARN") != str(spec):
return _err("ResourceNotFoundException", f"Unknown trail: {arn!r}")
@@ -321,7 +480,9 @@ def _create_trail(body: dict):
name = body.get("Name", "").strip()
if not name:
return _err("InvalidTrailNameException", "Trail name is required.")
- if _trails.get(name) is not None:
+ is_multi_region = body.get("IsMultiRegionTrail", False)
+ _, visible_trail = _find_any_account_trail(name) if is_multi_region else (None, None)
+ if visible_trail is not None or _find_visible_trail(name)[2] is not None:
return _err("TrailAlreadyExistsException", f"Trail {name!r} already exists.")
arn = _trail_arn(name)
trail = {
@@ -330,7 +491,7 @@ def _create_trail(body: dict):
"S3KeyPrefix": body.get("S3KeyPrefix", ""),
"SnsTopicName": body.get("SnsTopicName", ""),
"IncludeGlobalServiceEvents": body.get("IncludeGlobalServiceEvents", True),
- "IsMultiRegionTrail": body.get("IsMultiRegionTrail", False),
+ "IsMultiRegionTrail": is_multi_region,
"LogFileValidationEnabled": body.get("EnableLogFileValidation", False),
"HomeRegion": get_region(),
"TrailARN": arn,
@@ -366,13 +527,11 @@ def _delete_trail(body: dict):
raw = body.get("Name", "").strip()
if not raw:
return _err("InvalidTrailNameException", "Trail name is required.")
- name, error = _resolve_trail_name_or_error(raw)
+ name, home_region, _trail, error = _find_mutable_trail(raw)
if error:
return error
- if _trails.get(name) is None:
- return _err("TrailNotFoundException", f"Unknown trail: {name!r}", 404)
- del _trails[name]
- _event_selectors.pop(name, None)
+ _trails.pop_scoped(get_account_id(), home_region, name, None)
+ _event_selectors.pop_scoped(get_account_id(), home_region, name, None)
return _ok({})
@@ -382,10 +541,10 @@ def _get_trail(body: dict):
return _err("InvalidTrailNameException", "Trail name is required.")
if raw.startswith("arn:") and _is_non_aws_trail_arn_partition(raw):
return _err("InvalidTrailNameException", "Invalid trail name.")
- name, error = _resolve_trail_name_or_error(raw, allow_cross_region_arn=True)
- if error:
- return error
- trail = _trails.get(name)
+ try:
+ name, _home_region, trail = _find_visible_trail(raw)
+ except ValueError as exc:
+ return _err("CloudTrailARNInvalidException", str(exc))
if trail is None:
return _err("TrailNotFoundException", f"Unknown trail: {name!r}", 404)
return _ok({"Trail": trail})
@@ -393,15 +552,30 @@ def _get_trail(body: dict):
def _describe_trails(body: dict):
trail_names = body.get("trailNameList", [])
- all_trails = [v for _, v in _trails.items()]
+ include_shadow_trails = body.get("includeShadowTrails", True)
+ all_trails = [
+ trail
+ for _home_region, _name, trail in _visible_trail_items(
+ include_shadow_trails=include_shadow_trails
+ )
+ ]
if trail_names:
- resolved = set()
+ resolved = []
for trail_name in trail_names:
- name, error = _resolve_trail_name_or_error(trail_name, allow_cross_region_arn=True)
- if error:
- return error
- resolved.add(name)
- all_trails = [t for t in all_trails if t["Name"] in resolved]
+ try:
+ _name, home_region, trail = _find_visible_trail(trail_name)
+ except ValueError as exc:
+ return _err("CloudTrailARNInvalidException", str(exc))
+ if (
+ trail is not None
+ and (
+ include_shadow_trails
+ or home_region == get_region()
+ or not trail.get("IsMultiRegionTrail", False)
+ )
+ ):
+ resolved.append(trail)
+ all_trails = resolved
return _ok({"trailList": all_trails})
@@ -409,10 +583,10 @@ def _get_trail_status(body: dict):
raw = body.get("Name", "").strip()
if not raw:
return _err("InvalidTrailNameException", "Trail name is required.")
- name, error = _resolve_trail_name_or_error(raw, allow_cross_region_arn=True)
- if error:
- return error
- trail = _trails.get(name)
+ try:
+ name, _home_region, trail = _find_visible_trail(raw)
+ except ValueError as exc:
+ return _err("CloudTrailARNInvalidException", str(exc))
if trail is None:
return _err("TrailNotFoundException", f"Unknown trail: {name!r}", 404)
now = int(time.time())
@@ -433,12 +607,9 @@ def _start_logging(body: dict):
raw = body.get("Name", "").strip()
if not raw:
return _err("InvalidTrailNameException", "Trail name is required.")
- name, error = _resolve_trail_name_or_error(raw)
+ _name, _home_region, trail, error = _find_mutable_trail(raw)
if error:
return error
- trail = _trails.get(name)
- if trail is None:
- return _err("TrailNotFoundException", f"Unknown trail: {name!r}", 404)
trail["IsLogging"] = True
trail["_StartedAt"] = int(time.time())
trail.pop("_StoppedAt", None)
@@ -449,12 +620,9 @@ def _stop_logging(body: dict):
raw = body.get("Name", "").strip()
if not raw:
return _err("InvalidTrailNameException", "Trail name is required.")
- name, error = _resolve_trail_name_or_error(raw)
+ _name, _home_region, trail, error = _find_mutable_trail(raw)
if error:
return error
- trail = _trails.get(name)
- if trail is None:
- return _err("TrailNotFoundException", f"Unknown trail: {name!r}", 404)
trail["IsLogging"] = False
trail["_StoppedAt"] = int(time.time())
return _ok({})
@@ -468,7 +636,7 @@ def _list_trails(body: dict):
"Name": t["Name"],
"HomeRegion": t.get("HomeRegion", get_region()),
}
- for t in _trails.values()
+ for _home_region, _name, t in _visible_trail_items()
]
out = {"Trails": summaries}
return _ok(out)
@@ -478,12 +646,15 @@ def _update_trail(body: dict):
raw = body.get("Name", "").strip()
if not raw:
return _err("InvalidTrailNameException", "Trail name is required.")
- name, error = _resolve_trail_name_or_error(raw)
+ name, home_region, trail, error = _find_mutable_trail(raw)
if error:
return error
- trail = _trails.get(name)
- if trail is None:
- return _err("TrailNotFoundException", f"Unknown trail: {name!r}", 404)
+ if (
+ body.get("IsMultiRegionTrail") is True
+ and not trail.get("IsMultiRegionTrail", False)
+ and _has_peer_region_trail(name, home_region)
+ ):
+ return _err("TrailAlreadyExistsException", f"Trail {name!r} already exists.")
for src, dst in (
("S3BucketName", "S3BucketName"),
("S3KeyPrefix", "S3KeyPrefix"),
@@ -531,23 +702,25 @@ def _put_event_selectors(body: dict):
raw = body.get("TrailName", "").strip()
if not raw:
return _err("InvalidTrailNameException", "Trail name is required.")
- name, error = _resolve_existing_trail_name_or_error(raw)
+ name, home_region, trail, error = _find_mutable_trail(raw)
if error:
return error
selectors = body.get("EventSelectors", [])
- _event_selectors[name] = selectors
- return _ok({"TrailARN": _trail_arn(name), "EventSelectors": selectors})
+ _event_selectors.set_scoped(get_account_id(), home_region, name, selectors)
+ return _ok({"TrailARN": trail["TrailARN"], "EventSelectors": selectors})
def _get_event_selectors(body: dict):
raw = body.get("TrailName", "").strip()
if not raw:
return _err("InvalidTrailNameException", "Trail name is required.")
- name, error = _resolve_existing_trail_name_or_error(raw, allow_cross_region_arn=True)
- if error:
- return error
- trail = _trails.get(name) or {}
- selectors = _event_selectors.get(name) or []
+ try:
+ name, home_region, trail = _find_visible_trail(raw)
+ except ValueError as exc:
+ return _err("CloudTrailARNInvalidException", str(exc))
+ if trail is None:
+ return _err("TrailNotFoundException", f"Unknown trail: {raw!r}", 404)
+ selectors = _event_selectors.get_scoped(get_account_id(), home_region, name) or []
return _ok(
{
"TrailARN": trail.get("TrailARN", _trail_arn(name)),
diff --git a/tests/test_cloudtrail.py b/tests/test_cloudtrail.py
index 8e794141..170e436b 100644
--- a/tests/test_cloudtrail.py
+++ b/tests/test_cloudtrail.py
@@ -11,6 +11,8 @@ Tests are split into two sections:
- Event recording: LookupEvents and filter variants (require recording enabled)
"""
+import json
+import os
import time
from datetime import datetime, timedelta, timezone
@@ -19,8 +21,9 @@ import pytest
import requests
from botocore.exceptions import ClientError
-ENDPOINT = "http://localhost:4566"
+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
REGION = "us-east-1"
+WEST_REGION = "us-west-2"
def _client(service, region=REGION):
@@ -141,7 +144,7 @@ def test_get_trail_does_not_resolve_foreign_region_arn_by_tail(ct):
def test_read_trail_by_arn_from_different_request_region(ct):
name = f"trail-cross-region-read-{_uid()}"
arn = ct.create_trail(Name=name, S3BucketName="bucket")["TrailARN"]
- west_ct = _client("cloudtrail", region="us-west-2")
+ west_ct = _client("cloudtrail", region=WEST_REGION)
get_resp = west_ct.get_trail(Name=arn)
assert get_resp["Trail"]["Name"] == name
@@ -153,6 +156,132 @@ def test_read_trail_by_arn_from_different_request_region(ct):
assert [trail["TrailARN"] for trail in desc_resp["trailList"]] == [arn]
+def test_single_region_trail_is_visible_only_from_home_region_by_name(ct):
+ name = f"trail-sr-scope-{_uid()}"
+ arn = ct.create_trail(Name=name, S3BucketName="bucket")["TrailARN"]
+ west_ct = _client("cloudtrail", region=WEST_REGION)
+
+ with pytest.raises(ClientError) as exc:
+ west_ct.get_trail(Name=name)
+ assert exc.value.response["Error"]["Code"] == "TrailNotFoundException"
+
+ assert not any(t["Name"] == name for t in west_ct.describe_trails()["trailList"])
+ assert not any(t["Name"] == name for t in west_ct.list_trails()["Trails"])
+ assert west_ct.describe_trails(trailNameList=[name])["trailList"] == []
+
+ # A full ARN is unambiguous and remains readable across regions.
+ assert west_ct.get_trail(Name=arn)["Trail"]["Name"] == name
+
+
+def test_multi_region_trail_is_shadow_visible_from_peer_region(ct):
+ name = f"trail-mr-scope-{_uid()}"
+ arn = ct.create_trail(
+ Name=name,
+ S3BucketName="bucket",
+ IsMultiRegionTrail=True,
+ )["TrailARN"]
+ selectors = [{"ReadWriteType": "All", "IncludeManagementEvents": True, "DataResources": []}]
+ ct.put_event_selectors(TrailName=name, EventSelectors=selectors)
+ west_ct = _client("cloudtrail", region=WEST_REGION)
+
+ assert west_ct.get_trail(Name=name)["Trail"]["HomeRegion"] == REGION
+ assert west_ct.get_trail_status(Name=name)["IsLogging"] is True
+ assert west_ct.describe_trails(trailNameList=[name])["trailList"][0]["TrailARN"] == arn
+ assert any(t["TrailARN"] == arn for t in west_ct.describe_trails()["trailList"])
+ assert any(t["TrailARN"] == arn for t in west_ct.list_trails()["Trails"])
+ assert west_ct.get_event_selectors(TrailName=name)["EventSelectors"] == selectors
+
+
+def test_describe_trails_can_exclude_multi_region_shadow_trails(ct):
+ name = f"trail-mr-shadow-{_uid()}"
+ arn = ct.create_trail(
+ Name=name,
+ S3BucketName="bucket",
+ IsMultiRegionTrail=True,
+ )["TrailARN"]
+ west_ct = _client("cloudtrail", region=WEST_REGION)
+
+ assert any(t["TrailARN"] == arn for t in west_ct.describe_trails()["trailList"])
+ assert west_ct.describe_trails(includeShadowTrails=False)["trailList"] == []
+ assert west_ct.describe_trails(
+ trailNameList=[name], includeShadowTrails=False
+ )["trailList"] == []
+
+
+def test_mutations_from_peer_region_follow_home_region_rules(ct):
+ mr_name = f"trail-mr-mutate-{_uid()}"
+ sr_name = f"trail-sr-mutate-{_uid()}"
+ mr_arn = ct.create_trail(
+ Name=mr_name,
+ S3BucketName="bucket",
+ IsMultiRegionTrail=True,
+ )["TrailARN"]
+ ct.create_trail(Name=sr_name, S3BucketName="bucket")
+ west_ct = _client("cloudtrail", region=WEST_REGION)
+
+ for operation, kwargs in (
+ (west_ct.update_trail, {"Name": mr_name, "S3BucketName": "west"}),
+ (west_ct.stop_logging, {"Name": mr_name}),
+ (
+ west_ct.put_event_selectors,
+ {
+ "TrailName": mr_name,
+ "EventSelectors": [{"ReadWriteType": "All", "IncludeManagementEvents": True}],
+ },
+ ),
+ (west_ct.delete_trail, {"Name": mr_name}),
+ ):
+ with pytest.raises(ClientError) as exc:
+ operation(**kwargs)
+ assert exc.value.response["Error"]["Code"] == "InvalidHomeRegionException"
+
+ with pytest.raises(ClientError) as exc:
+ west_ct.update_trail(Name=mr_arn, S3BucketName="west")
+ assert exc.value.response["Error"]["Code"] == "InvalidHomeRegionException"
+
+ with pytest.raises(ClientError) as exc:
+ west_ct.update_trail(Name=sr_name, S3BucketName="west")
+ assert exc.value.response["Error"]["Code"] == "TrailNotFoundException"
+
+ ct.update_trail(Name=mr_name, S3BucketName="east")
+ assert ct.get_trail(Name=mr_name)["Trail"]["S3BucketName"] == "east"
+
+
+def test_multi_region_trail_name_reserves_all_regions(ct):
+ name = f"trail-name-scope-{_uid()}"
+ ct.create_trail(Name=name, S3BucketName="bucket", IsMultiRegionTrail=True)
+ west_ct = _client("cloudtrail", region=WEST_REGION)
+
+ with pytest.raises(ClientError) as exc:
+ west_ct.create_trail(Name=name, S3BucketName="bucket")
+ assert exc.value.response["Error"]["Code"] == "TrailAlreadyExistsException"
+
+ single_region_name = f"trail-sr-name-scope-{_uid()}"
+ east_arn = ct.create_trail(Name=single_region_name, S3BucketName="east")["TrailARN"]
+ west_arn = west_ct.create_trail(Name=single_region_name, S3BucketName="west")["TrailARN"]
+
+ assert east_arn != west_arn
+ assert ct.get_trail(Name=single_region_name)["Trail"]["S3BucketName"] == "east"
+ assert west_ct.get_trail(Name=single_region_name)["Trail"]["S3BucketName"] == "west"
+
+ west_ct.delete_trail(Name=single_region_name)
+ assert ct.get_trail(Name=single_region_name)["Trail"]["TrailARN"] == east_arn
+
+
+def test_update_trail_to_multi_region_rejects_peer_region_name_collision(ct):
+ name = f"trail-convert-collision-{_uid()}"
+ ct.create_trail(Name=name, S3BucketName="east")
+ west_ct = _client("cloudtrail", region=WEST_REGION)
+ west_ct.create_trail(Name=name, S3BucketName="west")
+
+ with pytest.raises(ClientError) as exc:
+ ct.update_trail(Name=name, IsMultiRegionTrail=True)
+ assert exc.value.response["Error"]["Code"] == "TrailAlreadyExistsException"
+
+ assert ct.get_trail(Name=name)["Trail"]["IsMultiRegionTrail"] is False
+ assert west_ct.get_trail(Name=name)["Trail"]["S3BucketName"] == "west"
+
+
def test_get_trail_not_found(ct):
with pytest.raises(ClientError) as exc:
ct.get_trail(Name=f"nonexistent-{_uid()}")
@@ -439,7 +568,7 @@ def test_add_tags_missing_aws_partition_trail_arn_returns_resource_not_found(ct)
def test_add_tags_rejects_foreign_region_trail_arn(ct):
name = f"trail-tags-foreign-{_uid()}"
arn = ct.create_trail(Name=name, S3BucketName="bucket")["TrailARN"]
- foreign_arn = arn.replace(f":{REGION}:", ":us-west-2:")
+ foreign_arn = arn.replace(f":{REGION}:", f":{WEST_REGION}:")
with pytest.raises(ClientError) as exc:
ct.add_tags(ResourceId=foreign_arn, TagsList=[{"Key": "env", "Value": "test"}])
@@ -619,6 +748,37 @@ def test_lookup_max_results(ct, s3):
assert len(resp["Events"]) <= 3
+def test_lookup_events_are_region_scoped(ct):
+ east_queue = f"ct-east-{_uid()}"
+ west_queue = f"ct-west-{_uid()}"
+ east_sqs = _client("sqs", region=REGION)
+ west_sqs = _client("sqs", region=WEST_REGION)
+ west_ct = _client("cloudtrail", region=WEST_REGION)
+
+ east_sqs.create_queue(QueueName=east_queue)
+ west_sqs.create_queue(QueueName=west_queue)
+
+ east_events = ct.lookup_events(
+ LookupAttributes=[{"AttributeKey": "EventName", "AttributeValue": "CreateQueue"}]
+ )["Events"]
+ west_events = west_ct.lookup_events(
+ LookupAttributes=[{"AttributeKey": "EventName", "AttributeValue": "CreateQueue"}]
+ )["Events"]
+
+ def event_regions_for_queue(events, queue_name):
+ regions = set()
+ for event in events:
+ payload = json.loads(event["CloudTrailEvent"])
+ if payload.get("requestParameters", {}).get("QueueName") == queue_name:
+ regions.add(payload["awsRegion"])
+ return regions
+
+ assert event_regions_for_queue(east_events, east_queue) == {REGION}
+ assert event_regions_for_queue(east_events, west_queue) == set()
+ assert event_regions_for_queue(west_events, west_queue) == {WEST_REGION}
+ assert event_regions_for_queue(west_events, east_queue) == set()
+
+
def test_lookup_newest_first(ct, s3):
b1 = f"ct-ord1-{_uid()}"
b2 = f"ct-ord2-{_uid()}"
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index 8cf7296a..58902f4a 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -2538,6 +2538,221 @@ def test_iot_region_scoped_state_is_rejected_by_v2_reader(
assert persistence.load_state("iot") is None
+def test_cloudtrail_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path):
+ """A rollback binary must reject CloudTrail's regional schema instead of
+ accepting it as v2 and dropping non-boot-region trails."""
+ import json as _json
+
+ from ministack.core.responses import AccountRegionScopedDict
+
+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)
+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
+
+ trails = AccountRegionScopedDict()
+ trails.set_scoped(
+ "000000000000",
+ "us-west-2",
+ "regional-trail",
+ {
+ "Name": "regional-trail",
+ "HomeRegion": "us-west-2",
+ "TrailARN": "arn:aws:cloudtrail:us-west-2:000000000000:trail/regional-trail",
+ },
+ )
+ persistence.save_state("cloudtrail", {"trails": trails})
+
+ raw = _json.loads((tmp_path / "cloudtrail.json").read_text())
+ assert raw["__ministack_format__"] == 3
+ loaded_trails = persistence.load_state("cloudtrail")["trails"]
+ assert loaded_trails.get_scoped(
+ "000000000000", "us-west-2", "regional-trail"
+ )["HomeRegion"] == "us-west-2"
+
+ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})
+ assert persistence.load_state("cloudtrail") is None
+
+
+def test_cloudtrail_region_scoped_v3_state_round_trips_idempotently(
+ monkeypatch, tmp_path
+):
+ import json as _json
+
+ from ministack.core.responses import AccountRegionScopedDict
+
+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)
+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
+
+ trails = AccountRegionScopedDict()
+ trails.set_scoped(
+ "000000000000",
+ "us-west-2",
+ "regional-trail",
+ {
+ "Name": "regional-trail",
+ "HomeRegion": "us-west-2",
+ "TrailARN": "arn:aws:cloudtrail:us-west-2:000000000000:trail/regional-trail",
+ },
+ )
+ selectors = AccountRegionScopedDict()
+ selectors.set_scoped(
+ "000000000000",
+ "us-west-2",
+ "regional-trail",
+ [{"ReadWriteType": "All", "IncludeManagementEvents": True}],
+ )
+
+ persistence.save_state(
+ "cloudtrail",
+ {"trails": trails, "event_selectors": selectors},
+ )
+ first_snapshot = _json.loads((tmp_path / "cloudtrail.json").read_text())
+ loaded = persistence.load_state("cloudtrail")
+ assert loaded["trails"].get_scoped(
+ "000000000000", "us-west-2", "regional-trail"
+ )["TrailARN"].endswith("trail/regional-trail")
+ assert loaded["event_selectors"].get_scoped(
+ "000000000000", "us-west-2", "regional-trail"
+ )[0]["ReadWriteType"] == "All"
+
+ persistence.save_state("cloudtrail", loaded)
+ second_snapshot = _json.loads((tmp_path / "cloudtrail.json").read_text())
+ assert second_snapshot == first_snapshot
+
+
+def test_cloudtrail_legacy_state_restores_trails_by_home_region():
+ from ministack.core.responses import (
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import cloudtrail
+
+ original_account = get_account_id()
+ original_region = get_region()
+ account_id = "111111111111"
+ boot_region = "us-east-1"
+ west_region = "us-west-2"
+ west_name = "legacy-west-trail"
+ east_name = "legacy-east-trail"
+ orphan_name = "legacy-orphan-trail"
+ west_arn = f"arn:aws:cloudtrail:{west_region}:{account_id}:trail/{west_name}"
+
+ try:
+ set_request_account_id(account_id)
+ set_request_region(boot_region)
+ cloudtrail.reset()
+ cloudtrail.restore_state(
+ {
+ "trails": {
+ west_name: {
+ "Name": west_name,
+ "HomeRegion": west_region,
+ "TrailARN": west_arn,
+ },
+ east_name: {
+ "Name": east_name,
+ "HomeRegion": boot_region,
+ "TrailARN": (
+ f"arn:aws:cloudtrail:{boot_region}:{account_id}:"
+ f"trail/{east_name}"
+ ),
+ },
+ },
+ "event_selectors": {
+ west_name: [{"ReadWriteType": "All"}],
+ orphan_name: [{"ReadWriteType": "WriteOnly"}],
+ },
+ "trail_tags": {west_arn: {"env": "legacy"}},
+ }
+ )
+
+ assert cloudtrail._trails.get_scoped(account_id, west_region, west_name)[
+ "HomeRegion"
+ ] == west_region
+ assert cloudtrail._event_selectors.get_scoped(
+ account_id, west_region, west_name
+ ) == [{"ReadWriteType": "All"}]
+ assert cloudtrail._trails.get_scoped(account_id, boot_region, west_name) is None
+ assert cloudtrail._event_selectors.get_scoped(
+ account_id, boot_region, orphan_name
+ ) == [{"ReadWriteType": "WriteOnly"}]
+ assert cloudtrail._trail_tags.get_scoped(
+ account_id, boot_region, west_arn
+ ) == {"env": "legacy"}
+ finally:
+ cloudtrail.reset()
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+
+
+def test_cloudtrail_persistence_lifecycle_restores_all_regional_accounts(
+ monkeypatch, tmp_path
+):
+ import importlib
+
+ from ministack.app import _build_persistence_save_dict, _state_map
+ from ministack.core.responses import set_request_account_id, set_request_region
+ from ministack.services import cloudtrail
+
+ boot_region = "us-east-1"
+ west_region = "us-west-2"
+ first_account = "111111111111"
+ second_account = "222222222222"
+
+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)
+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
+ set_request_account_id(first_account)
+ set_request_region(boot_region)
+ cloudtrail.reset()
+ try:
+ cloudtrail._trails.set_scoped(
+ first_account,
+ west_region,
+ "acct-one-west",
+ {
+ "Name": "acct-one-west",
+ "HomeRegion": west_region,
+ "TrailARN": (
+ f"arn:aws:cloudtrail:{west_region}:{first_account}:"
+ "trail/acct-one-west"
+ ),
+ },
+ )
+ cloudtrail._trails.set_scoped(
+ second_account,
+ boot_region,
+ "acct-two-east",
+ {
+ "Name": "acct-two-east",
+ "HomeRegion": boot_region,
+ "TrailARN": (
+ f"arn:aws:cloudtrail:{boot_region}:{second_account}:"
+ "trail/acct-two-east"
+ ),
+ },
+ )
+
+ assert _state_map["cloudtrail"] == "cloudtrail"
+ save_dict = _build_persistence_save_dict()
+ persistence.save_all({"cloudtrail": save_dict["cloudtrail"]})
+
+ cloudtrail.reset()
+ importlib.reload(cloudtrail)
+
+ assert cloudtrail._trails.get_scoped(
+ first_account, west_region, "acct-one-west"
+ )["HomeRegion"] == west_region
+ assert cloudtrail._trails.get_scoped(
+ second_account, boot_region, "acct-two-east"
+ )["HomeRegion"] == boot_region
+ assert cloudtrail._trails.get_scoped(
+ first_account, boot_region, "acct-one-west"
+ ) is None
+ finally:
+ cloudtrail.reset()
+
+
def test_ecs_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path):
"""A rollback binary must reject ECS's regional schema instead of
accepting it as v2 and silently dropping every regional store."""