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(agentcore): enforce runtime invocation IAM (#1867)
Lisandro Pintos5e96c080d847
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c7452a3e..238d75aa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,17 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Fixed++- **Bedrock AgentCore — `InvokeAgentRuntime` enforces IAM policies** — with `AUTH=true`, runtime invocations now resolve to `bedrock-agentcore:InvokeAgentRuntime` and authorize against the ARN in the request path, so a policy can allow one runtime and deny another. Previously, the action was not extracted and the request bypassed identity-policy evaluation.+- **IAM — a negated condition operator is true when its key is absent** — the evaluator treated an absent key as a failed condition for every operator, so a `Deny` guarded by `StringNotEquals`, `StringNotLike`, `ArnNotLike`, `NotIpAddress` or another negated operator never applied to a request without that key. AWS evaluates such a condition as true and denies. The single-valued negated operators now do the same, while `ForAnyValue` and the affirmative operators still fail on an absent key. Contributed by @iot-rocket.+- **KMS — `GenerateDataKey` returns `KeyMaterialId`** — requests without `Recipient` now include the identifier of the wrapping key material. The identifier remains stable across requests and persistence reloads, and changes when the wrapping material changes. Fixes #1853.+- **Secrets Manager — `BatchGetSecretValue` returns only the secrets the caller may read** — under `AUTH=true` a grant on `secretsmanager:BatchGetSecretValue` alone returned every secret in the request, and `Filters` were ignored, so a filtered call returned the whole store. Each secret now needs `secretsmanager:GetSecretValue` and lands in `Errors` as `AccessDeniedException` without it, a call by `Filters` also needs `secretsmanager:ListSecrets`, and the filters select the secrets as in `ListSecrets`. Contributed by @iot-rocket.+- **CloudFormation — change set members follow the action** — `Add` and `Remove` changes carried `Replacement: False`, a `Remove` had no physical id, `PolicyAction` was never sent and a `Metadata` or policy detail had no `RequiresRecreation`. `Remove` and `Modify` now name the physical resource, a `Remove` answers `PolicyAction: Delete` and a replacing `Modify` `ReplaceAndDelete` unless the resource retains or snapshots, and attribute details answer `Never`. Contributed by @iot-rocket.+- **CloudFormation — `AWS::SQS::Queue` applies every queue property** — `RedrivePolicy`, `RedriveAllowPolicy`, `KmsMasterKeyId`, `KmsDataKeyReusePeriodSeconds`, `SqsManagedSseEnabled`, `DeduplicationScope` and `FifoThroughputLimit` were dropped on create and update, so a dead-letter queue declared in a template never received messages, and a value SQS refuses now fails the resource instead of being stored. Contributed by @iot-rocket.+- **Lambda — Docker executor honors timeouts above 300 seconds** — pass the configured `Timeout` to AWS RIE through `AWS_LAMBDA_FUNCTION_TIMEOUT`, preventing its default 300-second limit from ending longer invocations early. Timeout updates recycle warm containers so the RIE deadline follows the new configuration (#1844).+- **KMS — `GenerateDataKey` returns `KeyMaterialId`** — requests without `Recipient` now include the identifier of the wrapping key material. The identifier remains stable across requests and persistence reloads, and changes when the wrapping material changes. Fixes #1853.+- **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- **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/core/iam_actions.py b/ministack/core/iam_actions.pyindex e298764e..d9f434da 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -40,7 +40,7 @@ SERVICE_TO_IAM_NAMESPACE: dict[str, str] = {"bedrock": "bedrock","bedrock-agent": "bedrock","bedrock-agent-runtime": "bedrock",- "bedrock-agentcore": "bedrock",+ "bedrock-agentcore": "bedrock-agentcore","bedrock-runtime": "bedrock","cloudcontrol": "cloudformation","cloudformation": "cloudformation",@@ -456,7 +456,9 @@ _BOTOCORE_SERVICE_MAP: dict[str, list[str]] = {"bedrock-runtime": ["bedrock-runtime"],"bedrock-agent": ["bedrock-agent"],"bedrock-agent-runtime": ["bedrock-agent-runtime"],- "bedrock-agentcore": [], # no botocore model yet+ # InvokeAgentRuntime is mapped explicitly below so AUTH works even with+ # Botocore versions that predate the AgentCore service model.+ "bedrock-agentcore": [],"cloudfront": ["cloudfront"],"cloudfront-keyvaluestore": ["cloudfront-keyvaluestore"],"dsql": ["dsql"],@@ -656,6 +658,12 @@ def _match_rest_action(service: str, method: str, path: str,return best_match+def _agentcore_runtime_arn(path: str) -> str | None:+ """Extract the runtime ARN from an InvokeAgentRuntime URI."""+ match = re.fullmatch(r"/runtimes/(.+?)/invocations/?", unquote(path))+ return match.group(1) if match else None++def extract_iam_action(service: str, method: str, path: str,headers: dict, body: bytes,query_params: dict) -> str | None:@@ -687,6 +695,10 @@ def extract_iam_action(service: str, method: str, path: str,if action_name:return f"lambda:{action_name}"+ if service == "bedrock-agentcore" and method == "POST":+ if _agentcore_runtime_arn(path):+ return "bedrock-agentcore:InvokeAgentRuntime"+# Tier 4: Generic botocore route matcher (all other REST services)action_name = _match_rest_action(service, method, path, query_params)if action_name:@@ -847,6 +859,9 @@ def extract_resource_arn(service: str, method: str, path: str,return resources[0]return "*"+ if service == "bedrock-agentcore" and method == "POST":+ return _agentcore_runtime_arn(path) or "*"+if service == "lambda":# Path: /2015-03-31/functions/{name}/...path_parts = [p for p in path.split("/") if p]diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex 8a2137b8..025545d5 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -2152,6 +2152,126 @@ class TestActionExtraction:assert extract_iam_action("iot", "PUT", "/jobs/rollout-2024", {}, b"", {}) == "iot:CreateJob"assert extract_iam_action("iot-data", "POST", "/topics/a/b/c", {}, b"", {}) == "iot:Publish"+ def test_agentcore_invoke_resolves_through_the_router(self):+ """The AgentCore signing scope and InvokeAgentRuntime path are recognized."""+ from ministack.core.iam_actions import extract_iam_action, extract_resource_arn+ from ministack.core.router import detect_service++ headers = _sigv4_headers(+ "bedrock-agentcore", "bedrock-agentcore.us-east-1.amazonaws.com"+ )+ path = (+ "/runtimes/arn%3Aaws%3Abedrock-agentcore%3Aus-east-1%3A"+ "000000000000%3Aruntime%2Frt-example/invocations"+ )+ service = detect_service("POST", path, headers, {})+ assert service == "bedrock-agentcore"+ assert extract_iam_action(service, "POST", path, headers, b"{}", {}) == (+ "bedrock-agentcore:InvokeAgentRuntime"+ )+ decoded_path = (+ "/runtimes/arn:aws:bedrock-agentcore:us-east-1:000000000000:"+ "runtime/rt-example/invocations"+ )+ assert extract_iam_action(service, "POST", decoded_path, headers, b"{}", {}) == (+ "bedrock-agentcore:InvokeAgentRuntime"+ )+ assert extract_resource_arn(+ service, "POST", path, headers, b"{}", {}, "us-east-1", "000000000000"+ ) == "arn:aws:bedrock-agentcore:us-east-1:000000000000:runtime/rt-example"+ assert extract_resource_arn(+ service, "POST", decoded_path, headers, b"{}", {}, "us-east-1", "000000000000"+ ) == "arn:aws:bedrock-agentcore:us-east-1:000000000000:runtime/rt-example"+ assert extract_iam_action(service, "GET", decoded_path, headers, b"{}", {}) is None+ assert extract_iam_action(+ service, "POST", "/runtimes//invocations", headers, b"{}", {}+ ) is None+++class TestBedrockAgentCoreAuthorization:+ _RUNTIME_ARN = "arn:aws:bedrock-agentcore:us-east-1:000000000000:runtime/rt-example"+ _OTHER_RUNTIME_ARN = "arn:aws:bedrock-agentcore:us-east-1:000000000000:runtime/rt-other"++ @staticmethod+ def _invoke(path, monkeypatch, policy):+ import asyncio++ import ministack.app as app_mod+ from ministack.core import iam_evaluator++ statements = parse_policy_document(policy)+ seen = []++ def enforce_stub(access_key_id, iam_action, service, region, resource_arn="*",+ service_context=None):+ seen.append((iam_action, service, region, resource_arn))+ result = evaluate(_ctx(action=iam_action, resource=resource_arn), [statements])+ if result.decision == "Allow":+ return None+ result.principal_arn = "arn:aws:iam::000000000000:user/testuser"+ return result++ async def invoke_handler(method, request_path, headers, body, query):+ return 200, {"Content-Type": "application/json"}, b"{}"++ monkeypatch.setattr(app_mod, "AUTH", True, raising=False)+ monkeypatch.setattr(iam_evaluator, "enforce", enforce_stub)+ monkeypatch.setitem(app_mod.SERVICE_HANDLERS, "bedrock-agentcore", invoke_handler)+ headers = {+ **_sigv4_headers(+ "bedrock-agentcore", "bedrock-agentcore.us-east-1.amazonaws.com"+ ),+ "host": "bedrock-agentcore.us-east-1.amazonaws.com",+ }+ headers["authorization"] = headers["authorization"].replace(+ "20260101/eu-central-1/", "20260101/us-east-1/"+ )+ response = asyncio.run(+ app_mod._dispatch_service_request("POST", path, headers, b"{}", {}, "req-agentcore")+ )+ return response, seen++ def test_invoke_allows_the_exact_runtime_resource(self, monkeypatch):+ path = "/runtimes/" + self._RUNTIME_ARN.replace(":", "%3A").replace("/", "%2F") + "/invocations"+ response, seen = self._invoke(+ path,+ monkeypatch,+ {"Statement": [{+ "Effect": "Allow",+ "Action": "bedrock-agentcore:InvokeAgentRuntime",+ "Resource": self._RUNTIME_ARN,+ }]},+ )++ assert response[0] == 200+ assert seen == [(+ "bedrock-agentcore:InvokeAgentRuntime",+ "bedrock-agentcore",+ "us-east-1",+ self._RUNTIME_ARN,+ )]++ def test_invoke_denies_a_different_runtime_resource(self, monkeypatch):+ path = "/runtimes/" + self._OTHER_RUNTIME_ARN.replace(":", "%3A").replace("/", "%2F") + "/invocations"+ response, seen = self._invoke(+ path,+ monkeypatch,+ {"Statement": [{+ "Effect": "Allow",+ "Action": "bedrock-agentcore:InvokeAgentRuntime",+ "Resource": self._RUNTIME_ARN,+ }]},+ )++ assert response[0] == 403+ assert b"AccessDenied" in response[2]+ assert seen == [(+ "bedrock-agentcore:InvokeAgentRuntime",+ "bedrock-agentcore",+ "us-east-1",+ self._OTHER_RUNTIME_ARN,+ )]+@pytest.mark.parametrize("granted,decision", [("iot:*", "ImplicitDeny"),("iotjobsdata:UpdateJobExecution", "Allow"),