Amazon Bedrock AgentCore Gateway as a Unified AI Gateway
Amazon Bedrock AgentCore Gateway: one entry point for all your AI providers, with Cedar policies and Bedrock Guardrails enforcing access automatically.
Series: AI Governance powered by AWS (2 articles)
- 2Amazon Bedrock AgentCore Gateway as a Unified AI Gateway This article
Modern AI applications call multiple model providers — Amazon Bedrock, OpenAI, Anthropic, Google Gemini, and others — from many different agents and services. Each provider has its own SDK, authentication scheme, and endpoint. Governance (who can call which model, what content is allowed) gets bolted on separately, inconsistently, or not at all. As the number of models and consumers grows, this becomes an operational and compliance problem.
Amazon Bedrock AgentCore Gateway solves this by acting as a single, policy-enforced entry point for all your AI traffic — a unified AI gateway. Every model call, regardless of provider, flows through one place where you control authentication, authorization, routing, and content safety.
In this post we cover:
- Concepts: what the gateway is, target types, the policy model, and how everything fits together
- Hands-on walkthrough: complete AWS CLI steps to create a gateway, add multi-provider inference targets, set up OAuth M2M tokens with Cognito, and write Cedar policies including Bedrock Guardrails
Core Concepts
What is AgentCore Gateway?
AgentCore Gateway is a managed, centralized gateway for AI workloads. It is more than a reverse proxy — it is a platform that supports multiple usage patterns:
- MCP server hub — expose Lambda functions, REST APIs, and other backends as MCP (Model Context Protocol) tools, enabling AI agents to discover and invoke tools through a single gateway URL
- Tool registry — centralize tool definitions so agents can search and call tools without knowing which backend serves them
- Unified AI gateway — proxy multiple model providers (Bedrock, OpenAI, Anthropic, Google Gemini, and many more) behind a single endpoint with consistent authentication, authorization, and content safety
This post focuses on the unified AI gateway use case — using PROVIDER inference targets to proxy multiple model providers and applying Cedar policies and Bedrock Guardrails to govern access.
As a unified AI gateway (inference targets), AgentCore Gateway handles the following:
- Inbound authentication — validates JWT tokens or AWS SigV4 signatures before forwarding requests
- Policy enforcement — evaluates Cedar policies on every request
- Credential management — abstracts upstream credentials using the gateway's IAM role so callers never need direct access to upstream services
- Traffic routing — routes requests to the correct target based on model-based routing, with the possibility of building more advanced routing strategies using AWS Lambda interceptors
Inference Target Types: PROVIDER vs CONNECTOR
AgentCore Gateway inference targets come in two types, and the choice depends on what you're connecting to.
PROVIDER targets are for inference endpoints — any URL that speaks OpenAI or Anthropic wire protocol. You provide the upstream endpoint, the allowed operations (paths and HTTP methods), the model IDs to accept, and optionally a
providerPath to override the upstream path. The gateway routes inference calls to this endpoint and enforces model-level access control via Cedar.Use PROVIDER targets when:
- Connecting to a model provider endpoint (Bedrock Mantle, OpenAI API, Anthropic API, Google Gemini, or a self-hosted vLLM server)
- You need per-model policy granularity — each PROVIDER target maps to one or more specific model IDs, and Cedar can reference each target individually as a distinct action
- You want the gateway to validate that the
modelfield in the request matches the allowed list
CONNECTOR targets are also for model inference — they are the zero-configuration alternative to PROVIDER targets. A CONNECTOR target works out of the box for supported providers (Bedrock Mantle, OpenAI, Anthropic): no
endpoint , no providerPath , no model allow-list needed. The gateway handles path rewriting automatically and exposes the provider's full model catalog.The trade-off is flexibility and governance. Because a CONNECTOR target exposes the full catalog, you cannot restrict which models are reachable through it via configuration alone — you would need Cedar policies to deny specific models. PROVIDER targets let you enforce the allow-list at the target level: only the models listed in
operations are reachable, and any other model ID is rejected before Cedar even evaluates.Use CONNECTOR targets when:
- You want a quick integration with a supported provider and don't need to restrict the model catalog
- You are prototyping or exploring before locking down a model allow-list
Use PROVIDER targets (this walkthrough) when:
- You need explicit control over which models are reachable
- You are connecting to a provider without a built-in connector (any OpenAI-compatible or Anthropic Messages-compatible endpoint)
- You need
providerPathto bridge a URL difference between the gateway and the upstream
| PROVIDER | CONNECTOR |
|---|---|---|
Used for | Model inference (explicit control) | Model inference (zero config) |
Supported providers | Any OpenAI-compatible or Anthropic Messages-compatible endpoint | Built-in providers only (Bedrock, OpenAI, Anthropic) |
Model catalog | Only models listed in operations | Full provider catalog |
Configuration | endpoint , operations , providerPath | Minimal — provider type only |
Cedar action format | gateway-arn___target___METHOD:/path | --- |
In this post we focus on PROVIDER targets for inference, as they provide seamless governance with AgentCore Policy and Bedrock Guardrails.
The Policy Model
The gateway uses Cedar — the same open-source policy language used by Amazon Verified Permissions and AWS authorization services. Cedar is default-deny: every request is blocked unless an explicit
permit rule allows it. A forbid rule always overrides a matching permit (deny-overrides semantics).Policies are grouped in an AgentCore Policy Engine, which attaches to a gateway in either
ENFORCE mode (blocks denied requests) or AUDIT mode (logs decisions without blocking — useful for testing policies before enabling enforcement).JWT claims from the inbound token are automatically surfaced as Cedar principal tags. The gateway's
CUSTOM_JWT authorizer supports any OAuth 2.0-compliant identity provider — this walkthrough uses Cognito M2M ( client_credentials ) as a concrete illustration, but the same pattern works for authorization code flow, device flow, or any other grant type your IdP supports. For M2M tokens, the available claims are machine identity fields like client_id , scope , and sub . For user-bearing tokens (authorization code flow), user-level claims like username , email , group , team , or department are present, enabling per-user restrictions.Guardrail policies extend Cedar with content scanning. Instead of the standard
when { ... } condition block, they use when guardrails { ... } to call Amazon Bedrock Guardrails inline during policy evaluation. The gateway scans the request body for PII, violent content, prompt injection, and more — and blocks or logs based on confidence scores — all without any application code change.How Governance Is Centralized
Every application pointed at the gateway URL gets the same policies automatically. Adding a new model restriction means writing one Cedar policy — not updating every SDK call across every service. When an agent is compromised or a user's access is revoked, you update one policy and it takes effect on all traffic immediately.
Architecture for This Walkthrough
┌─────────────────────────────────────────┐ │ Cognito User Pool │ │ (M2M client_credentials grant) │ └──────────────────┬──────────────────────┘ │ JWT token ▼Client Application ──────► AgentCore Gateway (CUSTOM_JWT auth) │ ┌────────────────┴────────────────┐ │ Policy Engine │ │ ┌─────────────────────────────┐│ │ │ permitAll ││ │ │ denyUserFromGpt54 (ABAC) ││ │ │ blockEmailInInput (Guardrail)││ │ └─────────────────────────────┘│ └────────────────┬────────────────┘ │ ┌────────────────────────┼──────────────────────┐ ▼ ▼ ▼ PROVIDER: gpt-54 PROVIDER: gpt-56 PROVIDER: anthropic openai.gpt-5.4 openai.gpt-5.6-sol anthropic.claude-sonnet-5 /openai/v1/responses /openai/v1/responses /anthropic/v1/messages │ │ │ └────────────────────────┴──────────────────────┘ │ bedrock-mantle.us-east-1.api.aws
Prerequisites
- AWS CLI configured with an IAM principal that has
bedrock-agentcore:*,cognito-idp:*, andiam:PassRolepermissions
- An IAM role for the gateway execution context — the gateway assumes this role to call upstream providers and evaluate guardrails
Step 0: Environment Setup
All steps below use shell variables derived from CLI output, so nothing is hardcoded. Set these once:
export AWS_REGION="us-east-1"export AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)export GATEWAY_ROLE_ARN="arn:aws:iam::${AWS_ACCOUNT_ID}:role/agentcore-gateway-role"
Step 1: Set Up Authentication (M2M Illustrated)
The gateway validates inbound JWTs using its
CUSTOM_JWT authorizer, which works with any OAuth 2.0-compliant identity provider. This walkthrough uses Cognito with the client_credentials (M2M) grant as a concrete illustration — the same setup applies to other flows (authorization code, device flow, etc.) supported by your IdP. For M2M access — agents, services, CI systems — the client_credentials grant is the simplest approach: no users, no login UI, just a client ID and secret that exchange for a JWT.Create the user pool
USER_POOL_ID=$(aws cognito-idp create-user-pool \ --pool-name "agentcore-gateway-pool" \ --query 'UserPool.Id' \ --output text)
echo "User pool: $USER_POOL_ID"Create a resource server (defines the token audience/scope)
aws cognito-idp create-resource-server \ --user-pool-id $USER_POOL_ID \ --identifier "https://gateway.agentcore" \ --name "AgentCore Gateway" \ --scopes '[{"ScopeName":"invoke","ScopeDescription":"Invoke gateway targets"}]'Create M2M app clients
Create two clients — one for general access (
client-a ) and one for a restricted service ( client-b ). In Step 6.6 you'll deny client-b from one specific model to demonstrate per-client governance.# Client A — general accessCLIENT_A=$(aws cognito-idp create-user-pool-client \ --user-pool-id $USER_POOL_ID \ --client-name "gateway-client-a" \ --generate-secret \ --allowed-o-auth-flows client_credentials \ --allowed-o-auth-scopes "https://gateway.agentcore/invoke" \ --allowed-o-auth-flows-user-pool-client)
CLIENT_A_ID=$(echo $CLIENT_A | python3 -c "import json,sys; print(json.load(sys.stdin)['UserPoolClient']['ClientId'])")CLIENT_A_SECRET=$(echo $CLIENT_A | python3 -c "import json,sys; print(json.load(sys.stdin)['UserPoolClient']['ClientSecret'])")
# Client B — will be restricted from gpt-54 in Step 6.6CLIENT_B=$(aws cognito-idp create-user-pool-client \ --user-pool-id $USER_POOL_ID \ --client-name "gateway-client-b" \ --generate-secret \ --allowed-o-auth-flows client_credentials \ --allowed-o-auth-scopes "https://gateway.agentcore/invoke" \ --allowed-o-auth-flows-user-pool-client)
CLIENT_B_ID=$(echo $CLIENT_B | python3 -c "import json,sys; print(json.load(sys.stdin)['UserPoolClient']['ClientId'])")CLIENT_B_SECRET=$(echo $CLIENT_B | python3 -c "import json,sys; print(json.load(sys.stdin)['UserPoolClient']['ClientSecret'])")
echo "Client A ID: $CLIENT_A_ID"echo "Client B ID: $CLIENT_B_ID"Add a Cognito domain (required for the token endpoint)
DOMAIN_PREFIX="agentcore-gateway-$(date +%s)"aws cognito-idp create-user-pool-domain \ --domain $DOMAIN_PREFIX \ --user-pool-id $USER_POOL_ID
TOKEN_ENDPOINT="https://${DOMAIN_PREFIX}.auth.${AWS_REGION}.amazoncognito.com/oauth2/token"DISCOVERY_URL="https://cognito-idp.${AWS_REGION}.amazonaws.com/${USER_POOL_ID}/.well-known/openid-configuration"
echo "Token endpoint: $TOKEN_ENDPOINT"echo "Discovery URL: $DISCOVERY_URL"Get JWT tokens for both clients
CLIENT_A_TOKEN=$(curl -s -X POST $TOKEN_ENDPOINT \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials&client_id=${CLIENT_A_ID}&client_secret=${CLIENT_A_SECRET}&scope=https://gateway.agentcore/invoke" \ | python3 -c "import json,sys; print(json.load(sys.stdin)['access_token'])")
CLIENT_B_TOKEN=$(curl -s -X POST $TOKEN_ENDPOINT \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials&client_id=${CLIENT_B_ID}&client_secret=${CLIENT_B_SECRET}&scope=https://gateway.agentcore/invoke" \ | python3 -c "import json,sys; print(json.load(sys.stdin)['access_token'])")
echo "Client A token (first 50 chars): ${CLIENT_A_TOKEN:0:50}..."echo "Client B token (first 50 chars): ${CLIENT_B_TOKEN:0:50}..."CLIENT_A_TOKEN is used for all standard gateway calls throughout this walkthrough. CLIENT_B_TOKEN is used in Step 6.6 to demonstrate per-client access control. Tokens expire (typically 1 hour); re-run the commands above to refresh.
Step 2: Create the Gateway IAM Role
The gateway assumes this role for three purposes: calling Bedrock Mantle to invoke upstream models, evaluating Cedar policies (policy engine authorization), and invoking Bedrock Guardrails for content scanning. All three permission sets must be in place before the policy engine and guardrail policies work correctly.
# Trust policy — allows the gateway service to assume this roleGATEWAY_ROLE_NAME="agentcore-gateway-role"aws iam create-role \ --role-name $GATEWAY_ROLE_NAME \ --assume-role-policy-document "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Effect\": \"Allow\", \"Principal\": {\"Service\": \"bedrock-agentcore.amazonaws.com\"}, \"Action\": \"sts:AssumeRole\", \"Condition\": { \"StringEquals\": {\"aws:SourceAccount\": \"$AWS_ACCOUNT_ID\"} } } ] }"
GATEWAY_ROLE_ARN=$(aws iam get-role --role-name $GATEWAY_ROLE_NAME --query 'Role.Arn' --output text)
# Bedrock Mantle — required for PROVIDER inference targetsaws iam put-role-policy \ --role-name $GATEWAY_ROLE_NAME \ --policy-name BedrockMantleInvoke \ --policy-document '{ "Version": "2012-10-17", "Statement": [ { "Sid": "BedrockInvoke", "Effect": "Allow", "Action": [ "bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream" ], "Resource": [ "arn:aws:bedrock:*::foundation-model/*", "arn:aws:bedrock:*:*:inference-profile/*" ] }, { "Sid": "BedrockMantleInvoke", "Effect": "Allow", "Action": [ "bedrock-mantle:CallWithBearerToken", "bedrock-mantle:CreateInference", "bedrock-mantle:GetInference", "bedrock-mantle:ListModels" ], "Resource": "*" } ] }'
# Bedrock Guardrails — required for guardrail policies in Cedaraws iam put-role-policy \ --role-name $GATEWAY_ROLE_NAME \ --policy-name BedrockGuardrails \ --policy-document '{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "bedrock:InvokeGuardrailChecks", "Resource": "*" } ] }'
echo "Gateway role ARN: $GATEWAY_ROLE_ARN"The policy engine permissions (bedrock-agentcore:GetPolicyEngine,bedrock-agentcore:AuthorizeAction) are added in Step 6 after the policy engine is created, since the policy ARN is needed to scope them correctly.
Step 3: Create the Gateway
GATEWAY=$(aws bedrock-agentcore-control create-gateway \ --name "model-policy-demo-v2" \ --role-arn $GATEWAY_ROLE_ARN \ --protocol-type "MCP" \ --authorizer-type "CUSTOM_JWT" \ --authorizer-configuration "{ \"customJWTAuthorizer\": { \"allowedClients\": [\"${CLIENT_A_ID}\", \"${CLIENT_B_ID}\"], \"discoveryUrl\": \"${DISCOVERY_URL}\" } }")
GATEWAY_ID=$(echo $GATEWAY | python3 -c "import json,sys; print(json.load(sys.stdin)['gatewayId'])")GATEWAY_ARN=$(echo $GATEWAY | python3 -c "import json,sys; print(json.load(sys.stdin)['gatewayArn'])")GATEWAY_URL=$(echo $GATEWAY | python3 -c "import json,sys; u=json.load(sys.stdin)['gatewayUrl']; print(u.replace('/mcp',''))")
echo "Gateway ID: $GATEWAY_ID"echo "Gateway ARN: $GATEWAY_ARN"echo "Gateway URL: $GATEWAY_URL"
# Wait for READYecho "Waiting for gateway to become READY..."while true; do STATUS=$(aws bedrock-agentcore-control get-gateway \ --gateway-identifier $GATEWAY_ID \ --query 'status' --output text) echo " Status: $STATUS" [ "$STATUS" = "READY" ] && break sleep 5doneAll subsequent commands use
$GATEWAY_ID , $GATEWAY_ARN , and $GATEWAY_URL — no hardcoded values.
Step 4: Add Inference Targets (PROVIDER Type)
Inference targets are PROVIDER-type targets that forward requests to an upstream model endpoint. The three key configuration fields:
-
endpoint— the upstream base URL (no path suffix)
-
path— the client-facing path the gateway accepts; must be one of/v1/responses,/v1/chat/completions,/v1/messages
-
providerPath— the actual path forwarded upstream when the upstream differs frompath
-
models— allow-list of model IDs this target accepts; requests with other model IDs are rejected
Why providerPath ?
Bedrock Mantle serves OpenAI-compatible models at
/openai/v1/responses and Anthropic models at /anthropic/v1/messages . But the gateway only accepts the standard paths ( /v1/responses , /v1/messages ) from clients. The providerPath field bridges this gap: the client calls /v1/responses , and the gateway rewrites the upstream path to /openai/v1/responses before forwarding.Without
providerPath , you'd get a 404 from the upstream because /v1/responses doesn't exist on Bedrock Mantle's OpenAI path.Target 1: GPT-5.4 (OpenAI Responses API)
TARGET_GPT54=$(aws bedrock-agentcore-control create-gateway-target \ --gateway-identifier $GATEWAY_ID \ --name "gpt-54" \ --target-configuration '{ "inference": { "provider": { "endpoint": "https://bedrock-mantle.us-east-1.api.aws", "operations": [ { "path": "/v1/responses", "providerPath": "/openai/v1/responses", "models": [{"model": "openai.gpt-5.4"}] } ] } } }' \ --credential-provider-configurations '[{"credentialProviderType": "GATEWAY_IAM_ROLE"}]')
echo "gpt-54 target ID: $(echo $TARGET_GPT54 | python3 -c "import json,sys; print(json.load(sys.stdin)['targetId'])")"Target 2: GPT-5.6-sol (OpenAI Responses API)
TARGET_GPT56=$(aws bedrock-agentcore-control create-gateway-target \ --gateway-identifier $GATEWAY_ID \ --name "gpt-56" \ --target-configuration '{ "inference": { "provider": { "endpoint": "https://bedrock-mantle.us-east-1.api.aws", "operations": [ { "path": "/v1/responses", "providerPath": "/openai/v1/responses", "models": [{"model": "openai.gpt-5.6-sol"}] } ] } } }' \ --credential-provider-configurations '[{"credentialProviderType": "GATEWAY_IAM_ROLE"}]')
echo "gpt-56 target ID: $(echo $TARGET_GPT56 | python3 -c "import json,sys; print(json.load(sys.stdin)['targetId'])")"Target 3: Claude Sonnet 5 (Anthropic Messages API)
TARGET_ANTHROPIC=$(aws bedrock-agentcore-control create-gateway-target \ --gateway-identifier $GATEWAY_ID \ --name "anthropic" \ --target-configuration '{ "inference": { "provider": { "endpoint": "https://bedrock-mantle.us-east-1.api.aws", "operations": [ { "path": "/v1/messages", "providerPath": "/anthropic/v1/messages", "models": [{"model": "anthropic.claude-sonnet-5"}] } ] } } }' \ --credential-provider-configurations '[{"credentialProviderType": "GATEWAY_IAM_ROLE"}]')
echo "anthropic target ID: $(echo $TARGET_ANTHROPIC | python3 -c "import json,sys; print(json.load(sys.stdin)['targetId'])")"Wait for all targets to reach
READY :aws bedrock-agentcore-control list-gateway-targets \ --gateway-identifier $GATEWAY_ID \ --query 'items[*].{name:name,status:status}'
Step 5: Test the Targets
With
CLIENT_A_TOKEN set from Step 1, call each target directly:OpenAI Responses API
# Standard callcurl ${GATEWAY_URL}/inference/v1/responses \ -H "Authorization: Bearer $CLIENT_A_TOKEN" \ -H "Content-Type: application/json" \ -d '{"model": "openai.gpt-5.4", "input": "What is Amazon Bedrock AgentCore?"}'
# Streamingcurl ${GATEWAY_URL}/inference/v1/responses \ -H "Authorization: Bearer $CLIENT_A_TOKEN" \ -H "Content-Type: application/json" \ -N \ -d '{"model": "openai.gpt-5.6-sol", "input": "What is Amazon Bedrock AgentCore?", "stream": true}'Anthropic Messages API
# Standard callcurl ${GATEWAY_URL}/inference/v1/messages \ -H "Authorization: Bearer $CLIENT_A_TOKEN" \ -H "Content-Type: application/json" \ -H "anthropic-version: 2023-06-01" \ -d '{"model": "anthropic.claude-sonnet-5", "max_tokens": 1024, "messages": [{"role": "user", "content": "What is Amazon Bedrock AgentCore?"}]}'
# Streamingcurl ${GATEWAY_URL}/inference/v1/messages \ -H "Authorization: Bearer $CLIENT_A_TOKEN" \ -H "Content-Type: application/json" \ -H "anthropic-version: 2023-06-01" \ -N \ -d '{"model": "anthropic.claude-sonnet-5", "max_tokens": 1024, "stream": true, "messages": [{"role": "user", "content": "What is Amazon Bedrock AgentCore?"}]}'All three targets should respond successfully at this point — no policy engine is attached yet so all authenticated requests pass through.
Step 6: Set Up the Policy Engine and Cedar Policies
This step covers everything from creating the policy engine to writing three Cedar policies. Cedar is default-deny: once the engine is attached, every request is blocked unless an explicit
permit allows it. forbid always overrides permit (deny-overrides semantics). We'll set up the engine, write a base permit, then add an ABAC deny and a guardrail deny.6.1 — Cedar fundamentals: action names and principal tags
Before writing policies, understand two things:
Action name format for PROVIDER targets:
AgentCore::Action::"<gateway-arn>___<target-name>___<METHOD>:<path>"For the
gpt-54 target on our gateway:AgentCore::Action::"<gateway-arn>___gpt-54___POST:/v1/responses"CONNECTOR targets (MCP/Lambda) use a shorter format:
"<gateway-arn>___<target-name>" — no method or path suffix.JWT claims as principal tags: Every claim in the inbound JWT is surfaced automatically as a Cedar principal tag:
principal.hasTag("client_id") // check if claim exists (M2M)principal.getTag("client_id") == "abc123" // restrict a specific app clientprincipal.getTag("scope").contains("read:models") // check scope membershipFor M2M
client_credentials tokens, the available claims are machine identity fields: client_id , sub , scope , iss , exp , iat , token_use . User-level claims like username , email , or cognito:groups only appear in user-bearing tokens issued via authorization code flow.6.2 — Create the policy engine
ENGINE=$(aws bedrock-agentcore-control create-policy-engine \ --name "modelPolicyDemoEngineV2")
ENGINE_ID=$(echo $ENGINE | python3 -c "import json,sys; print(json.load(sys.stdin)['policyEngineId'])")ENGINE_ARN=$(echo $ENGINE | python3 -c "import json,sys; print(json.load(sys.stdin)['policyEngineArn'])")
echo "Policy engine ID: $ENGINE_ID"echo "Policy engine ARN: $ENGINE_ARN"6.3 — Grant the gateway role permission to use the policy engine
The gateway evaluates policies using FAS (Forward Access Session) credentials from the execution role. Now that we have
$ENGINE_ARN , add the policy engine permissions to the role:aws iam put-role-policy \ --role-name $GATEWAY_ROLE_NAME \ --policy-name AllowPolicyEngine \ --policy-document "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Effect\": \"Allow\", \"Action\": [ \"bedrock-agentcore:GetPolicyEngine\", \"bedrock-agentcore:AuthorizeAction\", \"bedrock-agentcore:PartiallyAuthorizeActions\" ], \"Resource\": [ \"${ENGINE_ARN}\", \"${GATEWAY_ARN}\" ] } ] }"6.4 — Attach the policy engine to the gateway
aws bedrock-agentcore-control update-gateway \ --gateway-identifier "$GATEWAY_ID" \ --name "model-policy-demo-v2" \ --role-arn "$GATEWAY_ROLE_ARN" \ --authorizer-type "CUSTOM_JWT" \ --authorizer-configuration '{ "customJWTAuthorizer": { "allowedClients": ["'"$CLIENT_A_ID"'", "'"$CLIENT_B_ID"'"], "discoveryUrl": "'"$DISCOVERY_URL"'" } }' \ --policy-engine-configuration '{ "arn": "'"$ENGINE_ARN"'", "mode": "ENFORCE" }'Tip: Use"mode": "AUDIT"first to observe policy decisions in CloudWatch without blocking any traffic. Switch to"ENFORCE"when you're confident the policies are correct.
6.5 — Create the base permit policy
Cedar is default-deny, so every request is blocked the moment the policy engine is attached. Create this first.
aws bedrock-agentcore-control create-policy \ --policy-engine-id $ENGINE_ID \ --name "permitAllV2" \ --validation-mode "IGNORE_ALL_FINDINGS" \ --definition '{ "cedar": { "statement": "permit(principal, action, resource is AgentCore::Gateway);" } }'The--validation-mode IGNORE_ALL_FINDINGSflag bypasses the policy validator's "overly restrictive" check, which fires on a fresh engine with no existing permit. Always createpermitAllbefore anyforbidpolicies.
6.6 — Deny a specific app client from a specific model (M2M ABAC)
This policy reads the
client_id claim from the inbound M2M JWT and denies that specific app client access to the gpt-54 target. Other clients, and the same client on other targets, are unaffected.Whyclient_idand notusername? Cognitoclient_credentialstokens (M2M) contain only machine identity claims:client_id,sub,scope,iss,exp,iat,token_use. There is nousernameclaim in an M2M token — a Cedar condition checkingprincipal.getTag("username") == "alice"would never match. For per-human-user restrictions, you need a user-bearing token issued via authorization code flow, where the IdP includesusername,cognito:groups, and other user claims.
aws bedrock-agentcore-control create-policy \ --policy-engine-id $ENGINE_ID \ --name "denyClientBFromGpt54V2" \ --validation-mode "IGNORE_ALL_FINDINGS" \ --definition "{ \"cedar\": { \"statement\": \"forbid(principal, action == AgentCore::Action::\\\"${GATEWAY_ARN}___gpt-54___POST:/v1/responses\\\", resource == AgentCore::Gateway::\\\"${GATEWAY_ARN}\\\") when { principal.hasTag(\\\"client_id\\\") && principal.getTag(\\\"client_id\\\") == \\\"${CLIENT_B_ID}\\\" };\" } }"Cedar statement written out clearly:
forbid( principal, action == AgentCore::Action::"<gateway-arn>___gpt-54___POST:/v1/responses", resource == AgentCore::Gateway::"<gateway-arn>")when { principal.hasTag("client_id") && principal.getTag("client_id") == "<client-b-id>"};Test it: Client B calling
gpt-54 → 403 . Client B calling gpt-56 or anthropic → 200 . Any other client calling gpt-54 → 200 .# Denied for client Bcurl ${GATEWAY_URL}/inference/v1/responses \ -H "Authorization: Bearer $CLIENT_B_TOKEN" \ -H "Content-Type: application/json" \ -d '{"model": "openai.gpt-5.4", "input": "hello"}'# → 403
# Allowed for client B on a different targetcurl ${GATEWAY_URL}/inference/v1/responses \ -H "Authorization: Bearer $CLIENT_B_TOKEN" \ -H "Content-Type: application/json" \ -d '{"model": "openai.gpt-5.6-sol", "input": "hello"}'# → 2006.7 — Block PII with Bedrock Guardrails
Guardrail policies run Amazon Bedrock Guardrails inline during Cedar evaluation — scanning request content for sensitive information, harmful content, or prompt injection — before the request reaches the model. The
when guardrails { ... } block replaces the standard when { ... } condition. The action must be equality-constrained for guardrail policies.This policy blocks any request to
gpt-56 where the input field contains an email address:aws bedrock-agentcore-control create-policy \ --policy-engine-id $ENGINE_ID \ --name "blockEmailInInputV2" \ --validation-mode "IGNORE_ALL_FINDINGS" \ --definition "{ \"policy\": { \"statement\": \"forbid(principal, action == AgentCore::Action::\\\"${GATEWAY_ARN}___gpt-56___POST:/v1/responses\\\", resource == AgentCore::Gateway::\\\"${GATEWAY_ARN}\\\") when guardrails { BedrockGuardrails::SensitiveInformation([\\\"EMAIL\\\"], [context.input.input]).maxConfidenceScore().greaterThan(decimal(\\\"0.5\\\")) };\" } }"Cedar statement written out clearly:
forbid( principal, action == AgentCore::Action::"<gateway-arn>___gpt-56___POST:/v1/responses", resource == AgentCore::Gateway::"<gateway-arn>")when guardrails { BedrockGuardrails::SensitiveInformation(["EMAIL"], [context.input.input]) .maxConfidenceScore() .greaterThan(decimal("0.5"))};Context path mapping: For the Responses API, the JSON field
"input": "..." maps to context.input.input . The first input is the Cedar context namespace for the request body; the second is the JSON field name.Test it:
# Blocked — email address detected in inputcurl ${GATEWAY_URL}/inference/v1/responses \ -H "Authorization: Bearer $CLIENT_A_TOKEN" \ -H "Content-Type: application/json" \ -d '{"model": "openai.gpt-5.6-sol", "input": "send an email to user@example.com"}'# → 403
# Allowed — no PIIcurl ${GATEWAY_URL}/inference/v1/responses \ -H "Authorization: Bearer $CLIENT_A_TOKEN" \ -H "Content-Type: application/json" \ -d '{"model": "openai.gpt-5.6-sol", "input": "what is the capital of France"}'# → 200
Beyond the Walkthrough
Safe policy rollout — Attach the engine in
"mode": "AUDIT" first; Cedar evaluates every request and logs decisions without blocking. For individual guardrail policies, use --enforcement-mode LOG_ONLY to observe confidence score distributions in CloudWatch before switching to ACTIVE . See Policy Engine modes .Combining Cedar and guardrails —
when { ... } and when guardrails { ... } cannot be mixed in one policy statement, but two forbid policies on the same action work together via deny-overrides — either one can block independently.
Current Limitations
Failover routing — There is no built-in health-check-based failover between inference targets. The recommended workaround is a Lambda interceptor that reads a circuit-breaker flag maintained by a separate health probe and rewrites the target before the gateway forwards the request.
Cost governance and spend limits — Cedar policies can allow or deny requests but cannot inspect token counts or cumulative spend. Budget enforcement requires a Lambda interceptor that reads a per-caller usage counter (e.g., from DynamoDB) and blocks the request once the quota is exceeded. This pattern is covered end-to-end in the agentcore-gateway-usage-interceptor sample.
Cedar Quick Reference
Action name formats
Target type | Cedar action |
|---|---|
PROVIDER (Responses API) | AgentCore::Action::"<gateway-arn>___<target>___POST:/v1/responses" |
PROVIDER (Messages API) | AgentCore::Action::"<gateway-arn>___<target>___POST:/v1/messages" |
MCP/Lambda | AgentCore::Action::"<gateway-arn>___<target>" |
Context paths
API | JSON field | Cedar path |
|---|---|---|
Responses API | "input" | context.input.input |
Messages API | "messages" | context.input.messages |
MCP tools/call | params.arguments.X | context.input.X |
Guardrail syntax
forbid(principal, action == AgentCore::Action::"...", resource == AgentCore::Gateway::"...")when guardrails { BedrockGuardrails::SensitiveInformation(["EMAIL"], [context.input.input]) .maxConfidenceScore().greaterThan(decimal("0.5"))};Scores are discrete:
0, 0.2, 0.4, 0.6, 0.8, 1.0 . For available categories ( SensitiveInformation , ContentFilter , PromptAttack ) and aggregations ( .maxConfidenceScore() , .count() , per-category .confidenceScore ), see the Guardrails in Policies developer guide.
Summary
Capability | Mechanism |
|---|---|
Single entry point for multiple AI providers | PROVIDER inference targets with endpoint + providerPath |
Standard SDK compatibility | Gateway exposes OpenAI and Anthropic paths natively |
Default-deny access control | Cedar policy engine in ENFORCE mode |
Per-client, per-model restrictions (M2M) | Cedar ABAC on client_id claim from M2M JWT |
Content safety without application code | Bedrock Guardrails in Cedar when guardrails blocks |
Safe policy rollout | AUDIT gateway mode + LOG_ONLY policy enforcement mode |
Consistent governance across all models | One policy engine evaluates every request |
The architectural shift is significant: governance moves from being each application's responsibility to being infrastructure. A new model can be added to the gateway in minutes. A policy change takes effect on all traffic immediately. Compliance rules are code — auditable, version-controlled, and consistent.
Resources
Series: AI Governance powered by AWS (2 articles)
- 2Amazon Bedrock AgentCore Gateway as a Unified AI Gateway This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article