bedrock-agentcore-policy
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAmazon Bedrock AgentCore Policy
Amazon Bedrock AgentCore Policy
Overview
概述
AgentCore Policy provides deterministic enforcement of agent boundaries, separate from the probabilistic nature of prompt engineering. Author policies in natural language that automatically convert to Cedar—AWS's open-source policy language—for real-time enforcement at the Gateway layer.
Purpose: Define what agents can and cannot do with deterministic, auditable rules
Pattern: Task-based (5 operations)
Key Principles (validated by AWS December 2025):
- Natural Language Authoring - Write policies in plain English
- Automated Cedar Generation - System converts to valid Cedar
- Real-time Enforcement - Gateway intercepts every tool call
- Automated Reasoning - Detects overly permissive/restrictive rules
- Default Deny - No permit policy = automatic denial
- Forbid Wins - Forbid always overrides permit
Quality Targets:
- Policy generation: < 5 seconds
- Enforcement latency: < 10ms per tool call
- Validation coverage: 100% of tool schemas
AgentCore Policy 可确定性地执行Agent边界限制,与提示工程的概率性特性相分离。您可以用自然语言编写策略,系统会自动将其转换为AWS的开源策略语言Cedar,在网关层进行实时执行。
用途:通过确定性、可审计的规则定义Agent的可执行与不可执行操作
模式:基于任务(5项操作)
核心原则(经AWS 2025年12月验证):
- 自然语言编写 - 用通俗易懂的英语编写策略
- 自动生成Cedar - 系统转换为有效的Cedar策略
- 实时执行 - 网关拦截所有工具调用
- 自动推理 - 检测过于宽松或严格的规则
- 默认拒绝 - 无允许策略则自动拒绝
- 禁止优先 - 禁止规则始终覆盖允许规则
质量指标:
- 策略生成时间:<5秒
- 执行延迟:每次工具调用<10毫秒
- 验证覆盖率:100%工具架构
When to Use
适用场景
Use bedrock-agentcore-policy when:
- Setting boundaries for what agents can do
- Implementing role-based access control (RBAC)
- Enforcing compliance rules (e.g., max refund amounts)
- Temporarily disabling problematic tools
- Requiring specific parameters for operations
- Auditing agent actions
When NOT to Use:
- Content filtering (use Bedrock Guardrails)
- Rate limiting (use API Gateway)
- Business logic (implement in tools)
在以下场景中使用bedrock-agentcore-policy:
- 定义Agent的操作边界
- 实现基于角色的访问控制(RBAC)
- 执行合规规则(例如,退款金额上限)
- 临时禁用存在问题的工具
- 要求操作必须包含特定参数
- 审计Agent的操作行为
不适用场景:
- 内容过滤(使用Bedrock Guardrails)
- 请求频率限制(使用API Gateway)
- 业务逻辑(在工具中实现)
Prerequisites
前置条件
Required
必需条件
- AgentCore Gateway configured
- Tools registered as Gateway targets
- IAM permissions for policy operations
- 已配置AgentCore Gateway
- 已将工具注册为网关目标
- 拥有策略操作的IAM权限
Recommended
推荐条件
- Understanding of Cedar semantics
- Tool schemas documented
- Test scenarios defined
- 了解Cedar语义
- 已记录工具架构
- 已定义测试场景
Operations
操作步骤
Operation 1: Natural Language Policy Authoring
操作1:自然语言策略编写
Time: 2-5 minutes
Automation: 95%
Purpose: Create policies from plain English descriptions
Process:
- Define requirements in natural language:
"Allow all users to read policy details and claim status.
Only allow users with 'senior-adjuster' role to update coverage.
Block all claim filings unless a description is provided."- Generate Cedar policy:
python
import boto3
control = boto3.client('bedrock-agentcore-control')耗时:2-5分钟
自动化程度:95%
用途:通过自然语言描述创建策略
流程:
- 用自然语言定义需求:
"Allow all users to read policy details and claim status.
Only allow users with 'senior-adjuster' role to update coverage.
Block all claim filings unless a description is provided."- 生成Cedar策略:
python
import boto3
control = boto3.client('bedrock-agentcore-control')Start policy generation from natural language
Start policy generation from natural language
response = control.start_policy_generation(
gatewayId='gateway-xxx',
naturalLanguagePolicy="""
Allow all users to get policy and get claim status.
Only allow principals with the 'senior-adjuster' role to update coverage.
Block principals from filing claims unless description is provided.
""",
policyName='insurance-agent-policy'
)
generation_id = response['policyGenerationId']
response = control.start_policy_generation(
gatewayId='gateway-xxx',
naturalLanguagePolicy="""
Allow all users to get policy and get claim status.
Only allow principals with the 'senior-adjuster' role to update coverage.
Block principals from filing claims unless description is provided.
""",
policyName='insurance-agent-policy'
)
generation_id = response['policyGenerationId']
Wait for completion
Wait for completion
waiter = control.get_waiter('PolicyGenerationCompleted')
waiter.wait(policyGenerationId=generation_id)
waiter = control.get_waiter('PolicyGenerationCompleted')
waiter.wait(policyGenerationId=generation_id)
Get generated Cedar
Get generated Cedar
result = control.get_policy_generation(
policyGenerationId=generation_id
)
cedar_policy = result['generatedPolicy']
validation_results = result['validationResults']
3. **Review generated Cedar**:
```cedar
// Permit read-only actions for everyone
permit(
principal,
action in [
AgentCore::Action::"InsuranceAPI__get_policy",
AgentCore::Action::"InsuranceAPI__get_claim_status"
],
resource
);
// Permit updates only for specific roles
permit(
principal,
action == AgentCore::Action::"InsuranceAPI__update_coverage",
resource
)
when {
principal.hasTag("role") &&
principal.getTag("role") == "senior-adjuster"
};
// Block claims without description
forbid(
principal,
action == AgentCore::Action::"InsuranceAPI__file_claim",
resource
)
unless {
context.input has description
};result = control.get_policy_generation(
policyGenerationId=generation_id
)
cedar_policy = result['generatedPolicy']
validation_results = result['validationResults']
3. **查看生成的Cedar策略**:
```cedar
// Permit read-only actions for everyone
permit(
principal,
action in [
AgentCore::Action::"InsuranceAPI__get_policy",
AgentCore::Action::"InsuranceAPI__get_claim_status"
],
resource
);
// Permit updates only for specific roles
permit(
principal,
action == AgentCore::Action::"InsuranceAPI__update_coverage",
resource
)
when {
principal.hasTag("role") &&
principal.getTag("role") == "senior-adjuster"
};
// Block claims without description
forbid(
principal,
action == AgentCore::Action::"InsuranceAPI__file_claim",
resource
)
unless {
context.input has description
};Operation 2: Create Policy Directly (Cedar)
操作2:直接创建Cedar策略
Time: 5-10 minutes
Automation: 80%
Purpose: Write Cedar policies with full control
Cedar Syntax:
cedar
// Basic permit
permit(
principal,
action == AgentCore::Action::"ToolName__method",
resource == AgentCore::Gateway::"arn:..."
);
// With conditions
permit(
principal is AgentCore::OAuthUser,
action == AgentCore::Action::"RefundAPI__process_refund",
resource
)
when {
context.input.amount < 1000
};
// Forbid with unless
forbid(
principal,
action == AgentCore::Action::"DeleteAPI__delete_record",
resource
)
unless {
principal.hasTag("role") &&
principal.getTag("role") == "admin"
};Create policy via boto3:
python
response = control.create_policy(
name='refund-limit-policy',
description='Limits refunds to under $1000 for non-managers',
policyContent='''
permit(
principal,
action == AgentCore::Action::"RefundToolTarget___refund",
resource == AgentCore::Gateway::"arn:aws:bedrock-agentcore:us-east-1:123456789012:gateway/refund"
)
when {
context.input.amount < 1000
};
permit(
principal,
action == AgentCore::Action::"RefundToolTarget___refund",
resource == AgentCore::Gateway::"arn:aws:bedrock-agentcore:us-east-1:123456789012:gateway/refund"
)
when {
principal.hasTag("role") &&
principal.getTag("role") == "manager"
};
'''
)
policy_id = response['policyId']耗时:5-10分钟
自动化程度:80%
用途:完全自主编写Cedar策略
Cedar语法示例:
cedar
// Basic permit
permit(
principal,
action == AgentCore::Action::"ToolName__method",
resource == AgentCore::Gateway::"arn:..."
);
// With conditions
permit(
principal is AgentCore::OAuthUser,
action == AgentCore::Action::"RefundAPI__process_refund",
resource
)
when {
context.input.amount < 1000
};
// Forbid with unless
forbid(
principal,
action == AgentCore::Action::"DeleteAPI__delete_record",
resource
)
unless {
principal.hasTag("role") &&
principal.getTag("role") == "admin"
};通过boto3创建策略:
python
response = control.create_policy(
name='refund-limit-policy',
description='Limits refunds to under $1000 for non-managers',
policyContent='''
permit(
principal,
action == AgentCore::Action::"RefundToolTarget___refund",
resource == AgentCore::Gateway::"arn:aws:bedrock-agentcore:us-east-1:123456789012:gateway/refund"
)
when {
context.input.amount < 1000
};
permit(
principal,
action == AgentCore::Action::"RefundToolTarget___refund",
resource == AgentCore::Gateway::"arn:aws:bedrock-agentcore:us-east-1:123456789012:gateway/refund"
)
when {
principal.hasTag("role") &&
principal.getTag("role") == "manager"
};
'''
)
policy_id = response['policyId']Operation 3: Common Policy Patterns
操作3:常见策略模式
Time: 5-15 minutes
Automation: 90%
Purpose: Implement standard access control patterns
Pattern 1: Role-Based Access Control (RBAC)
cedar
// Admin-only actions
permit(
principal,
action in [
AgentCore::Action::"AdminAPI__delete_user",
AgentCore::Action::"AdminAPI__modify_permissions"
],
resource
)
when {
principal.hasTag("role") &&
principal.getTag("role") == "admin"
};Pattern 2: OAuth Scope Validation
cedar
// Require specific scope
permit(
principal is AgentCore::OAuthUser,
action == AgentCore::Action::"CustomerAPI__read_profile",
resource
)
when {
principal.hasTag("scope") &&
principal.getTag("scope") like "*customer:read*"
};Pattern 3: Parameter Constraints
cedar
// Limit by parameter value
permit(
principal,
action == AgentCore::Action::"TransferAPI__transfer_funds",
resource
)
when {
context.input has amount &&
context.input.amount <= 10000
};Pattern 4: Multi-Condition AND Logic
cedar
// All conditions must be true
permit(
principal,
action == AgentCore::Action::"InsuranceAPI__update_coverage",
resource
)
when {
context.input has coverageType &&
context.input has newLimit &&
(context.input.coverageType == "liability" ||
context.input.coverageType == "collision")
};Pattern 5: Disable Specific Tool
cedar
// Temporarily disable a tool
forbid(
principal,
action == AgentCore::Action::"ProblematicAPI__buggy_method",
resource
);Pattern 6: User-Specific Permissions
cedar
// Grant to specific user
permit(
principal,
action == AgentCore::Action::"SpecialAPI__sensitive_action",
resource
)
when {
principal.hasTag("username") &&
principal.getTag("username") == "trusted-user"
};耗时:5-15分钟
自动化程度:90%
用途:实现标准访问控制模式
模式1:基于角色的访问控制(RBAC)
cedar
// Admin-only actions
permit(
principal,
action in [
AgentCore::Action::"AdminAPI__delete_user",
AgentCore::Action::"AdminAPI__modify_permissions"
],
resource
)
when {
principal.hasTag("role") &&
principal.getTag("role") == "admin"
};模式2:OAuth权限范围验证
cedar
// Require specific scope
permit(
principal is AgentCore::OAuthUser,
action == AgentCore::Action::"CustomerAPI__read_profile",
resource
)
when {
principal.hasTag("scope") &&
principal.getTag("scope") like "*customer:read*"
};模式3:参数约束
cedar
// Limit by parameter value
permit(
principal,
action == AgentCore::Action::"TransferAPI__transfer_funds",
resource
)
when {
context.input has amount &&
context.input.amount <= 10000
};模式4:多条件与逻辑
cedar
// All conditions must be true
permit(
principal,
action == AgentCore::Action::"InsuranceAPI__update_coverage",
resource
)
when {
context.input has coverageType &&
context.input has newLimit &&
(context.input.coverageType == "liability" ||
context.input.coverageType == "collision")
};模式5:禁用特定工具
cedar
// Temporarily disable a tool
forbid(
principal,
action == AgentCore::Action::"ProblematicAPI__buggy_method",
resource
);模式6:用户专属权限
cedar
// Grant to specific user
permit(
principal,
action == AgentCore::Action::"SpecialAPI__sensitive_action",
resource
)
when {
principal.hasTag("username") &&
principal.getTag("username") == "trusted-user"
};Operation 4: Policy Engine Configuration
操作4:策略引擎配置
Time: 5-10 minutes
Automation: 85%
Purpose: Attach policies to Gateway for enforcement
Create Policy Engine:
python
undefined耗时:5-10分钟
自动化程度:85%
用途:将策略关联到网关以执行
创建策略引擎:
python
undefinedCreate policy engine to evaluate policies
Create policy engine to evaluate policies
response = control.create_policy_engine(
name='insurance-policy-engine',
description='Enforces insurance agent boundaries',
gatewayId='gateway-xxx'
)
engine_id = response['policyEngineId']
response = control.create_policy_engine(
name='insurance-policy-engine',
description='Enforces insurance agent boundaries',
gatewayId='gateway-xxx'
)
engine_id = response['policyEngineId']
Wait for active
Wait for active
waiter = control.get_waiter('PolicyEngineActive')
waiter.wait(policyEngineId=engine_id)
**Attach Policy to Engine**:
```pythonwaiter = control.get_waiter('PolicyEngineActive')
waiter.wait(policyEngineId=engine_id)
**将策略关联到引擎**:
```pythonUpdate policy engine with policies
Update policy engine with policies
response = control.update_policy_engine(
policyEngineId=engine_id,
policyIds=[
'policy-read-access',
'policy-role-restrictions',
'policy-refund-limits'
]
)
**Test Policy Enforcement**:
```pythonresponse = control.update_policy_engine(
policyEngineId=engine_id,
policyIds=[
'policy-read-access',
'policy-role-restrictions',
'policy-refund-limits'
]
)
**测试策略执行**:
```pythonInvoke agent and observe policy enforcement
Invoke agent and observe policy enforcement
client = boto3.client('bedrock-agentcore')
response = client.invoke_agent_runtime(
agentRuntimeArn='arn:...',
runtimeSessionId='test-session',
payload={
'prompt': 'Process a refund of $50000',
'context': {
'user_id': 'regular-user',
'role': 'customer-service' # Not manager
}
}
)
client = boto3.client('bedrock-agentcore')
response = client.invoke_agent_runtime(
agentRuntimeArn='arn:...',
runtimeSessionId='test-session',
payload={
'prompt': 'Process a refund of $50000',
'context': {
'user_id': 'regular-user',
'role': 'customer-service' # Not manager
}
}
)
Policy will block this - amount exceeds $1000 for non-managers
Policy will block this - amount exceeds $1000 for non-managers
Agent response will indicate the action was denied
Agent response will indicate the action was denied
---
---Operation 5: Policy Validation and Debugging
操作5:策略验证与调试
Time: 5-15 minutes
Automation: 80%
Purpose: Test and troubleshoot policy behavior
Validation Checks:
python
undefined耗时:5-15分钟
自动化程度:80%
用途:测试和排查策略行为
验证检查:
python
undefinedGet policy validation results
Get policy validation results
response = control.get_policy_generation(
policyGenerationId=generation_id
)
for issue in response.get('validationResults', {}).get('issues', []):
print(f"Issue: {issue['type']}")
print(f"Message: {issue['message']}")
print(f"Location: {issue.get('location', 'N/A')}")
response = control.get_policy_generation(
policyGenerationId=generation_id
)
for issue in response.get('validationResults', {}).get('issues', []):
print(f"Issue: {issue['type']}")
print(f"Message: {issue['message']}")
print(f"Location: {issue.get('location', 'N/A')}")
Common issues:
Common issues:
- Overly permissive (allows more than intended)
- Overly permissive (allows more than intended)
- Overly restrictive (blocks legitimate actions)
- Overly restrictive (blocks legitimate actions)
- Unsatisfiable conditions (can never match)
- Unsatisfiable conditions (can never match)
- Schema mismatch (references non-existent tools)
- Schema mismatch (references non-existent tools)
**Debug Policy Decisions**:
```python
**调试策略决策**:
```pythonEnable detailed logging
Enable detailed logging
import logging
logging.getLogger('botocore').setLevel(logging.DEBUG)
import logging
logging.getLogger('botocore').setLevel(logging.DEBUG)
Check CloudWatch for policy decisions
Check CloudWatch for policy decisions
Log group: /aws/bedrock-agentcore/gateway/{gateway-id}
Log group: /aws/bedrock-agentcore/gateway/{gateway-id}
Look for: PolicyDecision events
Look for: PolicyDecision events
Example log entry:
Example log entry:
{
{
"eventType": "PolicyDecision",
"eventType": "PolicyDecision",
"action": "InsuranceAPI__file_claim",
"action": "InsuranceAPI__file_claim",
"decision": "DENY",
"decision": "DENY",
"matchedPolicy": "policy-require-description",
"matchedPolicy": "policy-require-description",
"reason": "Condition not satisfied: context.input has description"
"reason": "Condition not satisfied: context.input has description"
}
}
**Test Scenarios**:
```python
def test_policy_scenarios():
"""Test various policy scenarios"""
test_cases = [
{
'name': 'Regular user reads policy',
'action': 'get_policy',
'context': {'role': 'user'},
'expected': 'ALLOW'
},
{
'name': 'Regular user updates coverage',
'action': 'update_coverage',
'context': {'role': 'user'},
'expected': 'DENY'
},
{
'name': 'Senior adjuster updates coverage',
'action': 'update_coverage',
'context': {'role': 'senior-adjuster'},
'expected': 'ALLOW'
},
{
'name': 'Claim without description',
'action': 'file_claim',
'context': {'role': 'user'},
'input': {'amount': 100}, # No description
'expected': 'DENY'
},
{
'name': 'Claim with description',
'action': 'file_claim',
'context': {'role': 'user'},
'input': {'amount': 100, 'description': 'Car accident'},
'expected': 'ALLOW'
}
]
for case in test_cases:
result = simulate_policy(case)
assert result == case['expected'], f"Failed: {case['name']}"
**测试场景**:
```python
def test_policy_scenarios():
"""Test various policy scenarios"""
test_cases = [
{
'name': 'Regular user reads policy',
'action': 'get_policy',
'context': {'role': 'user'},
'expected': 'ALLOW'
},
{
'name': 'Regular user updates coverage',
'action': 'update_coverage',
'context': {'role': 'user'},
'expected': 'DENY'
},
{
'name': 'Senior adjuster updates coverage',
'action': 'update_coverage',
'context': {'role': 'senior-adjuster'},
'expected': 'ALLOW'
},
{
'name': 'Claim without description',
'action': 'file_claim',
'context': {'role': 'user'},
'input': {'amount': 100}, # No description
'expected': 'DENY'
},
{
'name': 'Claim with description',
'action': 'file_claim',
'context': {'role': 'user'},
'input': {'amount': 100, 'description': 'Car accident'},
'expected': 'ALLOW'
}
]
for case in test_cases:
result = simulate_policy(case)
assert result == case['expected'], f"Failed: {case['name']}"Cedar Quick Reference
Cedar快速参考
Principal Types
主体类型
cedar
principal // Any principal
principal is AgentCore::OAuthUser // OAuth authenticated user
principal is AgentCore::ApiKeyUser // API key authenticatedcedar
principal // Any principal
principal is AgentCore::OAuthUser // OAuth authenticated user
principal is AgentCore::ApiKeyUser // API key authenticatedActions
操作
cedar
action == AgentCore::Action::"ToolName__method"
action in [Action1, Action2, Action3]cedar
action == AgentCore::Action::"ToolName__method"
action in [Action1, Action2, Action3]Conditions
条件
cedar
// Tag checks
principal.hasTag("role")
principal.getTag("role") == "admin"
principal.getTag("scope") like "*read*"
// Context/input checks
context.input has fieldName
context.input.amount < 1000
context.input.type == "premium"
// Logical operators
&& // AND
|| // OR
! // NOTcedar
// Tag checks
principal.hasTag("role")
principal.getTag("role") == "admin"
principal.getTag("scope") like "*read*"
// Context/input checks
context.input has fieldName
context.input.amount < 1000
context.input.type == "premium"
// Logical operators
&& // AND
|| // OR
! // NOTPolicy Types
策略类型
cedar
permit(...) // Allow if conditions match
permit(...) when {} // Allow with conditions
forbid(...) // Deny unconditionally
forbid(...) unless {} // Deny unless conditions matchcedar
permit(...) // Allow if conditions match
permit(...) when {} // Allow with conditions
forbid(...) // Deny unconditionally
forbid(...) unless {} // Deny unless conditions matchBest Practices
最佳实践
1. Start Permissive, Tighten Gradually
1. 从宽松到严格逐步收紧
cedar
// Phase 1: Allow all, log actions
permit(principal, action, resource);
// Phase 2: After analysis, add restrictions
permit(principal, action, resource)
when { /* specific conditions */ };cedar
// Phase 1: Allow all, log actions
permit(principal, action, resource);
// Phase 2: After analysis, add restrictions
permit(principal, action, resource)
when { /* specific conditions */ };2. Use Descriptive Policy Names
2. 使用描述性策略名称
python
control.create_policy(
name='refund-limit-1000-non-managers', # Good
# name='policy-1', # Bad
...
)python
control.create_policy(
name='refund-limit-1000-non-managers', # Good
# name='policy-1', # Bad
...
)3. Document Business Rules
3. 记录业务规则
cedar
// Business Rule: PCI-DSS compliance requires
// credit card operations to be role-restricted
permit(
principal,
action == AgentCore::Action::"PaymentAPI__process_card",
resource
)
when {
principal.hasTag("role") &&
principal.getTag("role") in ["payment-admin", "finance"]
};cedar
// Business Rule: PCI-DSS compliance requires
// credit card operations to be role-restricted
permit(
principal,
action == AgentCore::Action::"PaymentAPI__process_card",
resource
)
when {
principal.hasTag("role") &&
principal.getTag("role") in ["payment-admin", "finance"]
};4. Layer Policies
4. 分层策略
Policy Stack:
1. Global deny (default)
2. Read-only permits (broad)
3. Write permits (role-specific)
4. Admin permits (highly restricted)
5. Emergency forbids (immediate disable)Policy Stack:
1. Global deny (default)
2. Read-only permits (broad)
3. Write permits (role-specific)
4. Admin permits (highly restricted)
5. Emergency forbids (immediate disable)MCP Server Integration
MCP Server集成
AgentCore Policy is available as an MCP server for AI-assisted coding environments:
json
{
"mcpServers": {
"bedrock-agentcore-policy": {
"command": "uvx",
"args": ["bedrock-agentcore-policy-mcp"],
"env": {
"AWS_REGION": "us-east-1"
}
}
}
}AgentCore Policy 可作为MCP服务器集成到AI辅助编码环境中:
json
{
"mcpServers": {
"bedrock-agentcore-policy": {
"command": "uvx",
"args": ["bedrock-agentcore-policy-mcp"],
"env": {
"AWS_REGION": "us-east-1"
}
}
}
}Related Skills
相关技能
- bedrock-agentcore: Core platform and Gateway setup
- bedrock-agentcore-evaluations: Test policy effectiveness
- bedrock-agentcore-deployment: Deploy policies with agents
- eks-irsa: IAM integration for EKS-hosted agents
- bedrock-agentcore: 核心平台与网关设置
- bedrock-agentcore-evaluations: 测试策略有效性
- bedrock-agentcore-deployment: 随Agent一起部署策略
- eks-irsa: 为EKS托管的Agent集成IAM
References
参考资料
- - Complete Cedar language guide
references/cedar-syntax.md - - Common patterns library
references/policy-patterns.md - - Policy debugging guide
references/troubleshooting.md
- - 完整Cedar语言指南
references/cedar-syntax.md - - 常见模式库
references/policy-patterns.md - - 策略调试指南
references/troubleshooting.md