Skip to content

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

feat(agentcore): emulate resource-based policies (#1868)

Lisandro Pintos1b96016d1211
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 238d75aa..0ae40463 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,8 @@ 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
+- **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.
- **KMS — grants** — `CreateGrant`, `RevokeGrant` and `RetireGrant`; `ListGrants` now returns the grants they create, filtered by `GrantId` / `GranteePrincipal` and paged with `Limit` / `Marker`. `CreateGrant` follows the key state, rejects operations the key type cannot perform, and is idempotent for a named grant. Grants persist with the key and are not evaluated for authorization. Contributed by @DaviReisVieira.
diff --git a/README.md b/README.md
index c042a53b..69c9d24c 100644
--- a/README.md
+++ b/README.md
@@ -432,7 +432,7 @@ subnet = ec2.create_subnet(
| **Bedrock Runtime** | Converse, ConverseStream, InvokeModel, InvokeModelWithResponseStream, ApplyGuardrail, StartAsyncInvoke, GetAsyncInvoke, ListAsyncInvokes | Real eventstream wire format on streaming operations; **guardrails enforce their deterministic policies** — word policy, sensitive-information regexes, and the pattern-matchable PII types with `BLOCK`/`ANONYMIZE` per input/output stage — on `ApplyGuardrail` and on `Converse`/`ConverseStream` via `guardrailConfig` (`GUARDRAIL_INTERVENED`, blocked messaging, per-policy assessments, `ResourceNotFoundException` for an unknown id); the model-graded policies (topic, content, contextual grounding, `PROFANITY`) are not evaluated; deterministic family-aware mock responses selected by model ID prefix (`anthropic.*`, `amazon.titan*`, `amazon.nova*`, `meta.llama*`, `mistral.*`, `cohere.*`, `ai21.*`); verified against botocore `bedrock-runtime-2023-09-30` |
| **Bedrock Agent** | 72 operations — agents (versions, aliases, action groups, collaborators, agent knowledge bases, PrepareAgent), knowledge bases (data sources, ingestion jobs — `StartIngestionJob` reads the S3 data source and reports real statistics, `FAILED` with `failureReasons` when the source is unreadable — documents), flows (aliases, versions, ValidateFlowDefinition, PrepareFlow), prompts with versions, tagging | All 72 operations verified against botocore `bedrock-agent-2023-06-05` |
| **Bedrock Agent Runtime** | InvokeAgent, InvokeInlineAgent, GetAgentMemory, DeleteAgentMemory, Retrieve, RetrieveAndGenerate, RetrieveAndGenerateStream, Rerank, CreateSession, GetSession, UpdateSession, DeleteSession, EndSession, ListSessions, CreateInvocation, ListInvocations, PutInvocationStep, GetInvocationStep, ListInvocationSteps, InvokeFlow, StartFlowExecution, StopFlowExecution, GetFlowExecution, ListFlowExecutions, ListFlowExecutionEvents, GetExecutionFlowSnapshot, OptimizePrompt | All 31 operations verified against botocore `bedrock-agent-runtime-2023-07-26`; eventstream responses on streaming operations; `Retrieve` searches the documents Knowledge Base ingestion stored (lexical scoring — no embeddings) and returns content, `s3Location` and score; `InvokeAgent` answers a canned reply without orchestration and emits no trace events — it never fabricates an `ORCHESTRATE` trace |
-| **Bedrock AgentCore** | Control plane (`bedrock-agentcore-control`): CreateAgentRuntime, GetAgentRuntime, ListAgentRuntimes, UpdateAgentRuntime, DeleteAgentRuntime, ListAgentRuntimeVersions, CreateAgentRuntimeEndpoint, GetAgentRuntimeEndpoint, ListAgentRuntimeEndpoints, UpdateAgentRuntimeEndpoint, DeleteAgentRuntimeEndpoint. Data plane (`bedrock-agentcore`): InvokeAgentRuntime | Agent-runtime lifecycle with `CREATING`/`UPDATING`→`READY` transitions, versioned ARNs (`agent/{uuid}:{version}`, `agentEndpoint/{uuid}`); request/response shapes verified against botocore `bedrock-agentcore-control` / `bedrock-agentcore`; account- and region-scoped state; `InvokeAgentRuntime` runs the runtime's `containerUri` image in Docker (full image), waits for `/ping` and forwards to `/invocations` on port 8080, with container errors as `RuntimeClientError` (424); without Docker (slim image) or for a code artifact it answers a deterministic echo |
+| **Bedrock AgentCore** | Control plane (`bedrock-agentcore-control`): CreateAgentRuntime, GetAgentRuntime, ListAgentRuntimes, UpdateAgentRuntime, DeleteAgentRuntime, ListAgentRuntimeVersions, CreateAgentRuntimeEndpoint, GetAgentRuntimeEndpoint, ListAgentRuntimeEndpoints, UpdateAgentRuntimeEndpoint, DeleteAgentRuntimeEndpoint, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy. Data plane (`bedrock-agentcore`): InvokeAgentRuntime | Agent-runtime lifecycle with `CREATING`/`UPDATING`→`READY` transitions, versioned ARNs (`agent/{uuid}:{version}`, `agentEndpoint/{uuid}`); request/response shapes verified against botocore `bedrock-agentcore-control` / `bedrock-agentcore`; account- and region-scoped state; resource policies are evaluated for runtime and endpoint invocation when `AUTH=true`; `InvokeAgentRuntime` runs the runtime's `containerUri` image in Docker (full image), waits for `/ping` and forwards to `/invocations` on port 8080, with container errors as `RuntimeClientError` (424); without Docker (slim image) or for a code artifact it answers a deterministic echo |
| **Transcribe** | StartTranscriptionJob, GetTranscriptionJob, ListTranscriptionJobs, DeleteTranscriptionJob | Batch transcription jobs only; streaming is a separate endpoint (`transcribestreaming`). All four operations verified against botocore `transcribe-2017-10-26`. A job starts `IN_PROGRESS` with `StartTime` set, as on AWS, and reaches `COMPLETED` over two seconds; `QUEUED`, which AWS reaches only for a request that opted into job queueing (`JobExecutionSettings.AllowDeferredExecution`) while the account is at its concurrent job limit, is not modelled; the media object is read from MiniStack S3 via an `s3://`, path-style or virtual-hosted HTTPS URI, and an unreadable URI fails the job with a `FailureReason` rather than erroring at `Start`, as on AWS; the transcript is written back to S3 in the real result format (`results.transcripts`, word-level `results.items`, `results.audio_segments`, plus `results.segments` and `results.speaker_labels` when the matching `Settings` are set) at `OutputBucketName`/`OutputKey`, or to an auto-created `ministack-transcribe-output` bucket. `IdentifyLanguage` and `IdentifyMultipleLanguages` resolve a language on completion, `ContentRedaction` controls whether a `redacted-` copy replaces or accompanies the transcript, and `Subtitles` writes WebVTT and SubRip files, redacted alongside the transcript when redaction is on. Reaching a terminal state publishes a `Transcribe Job State Change` event, so EventBridge rules downstream of a job fire. There is no speech recognition, so the transcript is deterministic canned text keyed on a digest of the media URI |
| **Translate** | StartTextTranslationJob, DescribeTextTranslationJob, ListTextTranslationJobs, StopTextTranslationJob | Batch text translation jobs only; the synchronous `TranslateText` / `TranslateDocument` pair and the custom terminology / parallel data families are not implemented. All four operations verified against botocore `translate-2017-07-01`. Jobs walk `SUBMITTED` → `IN_PROGRESS` → `COMPLETED` over `TRANSLATE_JOB_RUN_SECONDS` (default 2, `0` completes immediately); every document under `InputDataConfig.S3Uri` is read from MiniStack S3 and written back to the rewritten output location AWS uses — `OutputDataConfig.S3Uri` is reported as `s3://<bucket>/<prefix><account-id>-TranslateText-<JobId>/` — as `<target-code>.<input name>`, with a `details/<code>.auxiliary-translation-details.json` summary per target language. `text/plain` is translated line by line, `text/html` keeps its markup and translates only text nodes, `application/x-xliff+xml` gets a populated `<target>` in every `<trans-unit>` plus `target-language` on every `<file>`, and the three Office ZIP types are copied through. A document that can't be read as its content type is counted in `JobDetails` and the job ends `COMPLETED_WITH_ERROR`; an empty or unreadable input location fails the job with a `Message` rather than erroring at `Start`. `ClientToken` is idempotent, `StopTextTranslationJob` reaches a running worker, and reaching a terminal state publishes a `Translate TextTranslationJob State Change` event, so EventBridge rules downstream of a job fire. There is no machine translation, so the output is deterministic canned text derived from the source |
| **MSK** | CreateCluster, ListClusters, DescribeCluster, DeleteCluster, GetBootstrapBrokers, ListNodes, CreateConfiguration, ListConfigurations, DescribeConfiguration, ListConfigurationRevisions, DescribeConfigurationRevision, BatchAssociateScramSecret, BatchDisassociateScramSecret, ListScramSecrets, TagResource, UntagResource, ListTagsForResource | Kafka control plane; `GetBootstrapBrokers` honors `MINISTACK_MSK_BOOTSTRAP` so clients route to a real broker you bring (Redpanda, Kafka, KRaft) — the Kafka wire protocol itself is not emulated |
diff --git a/ministack/app.py b/ministack/app.py
index 41893cdc..7b3d7696 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -2412,9 +2412,10 @@ async def _dispatch_service_request(
extract_iam_action,
extract_resource_arn,
)
- from ministack.core.iam_evaluator import AuthError, enforce
+ from ministack.core.iam_evaluator import AuthError, enforce, pin_request_caller
from ministack.core.responses import get_account_id
+ pin_request_caller(headers, query_params)
iam_action = extract_iam_action(service, method, path, headers, body, routing_params)
if iam_action is not None:
access_key = extract_access_key_id(headers, query_params)
@@ -2462,6 +2463,18 @@ async def _dispatch_service_request(
)
if denied:
break
+ if (
+ denied
+ and service == "bedrock-agentcore"
+ and iam_action == "bedrock-agentcore:InvokeAgentRuntime"
+ and not isinstance(denied, AuthError)
+ ):
+ from ministack.services import bedrock_agentcore
+
+ if bedrock_agentcore.resource_policy_allows_without_identity(
+ path, query_params
+ ):
+ denied = None
if denied:
if isinstance(denied, AuthError):
return access_denied_response(
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index d9f434da..ec025456 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -456,9 +456,11 @@ _BOTOCORE_SERVICE_MAP: dict[str, list[str]] = {
"bedrock-runtime": ["bedrock-runtime"],
"bedrock-agent": ["bedrock-agent"],
"bedrock-agent-runtime": ["bedrock-agent-runtime"],
- # InvokeAgentRuntime is mapped explicitly below so AUTH works even with
- # Botocore versions that predate the AgentCore service model.
- "bedrock-agentcore": [],
+ # Both the control and data-plane clients sign with the same
+ # ``bedrock-agentcore`` name. The control model supplies the REST routes
+ # for resource-policy CRUD; InvokeAgentRuntime remains explicit below so
+ # older Botocore installations still authorize it.
+ "bedrock-agentcore": ["bedrock-agentcore-control"],
"cloudfront": ["cloudfront"],
"cloudfront-keyvaluestore": ["cloudfront-keyvaluestore"],
"dsql": ["dsql"],
@@ -699,6 +701,21 @@ def extract_iam_action(service: str, method: str, path: str,
if _agentcore_runtime_arn(path):
return "bedrock-agentcore:InvokeAgentRuntime"
+ if service == "bedrock-agentcore" and path.startswith("/resourcepolicy/"):
+ policy_action = {
+ "PUT": "PutResourcePolicy",
+ "GET": "GetResourcePolicy",
+ "DELETE": "DeleteResourcePolicy",
+ }.get(method)
+ if policy_action:
+ return f"bedrock-agentcore:{policy_action}"
+
+ # The control-plane model also declares ``GET /runtimes/{id}``. Its
+ # permissive ARN route would otherwise misclassify an invalid GET against
+ # the data-plane invocation path as GetAgentRuntime.
+ if service == "bedrock-agentcore" and "/invocations" in unquote(path):
+ return None
+
# Tier 4: Generic botocore route matcher (all other REST services)
action_name = _match_rest_action(service, method, path, query_params)
if action_name:
@@ -859,6 +876,9 @@ def extract_resource_arn(service: str, method: str, path: str,
return resources[0]
return "*"
+ if service == "bedrock-agentcore" and path.startswith("/resourcepolicy/"):
+ return unquote(path[len("/resourcepolicy/"):]) or "*"
+
if service == "bedrock-agentcore" and method == "POST":
return _agentcore_runtime_arn(path) or "*"
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index a5a16e93..c4836105 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -1279,6 +1279,16 @@ def _principal_matches(principal: Any, caller_arn: str) -> bool:
continue
if fnmatch_iam(caller_arn, p):
return True
+ # A resource policy names an IAM role ARN, while a request made
+ # after AssumeRole carries the matching STS assumed-role ARN.
+ # AWS treats those as the same principal for resource policies.
+ if ":role/" in p and ":assumed-role/" in caller_arn:
+ principal_account = p.split(":")[4]
+ caller_account = caller_arn.split(":")[4]
+ role_name = p.rsplit("/", 1)[-1]
+ assumed_role = caller_arn.split(":assumed-role/", 1)[1].split("/", 1)[0]
+ if principal_account == caller_account and role_name == assumed_role:
+ return True
# Also match account root against any principal in that account
if p.endswith(":root") and f":{p.split(':')[4]}:" in caller_arn:
return True
diff --git a/ministack/services/bedrock_agentcore.py b/ministack/services/bedrock_agentcore.py
index 3f0d6516..50172fcf 100644
--- a/ministack/services/bedrock_agentcore.py
+++ b/ministack/services/bedrock_agentcore.py
@@ -9,13 +9,14 @@ Covers the two AgentCore services, which both sign as ``bedrock-agentcore``:
UpdateAgentRuntime, DeleteAgentRuntime, ListAgentRuntimeVersions,
CreateAgentRuntimeEndpoint, GetAgentRuntimeEndpoint,
ListAgentRuntimeEndpoints, UpdateAgentRuntimeEndpoint,
- DeleteAgentRuntimeEndpoint.
+ DeleteAgentRuntimeEndpoint, PutResourcePolicy, GetResourcePolicy,
+ DeleteResourcePolicy.
* ``bedrock-agentcore`` (rest-json) — data plane: InvokeAgentRuntime.
Deterministic and stateful: resources provision instantly (``READY``) and
InvokeAgentRuntime returns a deterministic echo response, so teams can test
-runtime lifecycle, endpoint wiring, and Invoke request/response contracts
-locally without live AWS.
+runtime lifecycle, endpoint wiring, resource-policy authorization, and Invoke
+request/response contracts locally without live AWS.
Shapes, HTTP methods, URIs, ARN/ID patterns, and status enums are verified
against botocore ``bedrock-agentcore-control`` / ``bedrock-agentcore``
@@ -45,6 +46,7 @@ from ministack.core.responses import (
json_response,
new_uuid,
now_iso,
+ request_scope,
)
logger = logging.getLogger("bedrock_agentcore")
@@ -55,6 +57,7 @@ logger = logging.getLogger("bedrock_agentcore")
_runtimes = AccountRegionScopedDict() # agentRuntimeId -> runtime record
_endpoints = AccountRegionScopedDict() # agentRuntimeId -> {endpointName -> endpoint record}
+_resource_policies = AccountRegionScopedDict() # resource ARN -> policy string
_containers = {} # (account, region, runtime id) -> Docker container
_container_lock = threading.RLock()
@@ -64,7 +67,11 @@ _NAME_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]{0,47}$")
def get_state():
- return copy.deepcopy({"runtimes": _runtimes, "endpoints": _endpoints})
+ return copy.deepcopy({
+ "runtimes": _runtimes,
+ "endpoints": _endpoints,
+ "resourcePolicies": _resource_policies,
+ })
def load_persisted_state(data):
@@ -76,8 +83,10 @@ def _restore_state(data):
return
_runtimes.clear()
_endpoints.clear()
+ _resource_policies.clear()
_runtimes.update(data.get("runtimes", {}))
_endpoints.update(data.get("endpoints", {}))
+ _resource_policies.update(data.get("resourcePolicies", {}))
@@ -89,6 +98,7 @@ def reset():
_containers.clear()
_runtimes.clear()
_endpoints.clear()
+ _resource_policies.clear()
# ---------------------------------------------------------------------------
@@ -115,6 +125,100 @@ def _endpoint_arn(endpoint_uuid: str) -> str:
f"agentEndpoint/{endpoint_uuid}")
+def _arn_owner(resource_arn: str) -> tuple[str, str] | None:
+ """Return the account and region encoded in an ARN."""
+ parts = resource_arn.split(":")
+ if len(parts) < 6 or parts[0] != "arn" or not parts[3] or not parts[4]:
+ return None
+ return parts[4], parts[3]
+
+
+def _resource_exists(resource_arn: str, account_id: str, region: str) -> bool:
+ """Whether a Runtime or Endpoint with this exact ARN exists."""
+ if any(r.get("agentRuntimeArn") == resource_arn
+ for r in _runtimes.values_scoped(account_id, region)):
+ return True
+ for endpoints in _endpoints.values_scoped(account_id, region):
+ if any(e.get("agentRuntimeEndpointArn") == resource_arn
+ for e in endpoints.values()):
+ return True
+ return False
+
+
+def _policy_validation(resource_arn: str, policy: str) -> str | None:
+ """Validate AgentCore's resource-policy-specific constraints."""
+ from ministack.core.iam_evaluator import validate_policy_document
+
+ if len(policy) > 20_480:
+ return "policy exceeds the maximum length of 20480 characters"
+ error = validate_policy_document(policy)
+ if error:
+ return error
+ try:
+ document = json.loads(policy)
+ except json.JSONDecodeError:
+ return "Policy document is not valid JSON"
+ statements = document.get("Statement", [])
+ if isinstance(statements, dict):
+ statements = [statements]
+ for index, statement in enumerate(statements):
+ if "Principal" not in statement:
+ return f"Statement {index} must contain a Principal element"
+ if "NotPrincipal" in statement:
+ return "NotPrincipal is not supported by MiniStack AgentCore policies"
+ resources = statement.get("Resource")
+ if isinstance(resources, str):
+ resources = [resources]
+ if not isinstance(resources, list) or resources != [resource_arn]:
+ return (
+ f"Statement {index} Resource must contain exactly "
+ f"{resource_arn}"
+ )
+ return None
+
+
+def _put_resource_policy(resource_arn: str, body):
+ data = _parse_body(body)
+ policy = data.get("policy")
+ owner = _arn_owner(resource_arn)
+ if not isinstance(policy, str) or not policy:
+ return _validation("policy is required")
+ if owner is None:
+ return _validation("resourceArn must be a valid ARN")
+ account_id, region = owner
+ if not _resource_exists(resource_arn, account_id, region):
+ return _not_found(f"Resource {resource_arn} not found")
+ error = _policy_validation(resource_arn, policy)
+ if error:
+ return _validation(error)
+ _resource_policies.set_scoped(account_id, region, resource_arn, policy)
+ return json_response({"policy": policy}, status=201)
+
+
+def _get_resource_policy(resource_arn: str):
+ owner = _arn_owner(resource_arn)
+ if owner is None:
+ return _validation("resourceArn must be a valid ARN")
+ if not _resource_exists(resource_arn, *owner):
+ return _not_found(f"Resource {resource_arn} not found")
+ policy = _resource_policies.get_scoped(*owner, resource_arn)
+ if policy is None:
+ return _not_found(f"Resource policy for {resource_arn} not found")
+ return json_response({"policy": policy})
+
+
+def _delete_resource_policy(resource_arn: str):
+ owner = _arn_owner(resource_arn)
+ if owner is None:
+ return _validation("resourceArn must be a valid ARN")
+ if not _resource_exists(resource_arn, *owner):
+ return _not_found(f"Resource {resource_arn} not found")
+ deleted = _resource_policies.pop_scoped(*owner, resource_arn, None)
+ if deleted is None:
+ return _not_found(f"Resource policy for {resource_arn} not found")
+ return 204, {"Content-Type": "application/json"}, b""
+
+
def _workload_identity_arn(name: str) -> str:
return (f"arn:aws:bedrock-agentcore:{get_region()}:{get_account_id()}:"
f"workload-identity-directory/default/workload-identity/{name}")
@@ -255,10 +359,12 @@ def _update_agent_runtime(runtime_id, body):
if not data.get(field):
return _validation(f"{field} is required")
_stop_container(runtime_id)
+ old_arn = record["agentRuntimeArn"]
now = now_iso()
new_version = str(int(record["agentRuntimeVersion"]) + 1)
record["agentRuntimeVersion"] = new_version
record["agentRuntimeArn"] = _runtime_arn(record["_uuid"], new_version)
+ _resource_policies.pop(old_arn, None)
record["lastUpdatedAt"] = now
record["status"] = "READY"
for field in ("agentRuntimeArtifact", "roleArn", "networkConfiguration"):
@@ -285,6 +391,9 @@ def _delete_agent_runtime(runtime_id):
if record is None:
return _not_found(f"Agent runtime {runtime_id} not found")
_stop_container(runtime_id)
+ _resource_policies.pop(record["agentRuntimeArn"], None)
+ for endpoint in (_endpoints.get(runtime_id) or {}).values():
+ _resource_policies.pop(endpoint.get("agentRuntimeEndpointArn"), None)
_runtimes.pop(runtime_id, None)
_endpoints.pop(runtime_id, None)
return json_response({"status": "DELETING", "agentRuntimeId": runtime_id})
@@ -402,7 +511,9 @@ def _delete_agent_runtime_endpoint(runtime_id, endpoint_name):
endpoints = _endpoints.get(runtime_id) or {}
if endpoint_name not in endpoints:
return _not_found(f"Endpoint {endpoint_name} not found")
- endpoints.pop(endpoint_name, None)
+ endpoint = endpoints.pop(endpoint_name, None)
+ if endpoint:
+ _resource_policies.pop(endpoint.get("agentRuntimeEndpointArn"), None)
return json_response({
"status": "DELETING",
"agentRuntimeId": runtime_id,
@@ -414,15 +525,179 @@ def _delete_agent_runtime_endpoint(runtime_id, endpoint_name):
# Data plane — InvokeAgentRuntime
# ---------------------------------------------------------------------------
-def _invoke_agent_runtime(runtime_arn, headers, body):
- # The runtime is addressed by ARN; resolve it in this account+region.
- runtime = next((r for r in _runtimes.values()
- if r["agentRuntimeArn"] == runtime_arn
- or r["agentRuntimeArn"].rsplit(":", 1)[0] == runtime_arn.rsplit(":", 1)[0]),
- None)
+def _find_runtime(runtime_arn):
+ """Resolve a runtime by the owner account encoded in its ARN."""
+ owner = _arn_owner(runtime_arn)
+ if owner is None:
+ return None, None, None
+ account_id, region = owner
+ runtime = next(
+ (
+ record
+ for record in _runtimes.values_scoped(account_id, region)
+ if record["agentRuntimeArn"] == runtime_arn
+ or record["agentRuntimeArn"].rsplit(":", 1)[0]
+ == runtime_arn.rsplit(":", 1)[0]
+ ),
+ None,
+ )
+ return runtime, account_id, region
+
+
+def _endpoint_for_qualifier(runtime, account_id, region, qualifier):
+ if not qualifier:
+ return None
+ endpoints = _endpoints.get_scoped(account_id, region, runtime["agentRuntimeId"], {})
+ return endpoints.get(qualifier)
+
+
+def _principal_context(action, resource_arn, region):
+ from ministack.core.iam_evaluator import caller_arn
+
+ principal = caller_arn()
+ parts = principal.split(":")
+ account_id = parts[4] if len(parts) > 4 else get_account_id()
+ if ":assumed-role/" in principal:
+ principal_type = "AssumedRole"
+ elif ":user/" in principal:
+ principal_type = "User"
+ else:
+ principal_type = "Root"
+ from ministack.core.iam_evaluator import EvalContext
+
+ return EvalContext(
+ principal_arn=principal,
+ principal_type=principal_type,
+ principal_account=account_id,
+ action=action,
+ resource_arn=resource_arn,
+ region=region,
+ )
+
+
+def _resource_policy_decision(resource_arn, account_id, region, action):
+ from ministack.core.iam_evaluator import evaluate_resource_policy
+
+ policy = _resource_policies.get_scoped(account_id, region, resource_arn)
+ if policy is None:
+ return None
+ return evaluate_resource_policy(
+ policy, _principal_context(action, resource_arn, region)
+ )
+
+
+def _resource_policy_allows_invocation(
+ runtime, account_id, region, qualifier, headers, query_params
+):
+ from ministack.core.iam_evaluator import resource_policy_allows
+
+ action = "bedrock-agentcore:InvokeAgentRuntime"
+ runtime_arn = runtime["agentRuntimeArn"]
+ principal = _principal_context(action, runtime_arn, region)
+ same_account = principal.principal_account == account_id
+ runtime_policy = _resource_policies.get_scoped(account_id, region, runtime_arn)
+ if not resource_policy_allows(runtime_policy, principal, same_account):
+ return False
+
+ # A named endpoint is an additional policy resource. AWS requires both the
+ # runtime and endpoint policies for cross-account invocation.
+ endpoint = _endpoint_for_qualifier(runtime, account_id, region, qualifier)
+ if qualifier and endpoint is None:
+ return False
+ if not same_account and endpoint is None:
+ return False
+ if endpoint is not None:
+ endpoint_arn = endpoint["agentRuntimeEndpointArn"]
+ endpoint_policy = _resource_policies.get_scoped(
+ account_id, region, endpoint_arn
+ )
+ endpoint_context = _principal_context(action, endpoint_arn, region)
+ if not resource_policy_allows(
+ endpoint_policy, endpoint_context, same_account
+ ):
+ return False
+ if not same_account:
+ from ministack.core.iam_evaluator import enforce
+ from ministack.core.router import extract_access_key_id
+
+ identity_result = enforce(
+ extract_access_key_id(headers, query_params or {}),
+ action,
+ "bedrock-agentcore",
+ region,
+ resource_arn=endpoint_arn,
+ )
+ if identity_result is not None:
+ return False
+ return True
+
+
+def resource_policy_allows_without_identity(path, query_params):
+ """Return whether a same-account resource policy can replace an identity Allow."""
+ from ministack.app import AUTH
+ if not AUTH:
+ return False
+ inner = path.strip("/")
+ if not (inner.startswith("runtimes/") and inner.endswith("/invocations")):
+ return False
+ runtime_arn = unquote(inner[len("runtimes/"):-len("/invocations")])
+ runtime, account_id, region = _find_runtime(runtime_arn)
+ if runtime is None:
+ return False
+ principal = _principal_context(
+ "bedrock-agentcore:InvokeAgentRuntime", runtime_arn, region
+ )
+ if principal.principal_account != account_id:
+ return False
+ runtime_decision = _resource_policy_decision(
+ runtime_arn, account_id, region, "bedrock-agentcore:InvokeAgentRuntime"
+ )
+ if runtime_decision is None or runtime_decision.decision != "Allow":
+ return False
+ qualifier = query_params.get("qualifier") if query_params else None
+ if isinstance(qualifier, list):
+ qualifier = qualifier[0] if qualifier else None
+ endpoint = _endpoint_for_qualifier(runtime, account_id, region, qualifier)
+ if endpoint is None:
+ return True
+ endpoint_decision = _resource_policy_decision(
+ endpoint["agentRuntimeEndpointArn"], account_id, region,
+ "bedrock-agentcore:InvokeAgentRuntime",
+ )
+ return endpoint_decision is not None and endpoint_decision.decision == "Allow"
+
+
+def _invoke_agent_runtime(runtime_arn, headers, body, query_params=None):
+ runtime, owner_account, owner_region = _find_runtime(runtime_arn)
if runtime is None:
return _not_found(f"Agent runtime {runtime_arn} not found")
+ qualifier = query_params.get("qualifier") if query_params else None
+ if isinstance(qualifier, list):
+ qualifier = qualifier[0] if qualifier else None
+ endpoint = _endpoint_for_qualifier(runtime, owner_account, owner_region, qualifier)
+ if qualifier and endpoint is None:
+ return _not_found(f"Agent runtime endpoint {qualifier} not found")
+
+ from ministack.app import AUTH
+ from ministack.core.iam_evaluator import pin_request_caller
+ pin_request_caller(headers, query_params or {})
+ if AUTH and not _resource_policy_allows_invocation(
+ runtime, owner_account, owner_region, qualifier, headers, query_params
+ ):
+ return error_response_json(
+ "AccessDeniedException",
+ f"User: {get_account_id()} is not authorized to perform: "
+ f"bedrock-agentcore:InvokeAgentRuntime on resource: {runtime_arn}",
+ 403,
+ )
+
+ with request_scope(owner_account, owner_region):
+ return _invoke_agent_runtime_in_owner(runtime, headers, body)
+
+
+def _invoke_agent_runtime_in_owner(runtime, headers, body):
+
session_id = (headers.get("x-amzn-bedrock-agentcore-runtime-session-id")
or new_uuid())
content_type = headers.get("content-type", "application/json")
@@ -651,13 +926,27 @@ def _invoke_container(url, body, headers, content_type, session_id):
async def handle_request(method, path, headers, body, query_params):
inner = path.strip("/")
+ if inner.startswith("resourcepolicy/"):
+ resource_arn = unquote(inner[len("resourcepolicy/"):])
+ if method == "PUT":
+ return _put_resource_policy(resource_arn, body)
+ if method == "GET":
+ return _get_resource_policy(resource_arn)
+ if method == "DELETE":
+ return _delete_resource_policy(resource_arn)
+ return error_response_json(
+ "InvalidAction", f"Unsupported AgentCore request: {method} {path}", 400
+ )
+
# InvokeAgentRuntime: POST /runtimes/{agentRuntimeArn}/invocations. The ARN
# is a single path label but carries literal '/' and ':' (agent/{uuid}:{ver}),
# so match the suffix before splitting on '/'.
if (method == "POST" and inner.startswith("runtimes/")
and inner.endswith("/invocations")):
arn = inner[len("runtimes/"):-len("/invocations")]
- return await asyncio.to_thread(_invoke_agent_runtime, unquote(arn), headers, body)
+ return await asyncio.to_thread(
+ _invoke_agent_runtime, unquote(arn), headers, body, query_params
+ )
parts = [p for p in inner.split("/") if p]
# All remaining AgentCore paths are rooted at /runtimes.
@@ -682,7 +971,9 @@ async def handle_request(method, path, headers, body, query_params):
elif n == 3:
seg = parts[2]
if seg == "invocations" and method == "POST":
- return await asyncio.to_thread(_invoke_agent_runtime, unquote(parts[1]), headers, body)
+ return await asyncio.to_thread(
+ _invoke_agent_runtime, unquote(parts[1]), headers, body, query_params
+ )
runtime_id = unquote(parts[1])
if seg == "versions" and method == "POST":
return _list_agent_runtime_versions(runtime_id, body)
diff --git a/tests/test_bedrock_agentcore.py b/tests/test_bedrock_agentcore.py
index 6c0c3eb1..38a5fae3 100644
--- a/tests/test_bedrock_agentcore.py
+++ b/tests/test_bedrock_agentcore.py
@@ -27,13 +27,14 @@ ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
_ARTIFACT = {"containerConfiguration": {"containerUri": "0.dkr.ecr.us-east-1.amazonaws.com/agent:latest"}}
_ROLE = "arn:aws:iam::000000000000:role/agentcore"
_NET = {"networkMode": "PUBLIC"}
+_AUTH_ENABLED = os.environ.get("AUTH", "").lower() == "true"
-def _client(service, region="us-east-1"):
+def _client(service, region="us-east-1", access_key="test"):
return boto3.client(
service,
endpoint_url=ENDPOINT,
- aws_access_key_id="test",
+ aws_access_key_id=access_key,
aws_secret_access_key="test",
region_name=region,
config=Config(region_name=region, retries={"mode": "standard"}),
@@ -145,6 +146,198 @@ def test_agentcore_invoke_returns_deterministic_echo():
ctl.delete_agent_runtime(agentRuntimeId=rid_resp["agentRuntimeId"])
+ not _AUTH_ENABLED,
+ reason="resource-policy authorization requires a MiniStack server with AUTH=true",
+)
+def test_agentcore_resource_policy_cross_account_requires_runtime_and_endpoint():
+ owner = "111111111111"
+ caller = "222222222222"
+ ctl = _client("bedrock-agentcore-control", access_key=owner)
+ caller_iam = _client("iam", access_key=caller)
+ caller_sts = _client("sts", access_key=caller)
+ created = _create(ctl, f"policy_{_uuid_mod.uuid4().hex[:8]}", _CODE_ARTIFACT)
+ runtime_arn = created["agentRuntimeArn"]
+ runtime_id = created["agentRuntimeId"]
+ role_name = f"worker_{_uuid_mod.uuid4().hex[:8]}"
+ role_arn = f"arn:aws:iam::{caller}:role/{role_name}"
+ worker_rt = None
+ try:
+ endpoint = ctl.create_agent_runtime_endpoint(
+ agentRuntimeId=runtime_id, name="prod"
+ )
+ endpoint_arn = endpoint["agentRuntimeEndpointArn"]
+
+ caller_iam.create_role(
+ RoleName=role_name,
+ AssumeRolePolicyDocument=json.dumps({
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Allow",
+ "Principal": {"AWS": f"arn:aws:iam::{caller}:root"},
+ "Action": "sts:AssumeRole",
+ }],
+ }),
+ )
+
+ def identity_policy(resources):
+ return json.dumps({
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Allow",
+ "Action": "bedrock-agentcore:InvokeAgentRuntime",
+ "Resource": resources,
+ }],
+ })
+
+ caller_iam.put_role_policy(
+ RoleName=role_name,
+ PolicyName="invoke-runtime",
+ PolicyDocument=identity_policy([runtime_arn, endpoint_arn]),
+ )
+ credentials = caller_sts.assume_role(
+ RoleArn=role_arn, RoleSessionName="investigator"
+ )["Credentials"]
+ worker_rt = boto3.client(
+ "bedrock-agentcore",
+ endpoint_url=ENDPOINT,
+ aws_access_key_id=credentials["AccessKeyId"],
+ aws_secret_access_key=credentials["SecretAccessKey"],
+ aws_session_token=credentials["SessionToken"],
+ region_name="us-east-1",
+ config=Config(region_name="us-east-1", retries={"mode": "standard"}),
+ )
+
+ def policy(resource):
+ return json.dumps({
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Allow",
+ "Principal": {"AWS": role_arn},
+ "Action": "bedrock-agentcore:InvokeAgentRuntime",
+ "Resource": resource,
+ }],
+ })
+
+ assert ctl.put_resource_policy(
+ resourceArn=runtime_arn, policy=policy(runtime_arn)
+ )["policy"] == policy(runtime_arn)
+ ctl.put_resource_policy(
+ resourceArn=endpoint_arn, policy=policy(endpoint_arn)
+ )
+
+ response = worker_rt.invoke_agent_runtime(
+ agentRuntimeArn=runtime_arn,
+ qualifier="prod",
+ payload=b"{}",
+ )
+ assert json.loads(response["response"].read())["agentRuntimeArn"] == runtime_arn
+
+ ctl.delete_resource_policy(resourceArn=endpoint_arn)
+ with pytest.raises(ClientError) as exc:
+ worker_rt.invoke_agent_runtime(
+ agentRuntimeArn=runtime_arn, qualifier="prod", payload=b"{}"
+ )
+ assert exc.value.response["Error"]["Code"] == "AccessDeniedException"
+
+ ctl.put_resource_policy(
+ resourceArn=endpoint_arn, policy=policy(endpoint_arn)
+ )
+ caller_iam.put_role_policy(
+ RoleName=role_name,
+ PolicyName="invoke-runtime",
+ PolicyDocument=identity_policy([runtime_arn]),
+ )
+ with pytest.raises(ClientError) as exc:
+ worker_rt.invoke_agent_runtime(
+ agentRuntimeArn=runtime_arn, qualifier="prod", payload=b"{}"
+ )
+ assert exc.value.response["Error"]["Code"] == "AccessDeniedException"
+ caller_iam.put_role_policy(
+ RoleName=role_name,
+ PolicyName="invoke-runtime",
+ PolicyDocument=identity_policy([runtime_arn, endpoint_arn]),
+ )
+ assert ctl.get_resource_policy(resourceArn=runtime_arn)["policy"]
+ ctl.delete_resource_policy(resourceArn=runtime_arn)
+ with pytest.raises(ClientError) as exc:
+ worker_rt.invoke_agent_runtime(
+ agentRuntimeArn=runtime_arn, qualifier="prod", payload=b"{}"
+ )
+ assert exc.value.response["Error"]["Code"] == "AccessDeniedException"
+ finally:
+ for resource_arn in (
+ locals().get("endpoint_arn"),
+ locals().get("runtime_arn"),
+ ):
+ if resource_arn:
+ try:
+ ctl.delete_resource_policy(resourceArn=resource_arn)
+ except ClientError:
+ pass
+ try:
+ caller_iam.delete_role_policy(
+ RoleName=role_name, PolicyName="invoke-runtime"
+ )
+ caller_iam.delete_role(RoleName=role_name)
+ except ClientError:
+ pass
+ ctl.delete_agent_runtime(agentRuntimeId=runtime_id)
+
+
+ not _AUTH_ENABLED,
+ reason="resource-policy authorization requires a MiniStack server with AUTH=true",
+)
+def test_agentcore_resource_policy_rejects_wildcard_resource():
+ ctl = _client("bedrock-agentcore-control")
+ created = _create(ctl, f"invalid_policy_{_uuid_mod.uuid4().hex[:8]}", _CODE_ARTIFACT)
+ runtime_arn = created["agentRuntimeArn"]
+ try:
+ policy = json.dumps({
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Allow",
+ "Principal": "*",
+ "Action": "bedrock-agentcore:InvokeAgentRuntime",
+ "Resource": "*",
+ }],
+ })
+ with pytest.raises(ClientError) as exc:
+ ctl.put_resource_policy(resourceArn=runtime_arn, policy=policy)
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+ finally:
+ ctl.delete_agent_runtime(agentRuntimeId=created["agentRuntimeId"])
+
+
+ not _AUTH_ENABLED,
+ reason="resource-policy authorization requires a MiniStack server with AUTH=true",
+)
+def test_agentcore_resource_policy_explicit_deny_overrides_identity_allow():
+ ctl = _client("bedrock-agentcore-control")
+ rt = _client("bedrock-agentcore")
+ created = _create(ctl, f"deny_policy_{_uuid_mod.uuid4().hex[:8]}", _CODE_ARTIFACT)
+ runtime_arn = created["agentRuntimeArn"]
+ policy = json.dumps({
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Deny",
+ "Principal": "*",
+ "Action": "bedrock-agentcore:InvokeAgentRuntime",
+ "Resource": runtime_arn,
+ }],
+ })
+ try:
+ ctl.put_resource_policy(resourceArn=runtime_arn, policy=policy)
+ with pytest.raises(ClientError) as exc:
+ rt.invoke_agent_runtime(agentRuntimeArn=runtime_arn, payload=b"{}")
+ assert exc.value.response["Error"]["Code"] == "AccessDeniedException"
+ finally:
+ ctl.delete_resource_policy(resourceArn=runtime_arn)
+ ctl.delete_agent_runtime(agentRuntimeId=created["agentRuntimeId"])
+
+
def test_agentcore_runtimes_are_region_scoped():
east = _client("bedrock-agentcore-control", "us-east-1")
west = _client("bedrock-agentcore-control", "us-west-2")
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 025545d5..bf66a9ea 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -2187,6 +2187,28 @@ class TestActionExtraction:
service, "POST", "/runtimes//invocations", headers, b"{}", {}
) is None
+ def test_agentcore_resource_policy_routes_use_control_plane_actions(self):
+ from ministack.core.iam_actions import extract_iam_action, extract_resource_arn
+
+ headers = _sigv4_headers(
+ "bedrock-agentcore", "bedrock-agentcore.us-east-1.amazonaws.com"
+ )
+ resource = "arn:aws:bedrock-agentcore:us-east-1:000000000000:runtime/rt-example"
+ path = "/resourcepolicy/" + resource.replace(":", "%3A").replace("/", "%2F")
+ assert extract_iam_action("bedrock-agentcore", "PUT", path, headers, b"{}", {}) == (
+ "bedrock-agentcore:PutResourcePolicy"
+ )
+ assert extract_iam_action("bedrock-agentcore", "GET", path, headers, b"", {}) == (
+ "bedrock-agentcore:GetResourcePolicy"
+ )
+ assert extract_iam_action("bedrock-agentcore", "DELETE", path, headers, b"", {}) == (
+ "bedrock-agentcore:DeleteResourcePolicy"
+ )
+ assert extract_resource_arn(
+ "bedrock-agentcore", "PUT", path, headers, b"{}", {},
+ "us-east-1", "000000000000",
+ ) == resource
+
class TestBedrockAgentCoreAuthorization:
_RUNTIME_ARN = "arn:aws:bedrock-agentcore:us-east-1:000000000000:runtime/rt-example"