

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 策略创建和更新：每个策略的引擎验证
<a name="policy-create-update-validation"></a>

当直接创建或更新策略（而不是通过生成）时，验证和分析会考虑新策略及其与策略引擎中**所有先前存在**的策略的交互。

## 工作原理
<a name="policy-create-update-validation-how"></a>

1. 对于与策略引擎关联**的所有网关**，将根据 Cedar 架构检查该策略。无论验证模式如何，架构检查始终运行。

1. 如果将验证模式设置为`FAIL_ON_ANY_FINDINGS`，则语义验证将在**整个策略引擎**的上下文中运行，检查是否存在过于宽松、过于严格和无效的策略。如果架构检查或语义验证得出结果，则策略将被拒绝。有关每项检查的详细信息，请参阅[验证和分析概述](policy-validation-overview.md)。

**注意**  
使用`IGNORE_ALL_FINDINGS`时，仅运行架构检查。只要策略通过架构检查，就可以被接受。有关更多信息，请参阅[向策略引擎添加策略](add-policies-to-engine.md)。

## 示例：创建带有验证的策略
<a name="policy-create-validation-example"></a>

创建经过严格验证的策略，拒绝包含任何发现的策略：

**Example**  

1. 将语句保存到文件中，例如`restrict_refunds.cedar`：

   ```
   forbid (
     principal,
     action == AgentCore::Action::"RefundTool___process_refund",
     resource == AgentCore::Gateway::"arn:aws:bedrock-agentcore:us-west-2:123456789012:gateway/my-gateway-a1b2c3d4e5"
   )
   when {
     context.input.amount > 1000
   };
   ```

1. 添加策略并部署：

   ```
   agentcore add policy --name RestrictRefunds \
     --engine MyEngine \
     --source restrict_refunds.cedar \
     --validation-mode FAIL_ON_ANY_FINDINGS
   
   agentcore deploy --yes
   ```

1. 在终端中运行以下代码，使用 Amazon CLI 创建策略：

   ```
   aws bedrock-agentcore-control create-policy \
     --policy-engine-id MyEngine-abc123defg \
     --name RestrictRefunds \
     --validation-mode FAIL_ON_ANY_FINDINGS \
     --definition '{
       "policy": {
         "statement": "forbid (principal, action == AgentCore::Action::\"RefundTool___process_refund\", resource == AgentCore::Gateway::\"arn:aws:bedrock-agentcore:us-west-2:123456789012:gateway/my-gateway-a1b2c3d4e5\") when { context.input.amount > 1000 };"
       }
     }'
   ```

1. 运行以下代码，使用适用于 Python 的 Amazon 软件开发工具包创建策略：

   ```
   import boto3
   
   client = boto3.client('bedrock-agentcore-control')
   
   GATEWAY_ARN = (
       'arn:aws:bedrock-agentcore:us-west-2:123456789012:gateway/my-gateway-a1b2c3d4e5'
   )
   
   statement = (
       'forbid (principal, '
       'action == AgentCore::Action::"RefundTool___process_refund", '
       f'resource == AgentCore::Gateway::"{GATEWAY_ARN}") '
       'when { context.input.amount > 1000 };'
   )
   
   response = client.create_policy(
       policyEngineId='MyEngine-abc123defg',
       name='RestrictRefunds',
       validationMode='FAIL_ON_ANY_FINDINGS',
       definition={'policy': {'statement': statement}},
   )
   print(response['policyId'], response['status'])
   ```

响应表示策略正在创建中：

```
{
  "policyId": "RestrictRefunds-ghi789jklm",
  "status": "CREATING"
}
```

检查策略状态以确认验证通过：

**Example**  

1. 显示项目中资源的部署状态：

   ```
   agentcore status
   ```

   C AgentCore LI 没有按策略执行读取操作。使用 C Amazon LI 或 SDK 检查单个策略的状态和发现。

1. 在终端中运行以下代码以使用 Amazon CLI 获取策略：

   ```
   aws bedrock-agentcore-control get-policy \
     --policy-engine-id MyEngine-abc123defg \
     --policy-id RestrictRefunds-ghi789jklm
   ```

