

# 建议加密
<a name="recommendations-encryption"></a>

当您根据推荐指定时，该服务会使用带有加密 SDK 的信封加密来加密**推荐配置****和推荐结果**。`kmsKeyArn` AWS 所有其他推荐元数据（名称、类型、状态）仍使用所 AWS 拥有的密钥进行加密。

`kmsKeyArn`是在创建时通过指定的`StartRecommendation`。

## 工作原理
<a name="recommendations-encryption-how-it-works"></a>

建议加密使用加 AWS 密 SDK 进行信封加密。当服务写入或读取推荐数据时，它会调用 KMS 来生成或解密数据密钥。推荐结果也 SSE-KMS 使用相同的客户托管密钥存储在 S3 中。

在 API 时，该服务使用试运行检查（转发访问会话）来验证呼叫者是否具有 KMS 权限。这样可以立即发现权限问题，而不是在推荐工作流程中异步失败。

当推荐工作流程异步运行时，服务主体 (`bedrock-agentcore.amazonaws.com`) 会解密配置并对结果进行加密。服务主体必须拥有`kms:GenerateDataKey`密钥策略中的`kms:Decrypt`权限。

AgentCore 优化仅支持对称加密 KMS 密钥。KMS 密钥必须与建议位于同一 AWS 区域。

### 配置使用客户托管 KMS 密钥的权限
<a name="recommendations-encryption-key-policy"></a>

以下密钥策略提供了建议加密所需的最低权限。该策略包含三条语句：
+  **AllowCallerAccess**— 允许 IAM 用户或角色通过验证密钥`DescribeKey`。
+  **AllowCallerCryptoOps**— 允许 IAM 用户或角色根据加密上下文进行加密和解密。
+  **AllowServicePrincipalAccess**— 允许 AgentCore 服务主体在异步推荐工作流程中加密和解密推荐数据，范围按源账户和源 ARN 确定。

```
{
"Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowCallerAccess",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::111122223333:role/MyRecommendationRole"
      },
      "Action": "kms:DescribeKey",
      "Resource": "*"
    },
    {
      "Sid": "AllowCallerCryptoOps",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::111122223333:role/MyRecommendationRole"
      },
      "Action": [
        "kms:GenerateDataKey",
        "kms:Decrypt"
      ],
      "Resource": "*",
      "Condition": {
        "StringLike": {
          "kms:EncryptionContext:aws:bedrock-agentcore:recommendationArn": "arn:aws:bedrock-agentcore:us-east-1:111122223333:recommendation/*"
        }
      }
    },
    {
      "Sid": "AllowServicePrincipalAccess",
      "Effect": "Allow",
      "Principal": {
        "Service": "bedrock-agentcore.amazonaws.com"
      },
      "Action": [
        "kms:GenerateDataKey",
        "kms:Decrypt"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "aws:SourceAccount": "111122223333"
        },
        "ArnLike": {
          "aws:SourceArn": "arn:aws:bedrock-agentcore:us-east-1:111122223333:recommendation/*"
        }
      }
    }
  ]
}
```

该政策包含以下声明：
+  **AllowCallerAccess**— 授予 IAM 角色在创建建议时进行密钥验证的`kms:DescribeKey`权限。{{111122223333}}替换为您的账户 ID {{MyRecommendationRole}} 和启动推荐的 IAM 角色或用户。
+  **AllowCallerCryptoOps**— 授予 IAM 角色`kms:GenerateDataKey`和`kms:Decrypt`权限，范围由`aws:bedrock-agentcore:recommendationArn`加密上下文决定。用您的值替换{{111122223333}}{{MyRecommendationRole}}、和{{us-east-1}}。要允许访问您账户中的所有推荐，请使用带有`StringLike`:`arn:aws:bedrock-agentcore:us-east-1:111122223333:recommendation/*`的通配符。
+  **AllowServicePrincipalAccess**— 授予 AgentCore 服务主体`kms:GenerateDataKey`和在异步工作流程中加密和解密推荐数据的`kms:Decrypt`权限。按来源账户和来源 ARN `aws:SourceArn` () 划分范围，以防止混淆副手攻击。{{111122223333}}用您的地区{{us-east-1}}和账户 ID 替换和。

