

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 政策建立和更新：每個政策引擎驗證

直接建立或更新政策時 （而不是透過產生），驗證和分析會將新政策及其與政策引擎中**所有預先存在政策**的互動納入考量。

## 運作方式
<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. 此範例假設 AgentCore 專案具有名為 的政策引擎，`MyEngine`連接到名為 的已部署閘道`my-gateway`，例如從 `agentcore add policy-engine --name MyEngine --attach-to-gateways my-gateway`後接 `agentcore deploy`。將陳述式儲存到檔案，例如 `restrict_refunds.cedar`，並在`agentcore status --json`其中使用該閘道的 ARN：

   ```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. 新增政策並部署：

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

1. 在終端機中執行下列程式碼，以使用 CLI AWS 建立政策：

   ```bash
   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 的 AWS SDK 建立政策：

   ```python
   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'])
   ```

回應表示正在建立政策：

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

檢查政策狀態以確認已通過驗證：

**Example**  

1. 顯示專案中資源的部署狀態：

   ```bash
   agentcore status
   ```

   若要檢查單一政策的狀態和調查結果，請使用 AWS CLI 或 SDK。

1. 在終端機中執行下列程式碼，以使用 CLI AWS 取得政策：

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

1. 執行下列程式碼，使用適用於 Python 的 AWS SDK 等待政策變為作用中：

   ```python
   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'))
   ```

驗證通過時，政策會變成作用中：

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

## 範例：驗證失敗
<a name="policy-validation-failure-example"></a>

如果政策參考在任何相關聯閘道的結構描述中不存在的動作，則驗證會失敗。請注意，此失敗是**非同步的**：建立呼叫會傳回 HTTP 202 與 `CREATING`，然後政策會進入 `CREATE_FAILED`。

**Example**  

1. 驗證失敗的政策會讓整個部署失敗，而不只是該資源：

   ```bash
   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
   ```

   部署會報告基礎`CREATE_FAILED`原因。使用 移除錯誤政策`agentcore remove policy --engine MyEngine --name InvalidPolicy`，然後再次部署。

1. 在終端機中執行下列程式碼，以建立參考未定義動作的政策：

   ```bash
   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. 檢查狀態以查看驗證失敗：

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

1. 執行下列程式碼來建立政策，並使用適用於 Python 的 AWS SDK 讀取失敗原因：

   ```python
   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'))
   ```

當您檢查政策狀態時，回應會顯示驗證失敗：

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