Skip to content

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

fix(iam): seed the AWS-managed policies under their real ARNs (#1596)

iot-rocketc653a3c707bf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3777b065..69a61f62 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
+- **IAM — the AWS-managed policies a CDK, SAM or Serverless deployment attaches resolve by their real ARNs** — the seeded catalogue filed the Lambda execution-role policies under `arn:aws:iam::aws:policy/<Name>` while AWS publishes them under `…:policy/service-role/<Name>`, the only ARN those tools emit, so `GetPolicy` on the real ARN answered `NoSuchEntity` and under `AUTH=true` a role that attached one carried no permissions from it; `AWSCloudFormationReadOnlyAccess` (the CDK deploy role's read grant), `CloudWatchLambdaInsightsExecutionRolePolicy`, `service-role/AmazonAPIGatewayPushToCloudWatchLogs` and `service-role/AWSIoTThingsRegistration` were missing altogether, which denied `cdk deploy` its first `DescribeStacks` under enforcement. The catalogue now carries them under their real path with the documents from the AWS Managed Policy Reference, reports `PolicyName` and `Path` as AWS does (so `ListPolicies` with `PathPrefix=/service-role/` finds them), adds the SQS, Kinesis and DynamoDB Lambda execution-role policies, and keeps the four path-less ARNs earlier versions seeded as aliases of the real record. Contributed by @iot-rocket.
+
- **IAM enforcement — the `aws:ResourceAccount` condition key resolves** — with `AUTH=true` a statement conditioned on `aws:ResourceAccount` (or its `s3:ResourceAccount` alias) never matched: the key was unknown to the evaluator, an unknown key is a no-match, and the statement's Allow never applied. CDK's own bootstrap template conditions the file-publishing role's S3 grant on exactly this key, so every `cdk deploy` under enforcement failed at asset publishing with "Bucket ... exists, but we dont have access to it". The key now resolves to the account that owns the resource — the requesting account, since MiniStack hosts one account per request and models no cross-account access, unless the resource ARN carries a different account field, which wins. A condition naming another account still denies, and every other unknown global key keeps denying. Contributed by @iot-rocket.
- **IAM enforcement — S3 multipart uploads authorize as `s3:PutObject`** — with `AUTH=true` a `CreateMultipartUpload` was checked as the literal action `s3:CreateMultipartUpload`, which no policy grants because it is not an IAM action; `UploadPart`, `CompleteMultipartUpload`, `AbortMultipartUpload` and `ListParts` fell to the generic object actions. Every upload above the SDK's multipart threshold was therefore denied, and `cdk deploy` failed on its first Lambda layer asset even with a correct file-publishing role. The operations now map to the actions S3 documents: the three upload steps to `s3:PutObject`, abort to `s3:AbortMultipartUpload`, the listings to `s3:ListBucketMultipartUploads` / `s3:ListMultipartUploadParts`; `?versions` is `s3:ListBucketVersions`, object-level `?tagging` / `?acl` are the object actions rather than the bucket ones, and the `DELETE` calls on the lifecycle, encryption, replication, tagging and CORS configurations authorize as the matching `Put*` action, since S3 defines no `Delete*` action for them (the table named actions such as `s3:DeleteBucketCors` that no policy can grant). Contributed by @iot-rocket.
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index 83468630..0745fe13 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -606,9 +606,12 @@ def _resolve_managed_policy_document(policy_arn: str,
"""Resolve a managed policy ARN to its default version's document."""
from ministack.services import iam as iam_svc
- # AWS-managed policy
+ # AWS-managed policy — through the service's own lookup so that
+ # MINISTACK_AUTOCREATE_AWS_MANAGED applies to enforcement exactly as it
+ # applies to GetPolicy (an attached-but-never-fetched ARN used to resolve
+ # to nothing here while GetPolicy would have autocreated it).
if policy_arn.startswith("arn:aws:iam::aws:policy/"):
- mp = iam_svc._aws_managed_policies.get(policy_arn)
+ mp = iam_svc._lookup_policy(policy_arn)
if mp:
default_vid = mp.get("DefaultVersionId", "v1")
versions = mp.get("Versions", {})
diff --git a/ministack/services/iam.py b/ministack/services/iam.py
index 82f5906d..7c506090 100644
--- a/ministack/services/iam.py
+++ b/ministack/services/iam.py
@@ -151,11 +151,18 @@ def _autovivify_aws_managed_policy(arn: str) -> dict:
def _make_aws_managed_record(name: str, document: str, description: str = "") -> dict:
- """Build a policy record matching the shape ``_create_policy`` stores."""
+ """Build a policy record matching the shape ``_create_policy`` stores.
+
+ ``name`` is the ARN's resource part, path included
+ (``service-role/AWSLambdaBasicExecutionRole``): the path becomes the
+ record's ``Path`` and only the last segment its ``PolicyName``, as AWS
+ reports them — Terraform's ``aws_iam_policy`` data source and
+ ``ListPolicies PathPrefix`` both read those two fields."""
arn = f"{_AWS_MANAGED_POLICY_PREFIX}{name}"
+ path, _, policy_name = name.rpartition("/")
created = _now()
return {
- "PolicyName": name,
+ "PolicyName": policy_name,
"Arn": arn,
"PolicyId": _gen_id("ANPA"),
"CreateDate": created,
@@ -163,7 +170,7 @@ def _make_aws_managed_record(name: str, document: str, description: str = "") ->
"DefaultVersionId": "v1",
"AttachmentCount": 0,
"IsAttachable": True,
- "Path": "/",
+ "Path": f"/{path}/" if path else "/",
"Description": description,
"Tags": [],
"Versions": {
@@ -202,6 +209,44 @@ def _seed_aws_managed_policies() -> None:
update via ``aws iam get-policy-version`` against real AWS when
a new policy version ships."""
seeds = [
+ # The service-role/* policies live under that path on AWS: it is the
+ # only ARN CDK, SAM and Serverless emit for a Lambda execution role.
+ # Earlier versions seeded four of them under a path-less ARN AWS does
+ # not publish; those stay reachable as aliases of the real record
+ # (``_AWS_MANAGED_POLICY_ALIASES``).
+ ('service-role/AWSLambdaBasicExecutionRole',
+ '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],"Resource":"*"}]}',
+ "Provides write permissions to CloudWatch Logs."),
+ ('service-role/AWSLambdaVPCAccessExecutionRole',
+ '{"Version":"2012-10-17","Statement":[{"Sid":"AWSLambdaVPCAccessExecutionPermissions","Effect":"Allow","Action":["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents","ec2:CreateNetworkInterface","ec2:DescribeNetworkInterfaces","ec2:DescribeSubnets","ec2:DeleteNetworkInterface","ec2:AssignPrivateIpAddresses","ec2:UnassignPrivateIpAddresses"],"Resource":"*"}]}',
+ "Provides minimum permissions for a Lambda function to execute while accessing a resource within a VPC - create, describe, delete network interfaces and write permissions to CloudWatch Logs."),
+ ('service-role/AWSLambdaRole',
+ '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["lambda:InvokeFunction"],"Resource":["*"]}]}',
+ "Default policy for AWS Lambda service role."),
+ ('service-role/AmazonECSTaskExecutionRolePolicy',
+ '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","logs:CreateLogStream","logs:PutLogEvents"],"Resource":"*"}]}',
+ "Provides access to other AWS service resources that are required to run Amazon ECS tasks"),
+ ('service-role/AmazonAPIGatewayPushToCloudWatchLogs',
+ '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["logs:CreateLogGroup","logs:CreateLogStream","logs:DescribeLogGroups","logs:DescribeLogStreams","logs:PutLogEvents","logs:GetLogEvents","logs:FilterLogEvents"],"Resource":"*"}]}',
+ "Allows API Gateway to push logs to user's account."),
+ ('service-role/AWSIoTThingsRegistration',
+ '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["iot:AddThingToThingGroup","iot:AttachPolicy","iot:AttachPrincipalPolicy","iot:AttachThingPrincipal","iot:CreateCertificateFromCsr","iot:CreatePolicy","iot:CreateThing","iot:DescribeCertificate","iot:DescribeThing","iot:DescribeThingGroup","iot:DescribeThingType","iot:DetachPolicy","iot:DetachThingPrincipal","iot:GetPolicy","iot:ListAttachedPolicies","iot:ListPolicyPrincipals","iot:ListPrincipalPolicies","iot:ListPrincipalThings","iot:ListTargetsForPolicy","iot:ListThingGroupsForThing","iot:ListThingPrincipals","iot:RegisterCertificate","iot:RegisterThing","iot:RemoveThingFromThingGroup","iot:UpdateCertificate","iot:UpdateThing","iot:UpdateThingGroupsForThing","iot:AddThingToBillingGroup","iot:DescribeBillingGroup","iot:RemoveThingFromBillingGroup"],"Resource":["*"]}]}',
+ "This policy allows users to register things at bulk using AWS IoT StartThingRegistrationTask API"),
+ ('AWSCloudFormationReadOnlyAccess',
+ '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["cloudformation:Describe*","cloudformation:BatchDescribe*","cloudformation:EstimateTemplateCost","cloudformation:Get*","cloudformation:List*","cloudformation:ValidateTemplate","cloudformation:Detect*"],"Resource":"*"}]}',
+ "Provides access to AWS CloudFormation via the AWS Management Console."),
+ ('CloudWatchLambdaInsightsExecutionRolePolicy',
+ '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"logs:CreateLogGroup","Resource":"*"},{"Effect":"Allow","Action":["logs:CreateLogStream","logs:PutLogEvents"],"Resource":"arn:aws:logs:*:*:log-group:/aws/lambda-insights:*"}]}',
+ "Policy required for the Lambda Insights Extension"),
+ ('service-role/AWSLambdaSQSQueueExecutionRole',
+ '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],"Resource":"*"}]}',
+ "Provides receive message, delete message, and read attribute access to SQS queues, and write permissions to CloudWatch logs."),
+ ('service-role/AWSLambdaKinesisExecutionRole',
+ '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["kinesis:DescribeStream","kinesis:DescribeStreamSummary","kinesis:GetRecords","kinesis:GetShardIterator","kinesis:ListShards","kinesis:ListStreams","kinesis:SubscribeToShard","logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],"Resource":"*"}]}',
+ "Provides list and read access to Kinesis streams and write permissions to CloudWatch logs."),
+ ('service-role/AWSLambdaDynamoDBExecutionRole',
+ '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["dynamodb:DescribeStream","dynamodb:GetRecords","dynamodb:GetShardIterator","dynamodb:ListStreams","logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],"Resource":"*"}]}',
+ "Provides list and read access to DynamoDB streams and write permissions to CloudWatch logs."),
('AdministratorAccess',
'{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"*","Resource":"*"}]}',
"Provides full access to AWS services and resources."),
@@ -238,21 +283,12 @@ def _seed_aws_managed_policies() -> None:
('AmazonDynamoDBFullAccess',
'{"Version":"2012-10-17","Statement":[{"Action":["dynamodb:*","dax:*","application-autoscaling:DeleteScalingPolicy","application-autoscaling:DeregisterScalableTarget","application-autoscaling:DescribeScalableTargets","application-autoscaling:DescribeScalingActivities","application-autoscaling:DescribeScalingPolicies","application-autoscaling:PutScalingPolicy","application-autoscaling:RegisterScalableTarget","cloudwatch:DeleteAlarms","cloudwatch:DescribeAlarmHistory","cloudwatch:DescribeAlarms","cloudwatch:DescribeAlarmsForMetric","cloudwatch:GetMetricStatistics","cloudwatch:ListMetrics","cloudwatch:PutMetricAlarm","cloudwatch:GetMetricData","datapipeline:ActivatePipeline","datapipeline:CreatePipeline","datapipeline:DeletePipeline","datapipeline:DescribeObjects","datapipeline:DescribePipelines","datapipeline:GetPipelineDefinition","datapipeline:ListPipelines","datapipeline:PutPipelineDefinition","datapipeline:QueryObjects","ec2:DescribeVpcs","ec2:DescribeSubnets","ec2:DescribeSecurityGroups","iam:GetRole","iam:ListRoles","kms:DescribeKey","kms:ListAliases","sns:CreateTopic","sns:DeleteTopic","sns:ListSubscriptions","sns:ListSubscriptionsByTopic","sns:ListTopics","sns:Subscribe","sns:Unsubscribe","sns:SetTopicAttributes","lambda:CreateFunction","lambda:ListFunctions","lambda:ListEventSourceMappings","lambda:CreateEventSourceMapping","lambda:DeleteEventSourceMapping","lambda:GetFunctionConfiguration","lambda:DeleteFunction","resource-groups:ListGroups","resource-groups:ListGroupResources","resource-groups:GetGroup","resource-groups:GetGroupQuery","resource-groups:DeleteGroup","resource-groups:CreateGroup","tag:GetResources","kinesis:ListStreams","kinesis:DescribeStream","kinesis:DescribeStreamSummary"],"Effect":"Allow","Resource":"*"},{"Action":"cloudwatch:GetInsightRuleReport","Effect":"Allow","Resource":"arn:aws:cloudwatch:*:*:insight-rule/DynamoDBContributorInsights*"},{"Action":["iam:PassRole"],"Effect":"Allow","Resource":"*","Condition":{"StringLike":{"iam:PassedToService":["application-autoscaling.amazonaws.com","application-autoscaling.amazonaws.com.cn","dax.amazonaws.com"]}}},{"Effect":"Allow","Action":["iam:CreateServiceLinkedRole"],"Resource":"*","Condition":{"StringEquals":{"iam:AWSServiceName":["replication.dynamodb.amazonaws.com","dax.amazonaws.com","dynamodb.application-autoscaling.amazonaws.com","contributorinsights.dynamodb.amazonaws.com","kinesisreplication.dynamodb.amazonaws.com"]}}}]}',
"Provides full access to Amazon DynamoDB via the AWS Management Console."),
- ('AWSLambdaBasicExecutionRole',
- '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],"Resource":"*"}]}',
- "Provides write permissions to CloudWatch Logs."),
- ('AWSLambdaVPCAccessExecutionRole',
- '{"Version":"2012-10-17","Statement":[{"Sid":"AWSLambdaVPCAccessExecutionPermissions","Effect":"Allow","Action":["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents","ec2:CreateNetworkInterface","ec2:DescribeNetworkInterfaces","ec2:DescribeSubnets","ec2:DeleteNetworkInterface","ec2:AssignPrivateIpAddresses","ec2:UnassignPrivateIpAddresses"],"Resource":"*"}]}',
- "Provides minimum permissions for a Lambda function to execute while accessing a resource within a VPC - create, describe, delete network interfaces and write permissions to CloudWatch Logs."),
('AmazonSQSFullAccess',
'{"Version":"2012-10-17","Statement":[{"Action":["sqs:*"],"Effect":"Allow","Resource":"*"}]}',
"Provides full access to Amazon SQS via the AWS Management Console."),
('AmazonSNSFullAccess',
'{"Version":"2012-10-17","Statement":[{"Sid":"SNSFullAccess","Effect":"Allow","Action":"sns:*","Resource":"*"},{"Sid":"SMSAccessViaSNS","Effect":"Allow","Action":["sms-voice:DescribeVerifiedDestinationNumbers","sms-voice:CreateVerifiedDestinationNumber","sms-voice:SendDestinationNumberVerificationCode","sms-voice:SendTextMessage","sms-voice:DeleteVerifiedDestinationNumber","sms-voice:VerifyDestinationNumber","sms-voice:DescribeAccountAttributes","sms-voice:DescribeSpendLimits","sms-voice:DescribePhoneNumbers","sms-voice:SetTextMessageSpendLimitOverride","sms-voice:DescribeOptedOutNumbers","sms-voice:DeleteOptedOutNumber"],"Resource":"*","Condition":{"StringEquals":{"aws:CalledViaLast":"sns.amazonaws.com"}}}]}',
"Provides full access to Amazon SNS via the AWS Management Console."),
- ('AmazonECSTaskExecutionRolePolicy',
- '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","logs:CreateLogStream","logs:PutLogEvents"],"Resource":"*"}]}',
- "Provides access to other AWS service resources that are required to run Amazon ECS tasks"),
('CloudWatchAgentServerPolicy',
'{"Version":"2012-10-17","Statement":[{"Sid":"CWACloudWatchServerPermissions","Effect":"Allow","Action":["cloudwatch:PutMetricData","ec2:DescribeVolumes","ec2:DescribeTags","logs:PutLogEvents","logs:PutRetentionPolicy","logs:DescribeLogStreams","logs:DescribeLogGroups","logs:CreateLogStream","logs:CreateLogGroup","xray:PutTraceSegments","xray:PutTelemetryRecords","xray:GetSamplingRules","xray:GetSamplingTargets","xray:GetSamplingStatisticSummaries"],"Resource":"*"},{"Sid":"CWASSMServerPermissions","Effect":"Allow","Action":["ssm:GetParameter"],"Resource":"arn:aws:ssm:*:*:parameter/AmazonCloudWatch-*"}]}',
"Permissions required to use AmazonCloudWatchAgent on servers"),
@@ -285,15 +321,29 @@ def _seed_aws_managed_policies() -> None:
('AWSXrayReadOnlyAccess',
'{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["xray:GetSamplingRules","xray:GetSamplingTargets","xray:GetSamplingStatisticSummaries","xray:BatchGetTraces","xray:BatchGetTraceSummaryById","xray:GetDistinctTraceGraphs","xray:GetServiceGraph","xray:GetTraceGraph","xray:GetTraceSummaries","xray:GetGroups","xray:GetGroup","xray:ListTagsForResource","xray:ListResourcePolicies","xray:GetTimeSeriesServiceStatistics","xray:GetInsightSummaries","xray:GetInsight","xray:GetInsightEvents","xray:GetInsightImpactGraph"],"Resource":["*"]}]}',
"AWS X-Ray read-only access. Grants permission to retrieve trace data, service graphs, and sampling rules."),
- ('AWSLambdaRole',
- '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["lambda:InvokeFunction"],"Resource":["*"]}]}',
- "Default policy for AWS Lambda service role — permits Lambda to invoke other Lambda functions."),
]
for name, document, description in seeds:
_aws_managed_policies[f"{_AWS_MANAGED_POLICY_PREFIX}{name}"] = _make_aws_managed_record(
name, document, description,
)
+ for alias, real in _AWS_MANAGED_POLICY_ALIASES.items():
+ _aws_managed_policies[f"{_AWS_MANAGED_POLICY_PREFIX}{alias}"] = (
+ _aws_managed_policies[f"{_AWS_MANAGED_POLICY_PREFIX}{real}"]
+ )
+
+
+# Path-less ARNs earlier versions seeded for policies AWS only publishes under
+# ``service-role/``. They do not exist on AWS, but templates written against
+# those versions attach them, so each resolves to the real policy's record —
+# the same object, so the document, id and attachment count are shared.
+# ``ListPolicies`` reports the real ARN only.
+_AWS_MANAGED_POLICY_ALIASES: dict[str, str] = {
+ "AWSLambdaBasicExecutionRole": "service-role/AWSLambdaBasicExecutionRole",
+ "AWSLambdaVPCAccessExecutionRole": "service-role/AWSLambdaVPCAccessExecutionRole",
+ "AWSLambdaRole": "service-role/AWSLambdaRole",
+ "AmazonECSTaskExecutionRolePolicy": "service-role/AmazonECSTaskExecutionRolePolicy",
+}
# ── Persistence ────────────────────────────────────────────
@@ -810,6 +860,8 @@ def _list_policies(p):
# AWS-managed policies — returned for scope "All" or "AWS".
if scope != "Local":
for arn, pol in _aws_managed_policies.items():
+ if pol.get("Arn") != arn: # a legacy alias of a real policy
+ continue
if not pol.get("Path", "/").startswith(prefix):
continue
members += f"<member>{_managed_policy_xml(arn)}</member>"
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 5f5d0c1b..13302c1e 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -789,6 +789,97 @@ class TestEnforce:
iam_svc._access_keys.pop(fake_key, None)
iam_svc._users.pop("inline-user", None)
iam_svc._user_inline_policies.pop("inline-user", None)
+class TestSeededAwsManagedPolicies:
+ """The AWS-managed policies CDK, SAM and Serverless attach by their real ARNs
+ resolve to a document: the service-role/* path is the only one AWS has for the
+ Lambda execution roles, and a CDK deploy role reads stacks through
+ AWSCloudFormationReadOnlyAccess."""
+
+ @pytest.mark.parametrize("name,action", [
+ ("service-role/AWSLambdaBasicExecutionRole", "logs:PutLogEvents"),
+ ("service-role/AWSLambdaVPCAccessExecutionRole", "ec2:CreateNetworkInterface"),
+ ("service-role/AmazonAPIGatewayPushToCloudWatchLogs", "logs:CreateLogGroup"),
+ ("service-role/AWSIoTThingsRegistration", "iot:RegisterThing"),
+ ("AWSCloudFormationReadOnlyAccess", "cloudformation:DescribeStacks"),
+ ("AWSCloudFormationReadOnlyAccess", "cloudformation:BatchDescribeTypeConfigurations"),
+ ("CloudWatchLambdaInsightsExecutionRolePolicy", "logs:CreateLogGroup"),
+ ("service-role/AWSLambdaSQSQueueExecutionRole", "sqs:ReceiveMessage"),
+ ("service-role/AWSLambdaKinesisExecutionRole", "kinesis:GetRecords"),
+ ("service-role/AWSLambdaDynamoDBExecutionRole", "dynamodb:GetShardIterator"),
+ ])
+ def test_real_arn_resolves_and_grants(self, name, action):
+ from ministack.core.iam_evaluator import _resolve_managed_policy_document
+ doc = _resolve_managed_policy_document(f"arn:aws:iam::aws:policy/{name}", "000000000000")
+ assert doc, name
+ stmts = parse_policy_document(doc)
+ assert evaluate(_ctx(action=action), [stmts]).decision == "Allow", action
+
+ def test_lambda_insights_log_writes_are_scoped_to_its_log_group(self):
+ from ministack.core.iam_evaluator import _resolve_managed_policy_document
+ stmts = parse_policy_document(_resolve_managed_policy_document(
+ "arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy", "000000000000"))
+ insights = "arn:aws:logs:us-east-1:000000000000:log-group:/aws/lambda-insights:log-stream:x"
+ assert evaluate(_ctx(action="logs:PutLogEvents", resource=insights), [stmts]).decision == "Allow"
+ other = "arn:aws:logs:us-east-1:000000000000:log-group:/aws/lambda/f:log-stream:x"
+ assert evaluate(_ctx(action="logs:PutLogEvents", resource=other), [stmts]).decision == "ImplicitDeny"
+
+ @pytest.mark.parametrize("name", [
+ "service-role/AWSLambdaBasicExecutionRole",
+ "service-role/AmazonAPIGatewayPushToCloudWatchLogs",
+ ])
+ def test_get_policy_reports_path_and_bare_name(self, name):
+ from ministack.services.iam import _get_policy
+ status, _, body = _get_policy({"PolicyArn": [f"arn:aws:iam::aws:policy/{name}"]})
+ body = body.decode()
+ assert status == 200
+ path, _, policy_name = name.rpartition("/")
+ assert f"<PolicyName>{policy_name}</PolicyName>" in body
+ assert f"<Path>/{path}/</Path>" in body
+ assert f"<Arn>arn:aws:iam::aws:policy/{name}</Arn>" in body
+
+ def test_list_policies_by_path_prefix_finds_service_role_policies(self):
+ from ministack.services.iam import _list_policies
+ body = _list_policies({"Scope": ["AWS"], "PathPrefix": ["/service-role/"]})[2].decode()
+ assert "<Arn>arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole</Arn>" in body
+ assert "<Arn>arn:aws:iam::aws:policy/AdministratorAccess</Arn>" not in body
+
+ def test_legacy_bare_arn_is_an_alias_of_the_real_policy(self):
+ # Earlier versions seeded the Lambda execution-role policies under an
+ # ARN without the service-role/ path. Templates written against them
+ # still resolve — to the same record — but ListPolicies reports the
+ # real ARN only.
+ from ministack.core.iam_evaluator import _resolve_managed_policy_document
+ from ministack.services.iam import _get_policy, _list_policies
+ bare = "arn:aws:iam::aws:policy/AWSLambdaBasicExecutionRole"
+ real = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
+ assert (_resolve_managed_policy_document(bare, "000000000000")
+ == _resolve_managed_policy_document(real, "000000000000"))
+ status, _, body = _get_policy({"PolicyArn": [bare]})
+ assert status == 200 and f"<Arn>{bare}</Arn>" in body.decode()
+ listing = _list_policies({"Scope": ["AWS"]})[2].decode()
+ assert f"<Arn>{real}</Arn>" in listing
+ assert f"<Arn>{bare}</Arn>" not in listing
+
+ def test_cloudformation_readonly_does_not_grant_writes(self):
+ from ministack.core.iam_evaluator import _resolve_managed_policy_document
+ doc = _resolve_managed_policy_document(
+ "arn:aws:iam::aws:policy/AWSCloudFormationReadOnlyAccess", "000000000000")
+ stmts = parse_policy_document(doc)
+ assert evaluate(_ctx(action="cloudformation:CreateStack"), [stmts]).decision == "ImplicitDeny"
+
+ def test_autocreate_applies_to_enforcement(self, monkeypatch):
+ from ministack.core.iam_evaluator import _resolve_managed_policy_document
+ from ministack.services import iam as iam_svc
+ arn = "arn:aws:iam::aws:policy/SomethingNobodySeeded"
+ monkeypatch.delenv("MINISTACK_AUTOCREATE_AWS_MANAGED", raising=False)
+ assert _resolve_managed_policy_document(arn, "000000000000") is None
+ monkeypatch.setenv("MINISTACK_AUTOCREATE_AWS_MANAGED", "1")
+ monkeypatch.setattr(iam_svc, "_aws_managed_policies", dict(iam_svc._aws_managed_policies))
+ doc = _resolve_managed_policy_document(arn, "000000000000")
+ assert doc and evaluate(_ctx(action="sqs:SendMessage"),
+ [parse_policy_document(doc)]).decision == "Allow"
+
+
# ---------------------------------------------------------------------------