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): persist KmsKeyId on CreateTrail (#1027)
Rajesh BAVANANTHAMca9335fc9974
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 27ada3c5..78fbb349 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,13 @@ All notable changes to MiniStack will be documented here.Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).Versioning follows [Semantic Versioning](https://semver.org/).+## [Unreleased]++### Fixed+- **CloudTrail — `CreateTrail` persists `KmsKeyId`** — `CreateTrail` accepted `KmsKeyId` but dropped it (only `UpdateTrail` stored it), so `DescribeTrails`/`GetTrail` read it back empty and Terraform's `aws_cloudtrail` did not converge in a single apply: the first `plan` after `apply` showed a `kms_key_id` diff that only cleared on a second apply (via `UpdateTrail`). `CreateTrail` now stores and returns `KmsKeyId`, normalized to a full key ARN as real AWS echoes it (a bare key id is expanded; an ARN or `alias/...` is kept), and omits the field when no CMK is set so an unset trail shows no diff. `UpdateTrail` normalizes it the same way and likewise omits it from its response when unset. Contributed by @b-rajesh.++---+## [1.3.70] — 2026-06-30### Addeddiff --git a/README.md b/README.mdindex b7aabe1c..d250f9e8 100644--- a/README.md+++ b/README.md@@ -384,7 +384,7 @@ subnet = ec2.create_subnet(| **KMS** | CreateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags | 27 actions; RSA (2048/4096), ECC (SECG_P256K1, NIST P-256/384/521), Edwards25519 (`ECC_NIST_EDWARDS25519` — pure Ed25519 via `ED25519_SHA_512` with `MessageType=RAW`; `ED25519_PH_SHA_512` advertised in `SigningAlgorithms` but returns `UnsupportedOperationException` until Ed25519ph lands), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; envelope encryption; alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image || **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin config round-trip; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; **CloudFront Functions** are API stubs (in-memory code + DEVELOPMENT/LIVE ETags for Terraform `aws_cloudfront_function`) with `KeyValueStoreAssociations` round-tripped — no `TestFunction`, no viewer-request JS execution at the edge; `UpdateFunction` clears the emulated LIVE stage until `PublishFunction` runs again || **CloudFront KeyValueStore (data plane)** | DescribeKeyValueStore, ListKeys, GetKey, PutKey, DeleteKey, UpdateKeys | Separate `cloudfront-keyvaluestore` SDK service (REST/JSON, signing name `cloudfront-keyvaluestore`); ETag-based optimistic concurrency on every mutating op; `UpdateKeys` is atomic (validates whole batch, rejects on first invalid entry); `ListKeys` paginates with opaque `NextToken` capped at 50 results per AWS spec; bridges to the management plane via the shared KVS ARN |-| **CloudTrail** | LookupEvents, CreateTrail, DeleteTrail, GetTrail, DescribeTrails, ListTrails, UpdateTrail, GetTrailStatus, StartLogging, StopLogging, PutEventSelectors, GetEventSelectors, AddTags, ListTags, RemoveTags | In-memory audit log; recording opt-in via `CLOUDTRAIL_RECORDING=1` (or runtime config endpoint); per-account ring buffer (`CLOUDTRAIL_MAX_EVENTS=10000`); `LookupEvents` supports all 8 AWS `LookupAttributes`; `IsLogging` flips on Start/StopLogging |+| **CloudTrail** | LookupEvents, CreateTrail, DeleteTrail, GetTrail, DescribeTrails, ListTrails, UpdateTrail, GetTrailStatus, StartLogging, StopLogging, PutEventSelectors, GetEventSelectors, AddTags, ListTags, RemoveTags | In-memory audit log; recording opt-in via `CLOUDTRAIL_RECORDING=1` (or runtime config endpoint); per-account ring buffer (`CLOUDTRAIL_MAX_EVENTS=10000`); `LookupEvents` supports all 8 AWS `LookupAttributes`; `IsLogging` flips on Start/StopLogging; `CreateTrail`/`UpdateTrail` persist `KmsKeyId` (normalized to a key ARN; omitted when unset) so `aws_cloudtrail` converges without drift || **Resource Groups** | CreateGroup, GetGroup, DeleteGroup, UpdateGroup, ListGroups, GetGroupQuery, UpdateGroupQuery, GetGroupConfiguration, PutGroupConfiguration, GroupResources, UngroupResources, ListGroupResources, ListGroupingStatuses, SearchResources, Tag, Untag, GetTags, GetAccountSettings, UpdateAccountSettings | 19 of 23 spec ops; tag-sync ops omitted (not exposed by AWS CLI / Terraform); `Group` accepts bare name or full ARN || **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 |diff --git a/ministack/services/cloudtrail.py b/ministack/services/cloudtrail.pyindex d34b4b93..b6dda68b 100644--- a/ministack/services/cloudtrail.py+++ b/ministack/services/cloudtrail.py@@ -92,6 +92,15 @@ def _trail_arn(name: str) -> str:return f"arn:aws:cloudtrail:{get_region()}:{get_account_id()}:trail/{name}"+def _normalize_kms_key_id(value: str) -> str:+ """Echo the CMK as real AWS does — a full key ARN. A bare key id is expanded to+ its ARN; an ARN or an ``alias/...`` reference is kept as sent (resolving an alias+ to its target key ARN would need a KMS lookup we don't do). Returns "" when unset."""+ if not value or value.startswith("arn:") or value.startswith("alias/"):+ return value+ return f"arn:aws:kms:{get_region()}:{get_account_id()}:key/{value}"++def _get_event_queue() -> collections.deque:q = _events.get("events")if q is None:@@ -255,19 +264,27 @@ def _create_trail(body: dict):"IsOrganizationTrail": body.get("IsOrganizationTrail", False),"IsLogging": True,}+ # CreateTrail must persist KmsKeyId so DescribeTrails/GetTrail echo it; otherwise a+ # CMK set at create is dropped and Terraform's aws_cloudtrail needs a second apply to+ # converge (only UpdateTrail stored it). Stored normalized to a key ARN, and only when+ # set — AWS omits the field when there is no CMK, and emitting "" yields a spurious diff.+ kms = _normalize_kms_key_id(body.get("KmsKeyId", ""))+ if kms:+ trail["KmsKeyId"] = kms_trails[name] = trail- return _ok(- {- "Name": name,- "S3BucketName": trail["S3BucketName"],- "S3KeyPrefix": trail["S3KeyPrefix"],- "IncludeGlobalServiceEvents": trail["IncludeGlobalServiceEvents"],- "IsMultiRegionTrail": trail["IsMultiRegionTrail"],- "TrailARN": arn,- "LogFileValidationEnabled": trail["LogFileValidationEnabled"],- "IsOrganizationTrail": trail["IsOrganizationTrail"],- }- )+ resp = {+ "Name": name,+ "S3BucketName": trail["S3BucketName"],+ "S3KeyPrefix": trail["S3KeyPrefix"],+ "IncludeGlobalServiceEvents": trail["IncludeGlobalServiceEvents"],+ "IsMultiRegionTrail": trail["IsMultiRegionTrail"],+ "TrailARN": arn,+ "LogFileValidationEnabled": trail["LogFileValidationEnabled"],+ "IsOrganizationTrail": trail["IsOrganizationTrail"],+ }+ if kms:+ resp["KmsKeyId"] = kms+ return _ok(resp)def _delete_trail(body: dict):@@ -382,28 +399,38 @@ def _update_trail(body: dict):("EnableLogFileValidation", "LogFileValidationEnabled"),("CloudWatchLogsLogGroupArn", "CloudWatchLogsLogGroupArn"),("CloudWatchLogsRoleArn", "CloudWatchLogsRoleArn"),- ("KmsKeyId", "KmsKeyId"),("IsOrganizationTrail", "IsOrganizationTrail"),):if src in body:trail[dst] = body[src]- return _ok(- {- "Name": name,- "S3BucketName": trail.get("S3BucketName", ""),- "S3KeyPrefix": trail.get("S3KeyPrefix", ""),- "SnsTopicName": trail.get("SnsTopicName", ""),- "SnsTopicARN": trail.get("SnsTopicARN", ""),- "IncludeGlobalServiceEvents": trail.get("IncludeGlobalServiceEvents", True),- "IsMultiRegionTrail": trail.get("IsMultiRegionTrail", False),- "TrailARN": trail["TrailARN"],- "LogFileValidationEnabled": trail.get("LogFileValidationEnabled", False),- "CloudWatchLogsLogGroupArn": trail.get("CloudWatchLogsLogGroupArn", ""),- "CloudWatchLogsRoleArn": trail.get("CloudWatchLogsRoleArn", ""),- "KmsKeyId": trail.get("KmsKeyId", ""),- "IsOrganizationTrail": trail.get("IsOrganizationTrail", False),- }- )+ # KmsKeyId normalized like CreateTrail; cleared (not stored as "") when unset so the+ # read-back stays AWS-shaped and Terraform sees no spurious diff.+ if "KmsKeyId" in body:+ kms = _normalize_kms_key_id(body["KmsKeyId"])+ if kms:+ trail["KmsKeyId"] = kms+ else:+ trail.pop("KmsKeyId", None)+ resp = {+ "Name": name,+ "S3BucketName": trail.get("S3BucketName", ""),+ "S3KeyPrefix": trail.get("S3KeyPrefix", ""),+ "SnsTopicName": trail.get("SnsTopicName", ""),+ "SnsTopicARN": trail.get("SnsTopicARN", ""),+ "IncludeGlobalServiceEvents": trail.get("IncludeGlobalServiceEvents", True),+ "IsMultiRegionTrail": trail.get("IsMultiRegionTrail", False),+ "TrailARN": trail["TrailARN"],+ "LogFileValidationEnabled": trail.get("LogFileValidationEnabled", False),+ "CloudWatchLogsLogGroupArn": trail.get("CloudWatchLogsLogGroupArn", ""),+ "CloudWatchLogsRoleArn": trail.get("CloudWatchLogsRoleArn", ""),+ "IsOrganizationTrail": trail.get("IsOrganizationTrail", False),+ }+ # Omit KmsKeyId when unset, matching CreateTrail and the DescribeTrails/GetTrail+ # read-back: AWS omits the field when there is no CMK, and an empty "" is not a+ # valid ARN (the Terraform aws provider fails parsing it).+ if trail.get("KmsKeyId"):+ resp["KmsKeyId"] = trail["KmsKeyId"]+ return _ok(resp)def _put_event_selectors(body: dict):diff --git a/tests/test_cloudtrail.py b/tests/test_cloudtrail.pyindex 621d74d6..55e147b2 100644--- a/tests/test_cloudtrail.py+++ b/tests/test_cloudtrail.py@@ -201,6 +201,84 @@ def test_update_trail_persists_fields(ct):assert desc["IsMultiRegionTrail"] is True+def test_create_trail_persists_kms_key_id(ct):+ """CreateTrail persists KmsKeyId so DescribeTrails/GetTrail echo it. Without this a+ CMK-encrypted trail reads back with no KmsKeyId, so Terraform's aws_cloudtrail does+ not converge in one apply (the value only lands via a later UpdateTrail)."""+ name = f"trail-kms-{_uid()}"+ kms_arn = f"arn:aws:kms:{REGION}:000000000000:key/{_uid()}"+ resp = ct.create_trail(Name=name, S3BucketName="bucket", KmsKeyId=kms_arn)+ assert resp["KmsKeyId"] == kms_arn++ desc = ct.describe_trails(trailNameList=[name])["trailList"][0]+ assert desc["KmsKeyId"] == kms_arn++ got = ct.get_trail(Name=name)["Trail"]+ assert got["KmsKeyId"] == kms_arn+++def test_create_trail_normalizes_bare_kms_key_id(ct):+ """A bare KMS key id is returned as a full key ARN, matching real AWS, which+ always echoes the CMK as an ARN — so a trail created with a key id shows no diff."""+ name = f"trail-kmsid-{_uid()}"+ key_id = f"{_uid()}-{_uid()}"+ resp = ct.create_trail(Name=name, S3BucketName="bucket", KmsKeyId=key_id)+ assert resp["KmsKeyId"] == f"arn:aws:kms:{REGION}:000000000000:key/{key_id}"+ desc = ct.describe_trails(trailNameList=[name])["trailList"][0]+ assert desc["KmsKeyId"] == resp["KmsKeyId"]+++def test_create_trail_without_cmk_omits_kms_key_id(ct):+ """A trail created without a CMK omits KmsKeyId entirely rather than returning "".+ Real AWS omits unset optional fields; emitting an empty string for an ARN-typed+ field makes the Terraform aws provider fail (`parsing ... ARN (): arn: invalid+ prefix`), so guard that neither the create response nor the read-back carries one."""+ name = f"trail-nocmk-{_uid()}"+ resp = ct.create_trail(Name=name, S3BucketName="bucket")+ assert "KmsKeyId" not in resp+ assert "SnsTopicARN" not in resp++ desc = ct.describe_trails(trailNameList=[name])["trailList"][0]+ assert "KmsKeyId" not in desc+ assert "SnsTopicARN" not in desc+++def test_create_trail_keeps_kms_alias(ct):+ """An ``alias/...`` reference is echoed verbatim — real AWS resolves it to the+ target key ARN, but the emulator keeps the caller's value rather than fabricate a+ wrong ARN (resolving the alias would need a KMS lookup it does not do)."""+ name = f"trail-alias-{_uid()}"+ alias = f"alias/ct-{_uid()}"+ resp = ct.create_trail(Name=name, S3BucketName="bucket", KmsKeyId=alias)+ assert resp["KmsKeyId"] == alias+ assert ct.describe_trails(trailNameList=[name])["trailList"][0]["KmsKeyId"] == alias+++def test_update_trail_normalizes_kms_key_id(ct):+ """UpdateTrail normalizes KmsKeyId the same way CreateTrail does: a bare key id+ becomes a full key ARN; an already-full ARN is left as-is."""+ name = f"trail-upkms-{_uid()}"+ ct.create_trail(Name=name, S3BucketName="bucket")+ key_id = f"{_uid()}-{_uid()}"+ out = ct.update_trail(Name=name, KmsKeyId=key_id)+ assert out["KmsKeyId"] == f"arn:aws:kms:{REGION}:000000000000:key/{key_id}"+ assert ct.describe_trails(trailNameList=[name])["trailList"][0]["KmsKeyId"] == out["KmsKeyId"]+ full = f"arn:aws:kms:{REGION}:000000000000:key/{_uid()}"+ assert ct.update_trail(Name=name, KmsKeyId=full)["KmsKeyId"] == full+++def test_update_trail_without_cmk_omits_kms_key_id(ct):+ """UpdateTrail on a trail with no CMK omits KmsKeyId rather than returning "".+ AWS omits unset optional fields; an empty ARN makes the Terraform aws provider fail+ (`parsing ... ARN (): arn: invalid prefix`), so neither the UpdateTrail response nor+ the read-back may carry one — matching CreateTrail and DescribeTrails/GetTrail."""+ name = f"trail-upnocmk-{_uid()}"+ ct.create_trail(Name=name, S3BucketName="bucket")+ out = ct.update_trail(Name=name, S3KeyPrefix="logs/")+ assert "KmsKeyId" not in out+ assert "KmsKeyId" not in ct.describe_trails(trailNameList=[name])["trailList"][0]++def test_start_logging_not_found(ct):with pytest.raises(ClientError) as exc:ct.start_logging(Name=f"nonexistent-{_uid()}")