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): store AdvancedEventSelectors and set HasCustomEventSelectors in PutEventSelectors (#1978)
iot-rocket6029ca75937f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fa85cb97..7f9cdab6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **CloudTrail — `PutEventSelectors` stores `AdvancedEventSelectors` and sets `HasCustomEventSelectors`** — advanced selectors are now stored and returned in place of `EventSelectors` instead of being dropped, a request with both kinds, neither, or an empty or oversized list fails with `InvalidEventSelectorsException`, basic selectors read back with their omitted members filled in, and `GetTrail` and `DescribeTrails` report `HasCustomEventSelectors: true` while a trail has selectors other than the default one. Contributed by @iot-rocket.+- **CloudTrail — `GetEventSelectors` returns the default selector of a new trail** — a trail that never had `PutEventSelectors` answered an empty `EventSelectors` list instead of the default selector that logs all read and write management events. Contributed by @iot-rocket.- **CloudTrail — `GetEventSelectors` returns the default selector of a new trail** — a trail that never had `PutEventSelectors` answered an empty `EventSelectors` list instead of the default selector that logs all read and write management events. Contributed by @iot-rocket.- **STS — `GetAccessKeyInfo` answers the account that owns the key** — it returned the caller's account whatever `AccessKeyId` said; it now returns the owning account for keys the emulator knows (its root key, IAM access keys and STS sessions), the account encoded in any other `AKIA` or `ASIA` key id as AWS does, and a `ValidationError` for an id that encodes no account or breaks the parameter's length and pattern constraints. Contributed by @iot-rocket.- **STS — `GetAccessKeyInfo` is authorized like other actions** — under `AUTH=true` it was allowed like `GetCallerIdentity` and `GetSessionToken`, whatever the caller's policies said. It now needs an identity policy that allows it and no deny, and otherwise answers `AccessDenied`, as AWS does; the other two stay allowed. Contributed by @iot-rocket.diff --git a/ministack/services/cloudtrail.py b/ministack/services/cloudtrail.pyindex 825a3de6..ea072369 100644--- a/ministack/services/cloudtrail.py+++ b/ministack/services/cloudtrail.py@@ -662,6 +662,11 @@ def _update_trail(body: dict):return _ok(resp)+def _event_selectors_field(selectors: list) -> str:+ """Response field for stored selectors; advanced selectors carry FieldSelectors."""+ return "AdvancedEventSelectors" if selectors and "FieldSelectors" in selectors[0] else "EventSelectors"++def _put_event_selectors(body: dict):raw = body.get("TrailName", "").strip()if not raw:@@ -669,9 +674,26 @@ def _put_event_selectors(body: dict):name, home_region, trail, error = _find_mutable_trail(raw)if error:return error- selectors = body.get("EventSelectors", [])+ basic, advanced = body.get("EventSelectors"), body.get("AdvancedEventSelectors")+ if basic is not None and advanced is not None:+ return _err(+ "InvalidEventSelectorsException",+ "You can select events by using either EventSelectors or AdvancedEventSelectors, but not both.",+ )+ if basic is None and advanced is None:+ return _err(+ "InvalidEventSelectorsException",+ "You must select events by using either EventSelectors or AdvancedEventSelectors, "+ "but you cannot use both.",+ )+ if advanced == []:+ return _err("InvalidEventSelectorsException", "Specify between 1 and 500 selectors for your trail.")+ if basic is not None and not 1 <= len(basic) <= 5:+ return _err("InvalidEventSelectorsException", "Specify a valid number of selectors (1 to 5) for your trail")+ selectors = advanced or [{**_DEFAULT_EVENT_SELECTORS[0], **selector} for selector in basic]_event_selectors.set_scoped(get_account_id(), home_region, name, selectors)- return _ok({"TrailARN": trail["TrailARN"], "EventSelectors": selectors})+ trail["HasCustomEventSelectors"] = selectors != _DEFAULT_EVENT_SELECTORS+ return _ok({"TrailARN": trail["TrailARN"], _event_selectors_field(selectors): selectors})def _get_event_selectors(body: dict):@@ -688,8 +710,7 @@ def _get_event_selectors(body: dict):return _ok({"TrailARN": trail.get("TrailARN", _trail_arn(name)),- "EventSelectors": selectors,- "AdvancedEventSelectors": [],+ _event_selectors_field(selectors): selectors,})diff --git a/tests/test_cloudtrail.py b/tests/test_cloudtrail.pyindex 93ac5a41..c8bdc4c9 100644--- a/tests/test_cloudtrail.py+++ b/tests/test_cloudtrail.py@@ -26,6 +26,15 @@ WEST_REGION = "us-west-2"DEFAULT_EVENT_SELECTORS = [{"ReadWriteType": "All", "IncludeManagementEvents": True, "DataResources": [], "ExcludeManagementEventSources": []}]+MANAGEMENT_ADVANCED_SELECTORS = [+ {+ "Name": "writes",+ "FieldSelectors": [+ {"Field": "eventCategory", "Equals": ["Management"]},+ {"Field": "readOnly", "Equals": ["false"]},+ ],+ }+]def _client(service, region=REGION):@@ -182,7 +191,7 @@ def test_multi_region_trail_is_shadow_visible_from_peer_region(ct):S3BucketName="bucket",IsMultiRegionTrail=True,)["TrailARN"]- selectors = [{"ReadWriteType": "All", "IncludeManagementEvents": True, "DataResources": []}]+ selectors = [{**DEFAULT_EVENT_SELECTORS[0], "ReadWriteType": "WriteOnly"}]ct.put_event_selectors(TrailName=name, EventSelectors=selectors)west_ct = _client("cloudtrail", region=WEST_REGION)@@ -484,16 +493,17 @@ def test_stop_logging_not_found(ct):def test_put_get_event_selectors(ct):+ """Omitted members of a basic selector read back with their defaults."""name = f"trail-sel-{_uid()}"ct.create_trail(Name=name, S3BucketName="bucket")- selectors = [{"ReadWriteType": "All", "IncludeManagementEvents": True, "DataResources": []}]- put_resp = ct.put_event_selectors(TrailName=name, EventSelectors=selectors)+ selectors = [{**DEFAULT_EVENT_SELECTORS[0], "ReadWriteType": "WriteOnly"}]+ put_resp = ct.put_event_selectors(TrailName=name, EventSelectors=[{"ReadWriteType": "WriteOnly"}])assert "TrailARN" in put_respassert put_resp["EventSelectors"] == selectorsget_resp = ct.get_event_selectors(TrailName=name)assert get_resp["EventSelectors"] == selectors- assert get_resp["AdvancedEventSelectors"] == []+ assert "AdvancedEventSelectors" not in get_respdef test_put_event_selectors_rejects_foreign_region_trail_arn(ct):@@ -512,7 +522,7 @@ def test_put_event_selectors_rejects_foreign_region_trail_arn(ct):def test_get_event_selectors_by_arn_from_different_request_region(ct):name = f"trail-sel-cross-region-{_uid()}"arn = ct.create_trail(Name=name, S3BucketName="bucket")["TrailARN"]- selectors = [{"ReadWriteType": "All", "IncludeManagementEvents": True, "DataResources": []}]+ selectors = [{**DEFAULT_EVENT_SELECTORS[0], "ReadWriteType": "WriteOnly"}]ct.put_event_selectors(TrailName=name, EventSelectors=selectors)west_ct = _client("cloudtrail", region="us-west-2")@@ -521,6 +531,69 @@ def test_get_event_selectors_by_arn_from_different_request_region(ct):assert resp["EventSelectors"] == selectors+def test_put_get_advanced_event_selectors(ct):+ """Advanced selectors are stored and returned without EventSelectors, and basic ones replace them."""+ name = f"trail-adv-{_uid()}"+ ct.create_trail(Name=name, S3BucketName="bucket")+ put_resp = ct.put_event_selectors(TrailName=name, AdvancedEventSelectors=MANAGEMENT_ADVANCED_SELECTORS)+ assert put_resp["AdvancedEventSelectors"] == MANAGEMENT_ADVANCED_SELECTORS+ assert "EventSelectors" not in put_resp+ get_resp = ct.get_event_selectors(TrailName=name)+ assert get_resp["AdvancedEventSelectors"] == MANAGEMENT_ADVANCED_SELECTORS+ assert "EventSelectors" not in get_resp++ ct.put_event_selectors(TrailName=name, EventSelectors=DEFAULT_EVENT_SELECTORS)+ get_resp = ct.get_event_selectors(TrailName=name)+ assert get_resp["EventSelectors"] == DEFAULT_EVENT_SELECTORS+ assert "AdvancedEventSelectors" not in get_resp+++def test_put_event_selectors_sets_has_custom_event_selectors(ct):+ """HasCustomEventSelectors is true for any selectors other than the default one."""+ name = f"trail-sel-custom-{_uid()}"+ ct.create_trail(Name=name, S3BucketName="bucket")+ all_management = [{"FieldSelectors": [{"Field": "eventCategory", "Equals": ["Management"]}]}]+ for kwargs, custom in (+ ({"EventSelectors": [{"ReadWriteType": "WriteOnly"}]}, True),+ ({"EventSelectors": [{}]}, False),+ ({"AdvancedEventSelectors": all_management}, True),+ ):+ ct.put_event_selectors(TrailName=name, **kwargs)+ assert ct.get_trail(Name=name)["Trail"]["HasCustomEventSelectors"] is custom+ assert ct.describe_trails(trailNameList=[name])["trailList"][0]["HasCustomEventSelectors"] is custom+++ ("kwargs", "message"),+ [+ (+ {"EventSelectors": DEFAULT_EVENT_SELECTORS, "AdvancedEventSelectors": MANAGEMENT_ADVANCED_SELECTORS},+ "You can select events by using either EventSelectors or AdvancedEventSelectors, but not both.",+ ),+ (+ {},+ "You must select events by using either EventSelectors or AdvancedEventSelectors, but you cannot use both.",+ ),+ ({"EventSelectors": []}, "Specify a valid number of selectors (1 to 5) for your trail"),+ (+ {"EventSelectors": DEFAULT_EVENT_SELECTORS * 6},+ "Specify a valid number of selectors (1 to 5) for your trail",+ ),+ ({"AdvancedEventSelectors": []}, "Specify between 1 and 500 selectors for your trail."),+ ],+ ids=["both", "neither", "no-basic", "six-basic", "no-advanced"],+)+def test_put_event_selectors_rejects_invalid_selector_lists(ct, kwargs, message):+ """PutEventSelectors takes one to five basic selectors or at least one advanced selector."""+ name = f"trail-sel-invalid-{_uid()}"+ ct.create_trail(Name=name, S3BucketName="bucket")+ with pytest.raises(ClientError) as exc:+ ct.put_event_selectors(TrailName=name, **kwargs)+ assert exc.value.response["Error"]["Code"] == "InvalidEventSelectorsException"+ assert exc.value.response["Error"]["Message"] == message+ assert ct.get_event_selectors(TrailName=name)["EventSelectors"] == DEFAULT_EVENT_SELECTORS++@pytest.mark.parametrize("region", [REGION, WEST_REGION])def test_get_event_selectors_defaults_to_all_management_events(ct, region):"""A trail without PutEventSelectors reports the default selector, also from a peer region."""