

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

# 撰写临时策略
<a name="policy-temporal-authoring"></a>

您可以使用 Dogwood 策略语言编写临时策略并将其添加到策略引擎中，就像在中 AgentCore为政策创建任何其他策略一样。临时策略是指将会话感知条件置于`temporal`区块中的`permit`或`forbid`规则；该规则适用的委托人、操作和资源使用标准`(principal, action, resource)`范围编写，与任何其他策略相同。以下各节介绍如何创建临时策略以及如何演练您可以表达的常见模式。

**Topics**
+ [创建临时策略](#policy-temporal-authoring-create)
+ [事件架构：您可以引用的字段](#policy-temporal-authoring-event-schema)
+ [临时策略示例](#policy-temporal-authoring-examples)

## 创建临时策略
<a name="policy-temporal-authoring-create"></a>

您可以使用该操作创建临时策略，该`create-policy`操作与用于其他策略的操作相同，然后将其附加到策略引擎。临时政策的声明属于`policy`定义范围，而不是无国籍雪松政策的声明低于`cedar`无国籍的雪松政策。

以下示例在策略引擎上创建临时策略：

**Example**  

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

   ```
   permit (
     principal,
     action == AgentCore::Action::"InsuranceAPI___disburse_payment",
     resource == AgentCore::Gateway::"arn:aws:bedrock-agentcore:us-west-2:123456789012:gateway/insurance-gw-a1b2c3d4e5"
   )
   when temporal {
     formerly within 1h AgentCore::Action::"InsuranceAPI___approve_claim"::response{
       eventResource: resource,
       output.claimId: context.input.claimId
     }
   };
   ```

1. 将策略添加到项目配置中并部署：

   ```
   agentcore add policy --name DisburseOnlyApprovedClaim \
     --engine insurance_pe \
     --source disburse_only_approved.dw
   
   agentcore deploy --yes
   ```

    `agentcore add`只在`agentcore/agentcore.json`；中记录策略；才`agentcore deploy`是创建策略的原因。

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

   ```
   aws bedrock-agentcore-control create-policy \
     --policy-engine-id insurance_pe-a1b2c3d4e5 \
     --name DisburseOnlyApprovedClaim \
     --validation-mode FAIL_ON_ANY_FINDINGS \
     --definition '{
       "policy": {
         "statement": "permit (principal, action == AgentCore::Action::\"InsuranceAPI___disburse_payment\", resource == AgentCore::Gateway::\"arn:aws:bedrock-agentcore:us-west-2:123456789012:gateway/insurance-gw-a1b2c3d4e5\") when temporal { formerly within 1h AgentCore::Action::\"InsuranceAPI___approve_claim\"::response{ eventResource: resource, output.claimId: context.input.claimId } };"
       }
     }'
   ```

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

   ```
   import boto3
   
   client = boto3.client("bedrock-agentcore-control")
   
   GATEWAY_ARN = (
       "arn:aws:bedrock-agentcore:us-west-2:123456789012:gateway/insurance-gw-a1b2c3d4e5"
   )
   
   statement = (
       'permit (principal, '
       'action == AgentCore::Action::"InsuranceAPI___disburse_payment", '
       f'resource == AgentCore::Gateway::"{GATEWAY_ARN}") '
       'when temporal { formerly within 1h '
       'AgentCore::Action::"InsuranceAPI___approve_claim"::response{ '
       'eventResource: resource, output.claimId: context.input.claimId } };'
   )
   
   response = client.create_policy(
       policyEngineId="insurance_pe-a1b2c3d4e5",
       name="DisburseOnlyApprovedClaim",
       validationMode="FAIL_ON_ANY_FINDINGS",
       definition={"policy": {"statement": statement}},
   )
   # CreatePolicy returns 202 - wait for the terminal status
   client.get_waiter("policy_active").wait(
       policyEngineId="insurance_pe-a1b2c3d4e5",
       policyId=response["policyId"],
   )
   print(response["policyId"])
   ```

此临时政策取决于已授权的`approve_claim`请求。如果没有该先决条件操作的明确许可，则默认拒绝会阻止请求运行，并且不会记录任何`response`事件。创建包含以下语句的单独策略：

```
permit (
  principal,
  action == AgentCore::Action::"InsuranceAPI___approve_claim",
  resource == AgentCore::Gateway::"arn:aws:bedrock-agentcore:us-west-2:123456789012:gateway/insurance-gw-a1b2c3d4e5"
);
```

您也可以通过用自然语言描述来创建临时策略，而不必自己撰写 Dogwood 声明。

## 事件架构：您可以引用的字段
<a name="policy-temporal-authoring-event-schema"></a>

`temporal { }`区块内的条件使用*时间事件谓词*来匹配到目前为止在会话中记录的特定事件（不超过并包括当前正在授权的操作）。谓词为匹配的事件命名时间窗口、操作和事件类型以及一组字段约束。上一节中的`create-policy`示例使用了一个谓词`formerly within 1h AgentCore::Action::"InsuranceAPI___approve_claim"::response{ eventResource: resource, output.claimId: context.input.claimId }`，该谓词与过去一小时内`approve_claim``response`录制的`output.claimId`等于当前请求的谓词相匹配。`claimId`

要编写谓词，您需要知道操作会生成哪些事件以及每个事件携带哪些字段，因为这些是谓词可以约束和关联的字段。本节介绍该事件架构。

每个动作最多生成三种事件，以谓词 (, `::request``::response`,`::error`) 中的事件类型命名：
+  `request`— 记录每个授权请求。携带操作的输入字段。
+  `response`— 当工具成功返回时进行记录。携带操作的输入和输出字段。
+  `error`— 在请求被拒绝或工具返回错误时记录。携带操作的输入字段。此事件仅限历史记录。

时间事件架构为每个操作定义这些事件`A`。 `…​inputs(A)`并`…​outputs(A)`扩展到操作声明的输入和输出字段：

```
// Recorded for each authorized request.
decision event <A>::request {
    ...inputs(A),
    eventPrincipal: principalType(A),
    eventResource:  resourceType(A),
    requestId:      String,
    pin sessionId:  String = context.sessionId,
}

// Recorded when the tool returns successfully; carries inputs and outputs.
event <A>::response {
    ...inputs(A),
    ...outputs(A),
    eventPrincipal: principalType(A),
    eventResource:  resourceType(A),
    requestId:      String,
    pin sessionId:  String = context.sessionId,
}

// Recorded when the request is denied or the tool returns an error; history-only.
event <A>::error {
    ...inputs(A),
    eventPrincipal: principalType(A),
    eventResource:  resourceType(A),
    requestId:      String,
    pin sessionId:  String = context.sessionId,
}
```

在谓词正文中，您可以引用匹配事件的以下字段：


| 字段 | 说明 | 
| --- | --- | 
|  `input.<name>`  | 操作的输入字段。在`request``response`、和`error`活动上可用。 | 
|  `output.<name>`  | 操作的输出字段。仅适用于`response`活动。 | 
|  `eventPrincipal`  | 发出录音请求的校长。 | 
|  `eventResource`  | 请务必将其设置为 `resource` (`forbid`as`eventResource: resource`)，使其引用策略范围内的资源，即`permit`或`resource`标题中的资源。这将匹配范围限定为当前请求的资源，并且每个时间谓词都必须包含该资源。 | 

要将记录的事件与当前请求相关联，请将其中一个字段与当前请求中的值（例如`context.input.<name>`）进行比较。

## 临时策略示例
<a name="policy-temporal-authoring-examples"></a>

[有关临时政策所表达的每种模式的示例（要求事先批准、过时的先决条件到期、限制计数或累计总数、冷却时间、相互排斥、连锁以及对先前的拒绝做出反应），请参阅政策编写指南中的[临时政策](example-policies-temporal.md)示例。](policy-authoring-guide.md)这里的每个示例都是针对与其他策略示例相同的参考网关编写的，说明了哪些引用网关允许将其与之配对，并给出了会话中每个请求序列的决定。