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(iam): resolve aws:ResourceAccount under AUTH=true (#1594)
iot-rocket032d1348fde2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3bc64d34..3777b065 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added+- **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.- **Amazon Transcribe (`transcribe`)** is a new service emulator covering batch transcription jobs: `StartTranscriptionJob`, `GetTranscriptionJob`, `ListTranscriptionJobs` and `DeleteTranscriptionJob`, verified against botocore `transcribe-2017-10-26`. A job walks `QUEUED` → `IN_PROGRESS` → `COMPLETED` on a background task paced by `TRANSCRIBE_JOB_RUN_SECONDS` (default 2, `0` completes immediately), reads its media object from MiniStack's S3 store through an `s3://`, path-style or virtual-hosted HTTPS URI, and writes a transcript document back to S3 in the real Transcribe result format: `results.transcripts`, word-level `results.items`, `results.audio_segments`, and `results.segments` / `results.speaker_labels` when `ShowAlternatives` and `ShowSpeakerLabels` are set. `IdentifyLanguage` fills in `LanguageCode` and `IdentifiedLanguageScore` on completion while `IdentifyMultipleLanguages` reports `LanguageCodes` and leaves `LanguageCode` unset, as AWS does. `ContentRedaction` decides whether the `redacted-` copy replaces the transcript or sits beside it, and `Subtitles` writes WebVTT and SubRip files reported as `SubtitleFileUris`, redacted and renamed to match when redaction is on. Output lands at `OutputBucketName` / `OutputKey`, or in an auto-created `ministack-transcribe-output` bucket when neither is given, so the reported URIs are always fetchable. Media that cannot be read fails the job asynchronously with a `FailureReason` rather than erroring at `Start`, matching AWS, and a job left mid-flight by a restart fails on restore instead of stranding pollers. Reaching a terminal state publishes a `Transcribe Job State Change` event on the default bus, so an S3 → Lambda → Transcribe → EventBridge pipeline runs end to end locally. There is **no speech recognition**: the transcript is deterministic canned text keyed on a digest of the media URI, the same approach Bedrock Runtime takes for model output, which keeps integration tests reproducible. Streaming transcription, the call-analytics and medical job families, custom vocabularies and the tagging operations are not implemented. State is account- and region-scoped and persisted. Contributed by @ppettitau.diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.pyindex 9b6dde32..83468630 100644--- a/ministack/core/iam_evaluator.py+++ b/ministack/core/iam_evaluator.py@@ -130,6 +130,21 @@ def _resource_matches(resource_arn: str, resources: list[str],# Condition evaluation# ---------------------------------------------------------------------------+def _account_from_arn(arn: str) -> str | None:+ """The account field of an ARN, or None when the ARN carries none: ``*``,+ partition-only ARNs such as S3 (``arn:aws:s3:::bucket``), AWS-owned ARNs+ (``arn:aws:iam::aws:policy/...``) and malformed values."""+ if not arn or arn == "*" or not arn.startswith("arn:"):+ return None+ parts = arn.split(":", 5)+ if len(parts) < 6:+ return None+ account = parts[4]+ if not account or account == "aws":+ return None+ return account++def _resolve_condition_key(key: str, ctx: EvalContext) -> Any:"""Resolve a global condition context key to its value."""k = key.lower()@@ -154,6 +169,14 @@ def _resolve_condition_key(key: str, ctx: EvalContext) -> Any:if k.startswith("aws:requesttag/"):tag_key = key[len("aws:RequestTag/"):]return ctx.request_tags.get(tag_key)+ if k in ("aws:resourceaccount", "s3:resourceaccount"):+ # The account that owns the resource. The emulator hosts one account+ # per request and models no cross-account access, so it is the+ # requesting account — unless the resource ARN carries a different+ # account field, which then wins. CDK's bootstrap file-publishing+ # role conditions its S3 grant on this key, so leaving it unresolved+ # denied every `cdk deploy` under AUTH=true.+ return _account_from_arn(ctx.resource_arn) or ctx.principal_accountreturn None # key not presentdiff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex f789611f..5f5d0c1b 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -397,6 +397,87 @@ class TestConditions:assert evaluate(ctx, [stmts]).decision == "ImplicitDeny"++class TestResourceAccountCondition:+ """``aws:ResourceAccount`` (and the ``s3:ResourceAccount`` alias) resolve to the+ account that owns the resource. The emulator hosts one account per request and+ models no cross-account access, so that is the requesting account unless the+ resource ARN carries an account field. CDK's bootstrap file-publishing role+ conditions its S3 grant on this key, so an unresolved key denied every+ ``cdk deploy`` under AUTH=true."""++ _S3 = {"Effect": "Allow", "Action": ["s3:GetBucket*", "s3:List*"],+ "Resource": ["arn:aws:s3:::cdk-assets", "arn:aws:s3:::cdk-assets/*"]}++ def _policy(self, condition):+ return parse_policy_document({"Statement": [dict(self._S3, Condition=condition)]})++ def test_same_account_condition_allows(self):+ stmts = self._policy({"StringEquals": {"aws:ResourceAccount": ["000000000000"]}})+ ctx = _ctx(action="s3:GetBucketLocation", resource="arn:aws:s3:::cdk-assets")+ assert evaluate(ctx, [stmts]).decision == "Allow"++ def test_s3_alias_allows(self):+ stmts = self._policy({"StringEquals": {"s3:ResourceAccount": "000000000000"}})+ ctx = _ctx(action="s3:ListBucket", resource="arn:aws:s3:::cdk-assets")+ assert evaluate(ctx, [stmts]).decision == "Allow"++ def test_foreign_account_condition_still_denies(self):+ stmts = self._policy({"StringEquals": {"aws:ResourceAccount": ["111111111111"]}})+ ctx = _ctx(action="s3:GetBucketLocation", resource="arn:aws:s3:::cdk-assets")+ assert evaluate(ctx, [stmts]).decision == "ImplicitDeny"++ def test_resource_arn_account_field_wins(self):+ # An ARN that names a different owning account is that account's resource.+ stmts = parse_policy_document({"Statement": [{+ "Effect": "Allow", "Action": "sqs:SendMessage", "Resource": "*",+ "Condition": {"StringEquals": {"aws:ResourceAccount": "222222222222"}}}]})+ ctx = _ctx(action="sqs:SendMessage",+ resource="arn:aws:sqs:us-east-1:222222222222:queue")+ assert evaluate(ctx, [stmts]).decision == "Allow"+ ctx_own = _ctx(action="sqs:SendMessage",+ resource="arn:aws:sqs:us-east-1:000000000000:queue")+ assert evaluate(ctx_own, [stmts]).decision == "ImplicitDeny"++ def test_unknown_global_key_still_denies(self):+ stmts = self._policy({"StringEquals": {"aws:PrincipalOrgID": "o-abc"}})+ ctx = _ctx(action="s3:ListBucket", resource="arn:aws:s3:::cdk-assets")+ assert evaluate(ctx, [stmts]).decision == "ImplicitDeny"++ @pytest.mark.parametrize("arn,expected", [+ ("*", None),+ ("", None),+ ("arn:aws:s3:::bucket", None), # partition-only, no account+ ("arn:aws:s3:::bucket/key", None),+ ("arn:aws:iam::aws:policy/AdministratorAccess", None), # AWS-owned+ ("arn:aws:sqs:us-east-1:222222222222:q", "222222222222"),+ ("not-an-arn", None),+ ("arn:aws:sqs", None), # too short+ ])+ def test_account_from_arn(self, arn, expected):+ from ministack.core.iam_evaluator import _account_from_arn+ assert _account_from_arn(arn) == expected++ def test_deny_statement_conditioned_on_resource_account(self):+ # A Deny guarded by aws:ResourceAccount fires for the caller's own account.+ stmts = parse_policy_document({"Statement": [+ {"Effect": "Allow", "Action": "s3:*", "Resource": "*"},+ {"Effect": "Deny", "Action": "s3:DeleteObject", "Resource": "*",+ "Condition": {"StringEquals": {"s3:ResourceAccount": "000000000000"}}},+ ]})+ ctx = _ctx(action="s3:DeleteObject", resource="arn:aws:s3:::cdk-assets/x")+ assert evaluate(ctx, [stmts]).decision == "Deny"+ ctx = _ctx(action="s3:GetObject", resource="arn:aws:s3:::cdk-assets/x")+ assert evaluate(ctx, [stmts]).decision == "Allow"++ def test_string_not_equals_on_resource_account(self):+ # The CDK bootstrap shape inverted: allow only when the resource is NOT+ # in a foreign account — resolves to the caller's account, so it allows.+ stmts = self._policy({"StringNotEquals": {"aws:ResourceAccount": "111111111111"}})+ ctx = _ctx(action="s3:ListBucket", resource="arn:aws:s3:::cdk-assets")+ assert evaluate(ctx, [stmts]).decision == "Allow"++# ---------------------------------------------------------------------------# Trust policy evaluation (per AWS AssumeRole documentation)# ---------------------------------------------------------------------------