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
feat(cloudwatch-logs): add resource policy (PutResourcePolicy/DescribeResourcePolicies/DeleteResourcePolicy) (#1871)
Fábio André Ramos Rodrigues59d5d26f0855
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0ae40463..fcea0887 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **CloudFormation — a nested stack's update deletes the resources its template drops** — a resource removed from the child template, or created by a failed child update that was rolled back, stayed in its service and in the nested stack's resource list. Contributed by @iot-rocket.### Added+- **CloudWatch Logs — resource policy** — `PutResourcePolicy`, `DescribeResourcePolicies` and `DeleteResourcePolicy`, the account/log-group-level policy Crossplane's `provider-aws-cloudwatchlogs` manages for cross-service log delivery — distinct from the per-destination `PutDestinationPolicy` and the delivery-scoped `PutDeliveryDestinationPolicy`. `PutResourcePolicy` supports `expectedRevisionId` for optimistic concurrency (`OperationAbortedException` on mismatch). Contributed by @fabio-andre-rodrigues.- **Bedrock AgentCore — resource-based policies** — `PutResourcePolicy`, `GetResourcePolicy` and `DeleteResourcePolicy` persist policies for runtimes and endpoints. With `AUTH=true`, runtime invocation evaluates caller principals, explicit denies and the runtime-plus-endpoint policy requirement for cross-account calls. This emulates the documented AgentCore policy contract locally; it does not validate behavior against AWS.- **KMS — grants** — `CreateGrant`, `RevokeGrant` and `RetireGrant`, and `ListGrants` returns the grants they create instead of always an empty list. `CreateGrant` returns a `GrantId` and a `GrantToken`, follows the key state (`DisabledException` for a disabled key, `KMSInvalidStateException` pending deletion, replica deletion or import), rejects operations the key cannot perform (`Sign` / `Verify` / `GenerateMac` / `VerifyMac` on a symmetric encryption key, data key operations on an asymmetric key, anything but `GenerateMac` / `VerifyMac` / `DescribeKey` / `CreateGrant` / `RetireGrant` on an HMAC key) with `ValidationException`, and with a `Name` a retry with identical parameters returns the original `GrantId` with a new token. `ListGrants` filters by `GrantId` and `GranteePrincipal` and pages with `Limit` (1 to 100, default 50) and `Marker`. `RetireGrant` takes a `GrantToken`, or a `KeyId` and `GrantId`. All three honour `DryRun`, and grants persist with the key. Grants are recorded but not evaluated when authorizing other calls, as with key policies. Contributed by @DaviReisVieira.- **RDS — IAM database authentication for MySQL and Aurora MySQL** — users created `IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS'` log in with an SDK-generated token over `mysql_clear_password`, as on AWS. The instance or cluster must have `IAMDatabaseAuthenticationEnabled`; with `AUTH=true` the token and the `rds-db:connect` policy are verified too. `ModifyDBInstance` accepts `EnableIAMDatabaseAuthentication`. Contributed by @Areson.diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.pyindex e7030a91..7ece44ef 100644--- a/ministack/services/cloudwatch_logs.py+++ b/ministack/services/cloudwatch_logs.py@@ -13,6 +13,7 @@ Supports: CreateLogGroup, DeleteLogGroup, DescribeLogGroups,TagResource, UntagResource, ListTagsForResource,PutDestination, DeleteDestination, DescribeDestinations,PutDestinationPolicy,+ PutResourcePolicy, DescribeResourcePolicies, DeleteResourcePolicy,PutMetricFilter, DeleteMetricFilter, DescribeMetricFilters,StartQuery, GetQueryResults, StopQuery,PutDeliverySource, GetDeliverySource, DeleteDeliverySource, DescribeDeliverySources,@@ -66,6 +67,10 @@ _log_groups = AccountRegionScopedDict()_destinations = AccountRegionScopedDict()# dest_name -> {destinationName, targetArn, roleArn, accessPolicy, arn, creationTime}+_resource_policies = AccountRegionScopedDict()+# policy_name -> {policyName, policyDocument, resourceArn, policyScope,+# lastUpdatedTime, revisionId}+_metric_filters = AccountRegionScopedDict()# (log_group_name, filter_name) -> {filterName, logGroupName, filterPattern, metricTransformations, creationTime}@@ -109,6 +114,7 @@ def get_state():return {"log_groups": copy.deepcopy(_log_groups),"destinations": copy.deepcopy(_destinations),+ "resource_policies": copy.deepcopy(_resource_policies),"metric_filters": copy.deepcopy(_metric_filters),"queries": copy.deepcopy(_queries),"log_records": copy.deepcopy(_log_records),@@ -199,6 +205,7 @@ def _restore_state(data):if data:_log_groups.update(data.get("log_groups", {}))_destinations.update(data.get("destinations", {}))+ _resource_policies.update(data.get("resource_policies", {}))_restore_metric_filters(data.get("metric_filters", {}))_restore_queries(data.get("queries", {}))_log_records.update(data.get("log_records", {}))@@ -308,6 +315,9 @@ async def handle_request(method, path, headers, body, query_params):"DeleteDestination": _delete_destination,"DescribeDestinations": _describe_destinations,"PutDestinationPolicy": _put_destination_policy,+ "PutResourcePolicy": _put_resource_policy,+ "DescribeResourcePolicies": _describe_resource_policies,+ "DeleteResourcePolicy": _delete_resource_policy,"PutMetricFilter": _put_metric_filter,"DeleteMetricFilter": _delete_metric_filter,"DescribeMetricFilters": _describe_metric_filters,@@ -1573,6 +1583,65 @@ def _put_destination_policy(data):return json_response({})+def _format_resource_policy(policy):+ return {+ "policyName": policy["policyName"],+ "policyDocument": policy["policyDocument"],+ "lastUpdatedTime": policy["lastUpdatedTime"],+ "policyScope": policy.get("policyScope", "ACCOUNT"),+ "resourceArn": policy.get("resourceArn"),+ "revisionId": policy["revisionId"],+ }+++def _put_resource_policy(data):+ name = data.get("policyName")+ document = data.get("policyDocument")+ if not name or not document:+ return error_response_json(+ "InvalidParameterException",+ "policyName and policyDocument are required.", 400,+ )+ expected_revision = data.get("expectedRevisionId")+ existing = _resource_policies.get(name)+ if expected_revision is not None and (not existing or existing["revisionId"] != expected_revision):+ return error_response_json(+ "OperationAbortedException",+ "The revision id does not match the latest revision id.", 400,+ )+ policy = {+ "policyName": name,+ "policyDocument": document,+ "resourceArn": data.get("resourceArn"),+ "policyScope": data.get("policyScope", "ACCOUNT"),+ "lastUpdatedTime": int(time.time() * 1000),+ "revisionId": new_uuid(),+ }+ _resource_policies[name] = policy+ formatted = _format_resource_policy(policy)+ return json_response({"resourcePolicy": formatted, "revisionId": policy["revisionId"]})+++def _describe_resource_policies(data):+ resource_arn = data.get("resourceArn")+ policies = [+ _format_resource_policy(p) for p in _resource_policies.values()+ if not resource_arn or p.get("resourceArn") == resource_arn+ ]+ return json_response({"resourcePolicies": policies})+++def _delete_resource_policy(data):+ name = data.get("policyName")+ if not name or name not in _resource_policies:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified resource policy does not exist: {name}", 400,+ )+ del _resource_policies[name]+ return json_response({})++# ---------------------------------------------------------------------------# Metric Filters# ---------------------------------------------------------------------------@@ -2023,6 +2092,7 @@ def _stop_query(data):def reset():_log_groups.clear()_destinations.clear()+ _resource_policies.clear()_metric_filters.clear()_queries.clear()_log_records.clear()diff --git a/tests/test_cloudwatch_logs.py b/tests/test_cloudwatch_logs.pyindex dcc97d6f..0a170466 100644--- a/tests/test_cloudwatch_logs.py+++ b/tests/test_cloudwatch_logs.py@@ -970,6 +970,78 @@ def test_logs_put_destination_policy(logs):logs.delete_destination(destinationName=dest_name)+# ---------------------------------------------------------------------------+# Account-level resource policies (PutResourcePolicy / DescribeResourcePolicies+# / DeleteResourcePolicy) - distinct from PutDestinationPolicy above (which+# sets accessPolicy on one classic Destination) and from+# PutDeliveryDestinationPolicy (which authorizes the vended-logs delivery+# service for one DeliveryDestination). This family grants log-group-level+# actions such as PutSubscriptionFilter, CreateExportTask or the+# CloudWatch Logs Resource Policy Crossplane manages for cross-service log+# delivery, to any principal named in the policy document.+# ---------------------------------------------------------------------------++def test_logs_resource_policy_crud(logs):+ """Put/Describe/Delete round-trip for an account-level resource policy."""+ uid = _uuid_mod.uuid4().hex[:8]+ name = f"intg-resource-policy-{uid}"+ document = json.dumps(+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Sid": "AllowLogsDelivery",+ "Effect": "Allow",+ "Principal": {"Service": "delivery.logs.amazonaws.com"},+ "Action": "logs:PutSubscriptionFilter",+ "Resource": "*",+ }+ ],+ }+ )++ put_resp = logs.put_resource_policy(policyName=name, policyDocument=document)+ assert put_resp["resourcePolicy"]["policyName"] == name+ assert put_resp["resourcePolicy"]["policyDocument"] == document+ assert put_resp["resourcePolicy"]["revisionId"] == put_resp["revisionId"]++ describe_resp = logs.describe_resource_policies()+ policy = next(p for p in describe_resp["resourcePolicies"] if p["policyName"] == name)+ assert policy["policyDocument"] == document++ logs.delete_resource_policy(policyName=name)+ describe_resp = logs.describe_resource_policies()+ assert not any(p["policyName"] == name for p in describe_resp["resourcePolicies"])+++def test_logs_resource_policy_requires_name_and_document(logs):+ with pytest.raises(ClientError) as exc:+ logs.put_resource_policy(policyName="", policyDocument="{}")+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"+++def test_logs_delete_resource_policy_requires_existing(logs):+ with pytest.raises(ClientError) as exc:+ logs.delete_resource_policy(policyName="does-not-exist")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_logs_put_resource_policy_rejects_stale_revision(logs):+ """expectedRevisionId lets a caller detect concurrent modification."""+ uid = _uuid_mod.uuid4().hex[:8]+ name = f"intg-resource-policy-rev-{uid}"+ put_resp = logs.put_resource_policy(policyName=name, policyDocument="{}")+ stale_revision = put_resp["revisionId"] + "-stale"++ with pytest.raises(ClientError) as exc:+ logs.put_resource_policy(+ policyName=name, policyDocument="{}", expectedRevisionId=stale_revision,+ )+ assert exc.value.response["Error"]["Code"] == "OperationAbortedException"++ logs.delete_resource_policy(policyName=name)++# ---------------------------------------------------------------------------# ARN-based tagging operations (TagResource / UntagResource)# ---------------------------------------------------------------------------