### 缩小对客户托管的 KMS 密钥的访问权限
<a name="recommendations-encryption-scoping"></a>

您可以使用加密上下文来缩小对客户托管密钥的访问范围。 AgentCore 优化在所有 KMS 操作中都包括以下加密上下文：

```
{
  "aws:bedrock-agentcore:recommendationArn": "arn:aws:bedrock-agentcore:us-east-1:111122223333:recommendation/recommendation-id"
}
```

您可以在密钥策略条件中使用此加密上下文将 KMS 操作限制在特定的建议范围内，如上面示例密钥策略中的`AllowCallerCryptoOps`声明所示。请注意，`AllowServicePrincipalAccess`它`aws:SourceArn`用于范围界定而不是加密上下文。

## 使用客户托管的 KMS 密钥开始推荐
<a name="recommendations-encryption-creating"></a>

调用时指定`kmsKeyArn`参数`StartRecommendation`：

**Example**  

```
agentcore run recommendation \
  -t system-prompt \
  -r MyAgent \
  -e Builtin.Correctness \
  --inline "You are a helpful assistant" \
  --kms-key arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab
```

```
aws bedrock-agentcore start-recommendation \
  --name "MyEncryptedRecommendation" \
  --type SYSTEM_PROMPT_RECOMMENDATION \
  --kms-key-arn "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" \
  --recommendation-config '{
    "systemPromptRecommendationConfig": {
      "systemPrompt": {
        "text": "You are a helpful assistant."
      },
      "agentTraces": {
        "cloudwatchLogs": {
          "logGroupArns": ["arn:aws:logs:us-east-1:111122223333:log-group:/aws/bedrock-agentcore/sessions/my-agent"],
          "serviceNames": ["my-agent.DEFAULT"],
          "startTime": "2025-01-01T00:00:00Z",
          "endTime": "2025-01-02T00:00:00Z"
        }
      },
      "evaluationConfig": {
        "evaluators": [{"evaluatorArn": "arn:aws:bedrock-agentcore:::evaluator/Builtin.Helpfulness"}]
      }
    }
  }'
```

```
import boto3

client = boto3.client('bedrock-agentcore')

response = client.start_recommendation(
    name='MyEncryptedRecommendation',
    type='SYSTEM_PROMPT_RECOMMENDATION',
    kmsKeyArn='arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab',
    recommendationConfig={
        'systemPromptRecommendationConfig': {
            'systemPrompt': {
                'text': 'You are a helpful assistant.'
            },
            'agentTraces': {
                'cloudwatchLogs': {
                    'logGroupArns': ['arn:aws:logs:us-east-1:111122223333:log-group:/aws/bedrock-agentcore/sessions/my-agent'],
                    'serviceNames': ['my-agent.DEFAULT'],
                    'startTime': '2025-01-01T00:00:00Z',
                    'endTime': '2025-01-02T00:00:00Z'
                }
            },
            'evaluationConfig': {
                'evaluators': [{'evaluatorArn': 'arn:aws:bedrock-agentcore:::evaluator/Builtin.Helpfulness'}]
            }
        }
    }
)

print(f"Recommendation ID: {response['recommendationId']}")
```

## 监控 KMS 使用情况以获取建议
<a name="recommendations-encryption-monitoring"></a>

建议的 KMS 操作会出现以下 CloudTrail 事件名称：
+  `GenerateDataKey`— 启动推荐（加密配置）和推荐工作流程完成时（加密结果）。该`encryptionContext`字段包含`aws:bedrock-agentcore:recommendationArn`。
+  `Decrypt`— 当推荐工作流处理配置时，或者在检索推荐结果时。
+  `DescribeKey`— 在创建推荐时验证密钥时。

## 密钥不可用时的行为
<a name="recommendations-encryption-unavailable"></a>

如果您禁用或删除建议使用的客户托管 KMS 密钥：
+  **StartRecommendation**— 使用验证失败`ValidationException`。
+  **GetRecommendation**— 失败，`ValidationException`指示 KMS 密钥已禁用或删除。
+  **ListRecommendations**— 之所以成功，是因为列出仅返回元数据且不需要 KMS 操作。
+  **DeleteRecommendation**— 成功是因为删除不需要解密推荐数据。