1. 使用适用于 Python 的 Amazon SDK 运行以下代码，等待策略生效：

   ```
   import boto3
   
   client = boto3.client('bedrock-agentcore-control')
   
   client.get_waiter('policy_active').wait(
       policyEngineId='MyEngine-abc123defg',
       policyId='RestrictRefunds-ghi789jklm',
   )
   
   policy = client.get_policy(
       policyEngineId='MyEngine-abc123defg',
       policyId='RestrictRefunds-ghi789jklm',
   )
   print(policy['status'], policy.get('statusReasons'))
   ```

验证通过后，策略将变为活动状态：

```
{
  "policyId": "RestrictRefunds-ghi789jklm",
  "status": "ACTIVE",
  "statusReasons": []
}
```

## 示例：验证失败
<a name="policy-validation-failure-example"></a>

如果策略引用的操作不存在于任何关联网关的架构中，则验证失败。请注意，此失败是**异步**的：create 调用返回 HTTP 202`CREATING`，然后策略设置为`CREATE_FAILED`。

**Example**  

1. 验证失败的策略会使整个部署失败，而不仅仅是该资源：

   ```
   agentcore add policy --name InvalidPolicy \
     --engine MyEngine \
     --statement 'permit (principal, action == AgentCore::Action::"RefundTool___nonExistentTool", resource == AgentCore::Gateway::"arn:aws:bedrock-agentcore:us-west-2:123456789012:gateway/my-gateway-a1b2c3d4e5");'
   
   agentcore deploy --yes
   ```

   部署报告了根本`CREATE_FAILED`原因。使用删除错误的策略，`agentcore remove policy --engine MyEngine --name InvalidPolicy`然后重新部署。

1. 在终端中运行以下代码，创建引用未定义操作的策略：

   ```
   aws bedrock-agentcore-control create-policy \
     --policy-engine-id MyEngine-abc123defg \
     --name InvalidPolicy \
     --validation-mode FAIL_ON_ANY_FINDINGS \
     --definition '{
       "policy": {
         "statement": "permit (principal, action == AgentCore::Action::\"RefundTool___nonExistentTool\", resource == AgentCore::Gateway::\"arn:aws:bedrock-agentcore:us-west-2:123456789012:gateway/my-gateway-a1b2c3d4e5\");"
       }
     }'
   ```

1. 检查状态以查看验证失败：

   ```
   aws bedrock-agentcore-control get-policy \
     --policy-engine-id MyEngine-abc123defg \
     --policy-id InvalidPolicy-jkl012mnop
   ```

1. 使用适用于 Python 的 Amazon SDK 运行以下代码来创建策略并读取失败原因：

   ```
   import time
   import boto3
   
   client = boto3.client('bedrock-agentcore-control')
   
   GATEWAY_ARN = (
       'arn:aws:bedrock-agentcore:us-west-2:123456789012:gateway/my-gateway-a1b2c3d4e5'
   )
   
   response = client.create_policy(
       policyEngineId='MyEngine-abc123defg',
       name='InvalidPolicy',
       validationMode='FAIL_ON_ANY_FINDINGS',
       definition={'policy': {'statement': (
           'permit (principal, '
           'action == AgentCore::Action::"RefundTool___nonExistentTool", '
           f'resource == AgentCore::Gateway::"{GATEWAY_ARN}");'
       )}},
   )
   
   # The 202 above is not success - poll for the terminal status
   while True:
       policy = client.get_policy(
           policyEngineId='MyEngine-abc123defg',
           policyId=response['policyId'],
       )
       if policy['status'] != 'CREATING':
           break
       time.sleep(4)
   
   print(policy['status'], policy.get('statusReasons'))
   ```

当您检查策略状态时，响应会显示验证失败：

```
{
  "policyId": "InvalidPolicy-jkl012mnop",
  "status": "CREATE_FAILED",
  "statusReasons": [
    "Validation failed: Action 'nonExistentTool' is not defined in the schema for any associated gateway"
  ]
}
```