

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

# 了解 Amazon SNS 数据保护策略
<a name="sns-message-data-protection-policies"></a>

**重要**  
从 2026 年 4 月 30 日起，Amazon SNS 消息数据保护将不再向新客户提供。有关替代方案的更多信息和指导，请参阅 [Amazon SNS 消息数据保护可用性变更](https://docs.aws.amazon.com/sns/latest/dg/sns-message-data-protection-availability-change.html)。

## 什么是数据保护策略？
<a name="what-are-data-protection-policies"></a>

Amazon SNS 使用**数据保护策略**选择要扫描的敏感数据，以及为了保护这些数据不被 Amazon SNS 主题交换而要采取的操作。要选择感兴趣的敏感数据，您可以使用[数据标识符](sns-message-data-protection-managed-data-identifiers.md)。Amazon SNS 消息数据保护功能随后使用机器学习和模式匹配来检测敏感数据。要对找到的数据标识符采取操作，您可以定义**审计**、**去身份识别**或**拒绝**操作。利用这些操作，您可以记录已找到（或未找到）的敏感数据，遮蔽或者去除敏感数据，或者拒绝消息传送。

![\[Amazon SNS 利用数据保护策略来管理和保护不同地区的敏感数据。 AWS 服务它显示了入站和出站消息的工作流程，详细说明了如何监控数据以及如何根据诸如审计、去标识化或拒绝数据传输之类的策略设置采取措施，以保护个人身份信息（PII）和受保护健康信息（PHI）等信息。\]](http://docs.aws.amazon.com/zh_cn/sns/latest/dg/images/message-data-protection-policies-overview.png)


## 数据保护策略采用什么结构？
<a name="overview-of-data-protection-policies"></a>

如下图所示，数据保护策略文档包含以下元素：
+ 文档顶部的可选策略范围信息
+ 一个或多个单独语句

每个语句都包含有关单个权限的信息。

![\[Amazon SNS 中数据保护策略的结构，说明该策略是如何由各种元素组成的，例如策略名称、描述、版本以及根据数据方向、标识符和相关主体指定审计、去标识化或拒绝等操作的多个语句。\]](http://docs.aws.amazon.com/zh_cn/sns/latest/dg/images/payload-policy-process.png)


每个 Amazon SNS 主题只能定义一个数据保护策略。数据保护策略可以有一个或多个拒绝或去身份识别语句，但只能有一个审计语句。

### 数据保护策略的 JSON 属性
<a name="data-protection-policy-json-properties"></a>

数据保护策略需要以下基本策略信息用于识别：
+ **Name**（名称）– 策略名称。
+ **描述**（可选）：策略描述。
+ **Version**（版本）– 策略语言版本。当前版本为 2021-06-01。
+ **Statement**（语句）– 指定数据保护策略操作的语句列表。

```
{
  "Name": "basicPII-protection",
  "Description": "Protect basic types of sensitive data",
  "Version": "2021-06-01",
  "Statement": [
        ...
  ]
}
```

### 策略语句的 JSON 属性
<a name="policy-statement-json-properties"></a>

策略语句设置数据保护操作的检测上下文。
+ **Sid**（可选）– 语句标识符。
+ **DataDirection**— 与 Amazon SNS 主题相关的入库（用于发布 API 请求）或出库（用于通知传送）。
+ **DataIdentifier**— Amazon SNS 主题应扫描的敏感数据。例如，姓名、地址或电话号码。
+ **主体** – 发布到该主题的 IAM 主体或订阅该主题的 IAM 主体。
+ **Operation**（操作）– Amazon SNS 主题在找到敏感数据后执行的后续操作，可以为 **Audit**（审计）、**De-identiyf**（去身份识别）（即遮蔽或去除）或者 **Deny**（拒绝）（即阻止）。

```
{
    "Sid": "basicPII-inbound-protection",
    "DataDirection": "Inbound",
    "Principal": ["*"],
    "DataIdentifier": [
        "arn:aws:dataprotection::aws:data-identifier/Name",
        "arn:aws:dataprotection::aws:data-identifier/PhoneNumber-US"
    ],
    "Operation": {
        ...
    }
}
```

### 策略语句操作的 JSON 属性
<a name="statement-operation-json-properties"></a>

策略语句设置以下数据保护操作之一。
+ [**Audit**](sns-message-data-protection-operations.md#statement-operation-json-properties-audit)（审计）– 发布指标并发现结果日志，而不中断消息发布或传输。
+ [**De-identify**](sns-message-data-protection-operations.md#statement-operation-json-properties-deidentify)（去身份识别）– 遮蔽或去除敏感数据而不中断消息发布。
+ [**Deny**](sns-message-data-protection-operations.md#statement-operation-json-properties-deny)（拒绝）– 阻止 Amazon SNS 发布请求或者使消息传输失败。

## 如何确定我的数据保护策略的 IAM 主体？
<a name="data-protection-policy-iam-principal-determined"></a>

消息数据保护功能使用两个与 Amazon SNS 交互的 IAM 主体。

1. **Publish API Principal**（发布 API 主体）（入站）– 调用 Amazon SNS `Publish` API 的经过身份验证的 IAM 主体。

1. **Subscription Principal**（订阅主体）（出站）– 在订阅创建期间调用 `Subscribe` API 的经过身份验证的 IAM 主体。

`SubscriptionPrincipal` 是正式发布的 Amazon SNS 订阅属性，可以从 `GetSubscriptionAttributes` API 检索。

```
{
  "Attributes": {
    "SubscriptionPrincipal": "arn:aws:iam::123456789012:user/NoNameAccess",
    "Owner": "123412341234",
    "RawMessageDelivery": "true",
    "TopicArn": "arn:aws:sns:us-east-1:123412341234:PII-data-topic",
    "Endpoint": "arn:aws:sqs:us-east-1:123456789012:NoNameAccess",
    "Protocol": "sqs",
    "PendingConfirmation": "false",
    "ConfirmationWasAuthenticated": "true",
    "SubscriptionArn": "arn:aws:sns:us-east-1:123412341234:PII-data-topic:5d8634ef-67ef-49eb-a824-4042b28d6f55"
  }
}
```

# Amazon SNS 中的数据保护策略操作
<a name="sns-message-data-protection-operations"></a>

**重要**  
从 2026 年 4 月 30 日起，Amazon SNS 消息数据保护将不再向新客户提供。有关替代方案的更多信息和指导，请参阅 [Amazon SNS 消息数据保护可用性变更](https://docs.aws.amazon.com/sns/latest/dg/sns-message-data-protection-availability-change.html)。

以下数据保护策略示例可用于审计和拒绝敏感数据。有关包含示例应用程序的完整教程，请参阅 [Introducing message data protection for Amazon SNS](https://aws.amazon.com/blogs/compute/introducing-message-data-protection-for-amazon-sns/)（Amazon SNS 消息数据保护简介）博客文章。

## 审计操作
<a name="statement-operation-json-properties-audit"></a>

**审计操作对**主题入站消息进行采样，并记录 AWS 目标中发现的敏感数据。采样率可以是 0-99 之间的整数。此操作需要以下类型的日志记录目标之一：

1. **FindingsDestination**— Amazon SNS 主题在有效负载中发现敏感数据时的记录目标。

1. **NoFindingsDestination**— 当 Amazon SNS 主题在有效负载中找不到敏感数据时的日志记录目标。

您可以在以下每种日志目标类型 AWS 服务 中使用以下内容：
+ **Amaz CloudWatch on Logs**（可选）— `LogGroup` 必须位于主题区域中，并且名称必须以 **/aws/vendedlogs/** 开头。
+ ** **（可选）– `DeliveryStream` 必须位于主题区域并且使用 **Direct PUT** 作为传输流的来源。有关其他详细信息，请参阅《Amazon Data Firehose 开发人员指南》**中的[来源、目标和名称](https://docs.aws.amazon.com/firehose/latest/dev/create-name.html)。
+ **Amazon S3**（可选）– Amazon S3 存储桶名称。[要使用启用了 SSE-KMS 加密的 Amazon S3 桶，需要执行额外操作](#flow-logs-s3-cmk-policy)。

```
{
  "Operation": {
    "Audit": {
      "SampleRate": "99",
      "FindingsDestination": {
            "CloudWatchLogs": {
                "LogGroup": "/aws/vendedlogs/log-group-name"
            },
            "Firehose": {
                "DeliveryStream": "delivery-stream-name"
            },
            "S3": {
                "Bucket": "bucket-name"
            }
      },
      "NoFindingsDestination": {
            "CloudWatchLogs": {
                "LogGroup": "/aws/vendedlogs/log-group-name"
            },
            "Firehose": {
                "DeliveryStream": "delivery-stream-name"
            },
            "S3": {
                "Bucket": "bucket-name"
            }
      }
    }
  }
}
```

### 指定日志目标时所需的权限
<a name="required-permissions-log-operations"></a>

在数据保护策略中指定日志记录目标时，对于调用 Amazon SNS `PutDataProtectionPolicy` API 或者带有 `--data-protection-policy` 参数的 `CreateTopic` API 的 IAM 主体，您必须向 IAM 身份策略添加以下权限。


| 审计目标 | IAM 权限 | 
| --- | --- | 
| 默认 | logs:CreateLogDelivery logs:GetLogDelivery logs:UpdateLogDelivery logs:DeleteLogDelivery logs:ListLogDeliveries  | 
| CloudWatchLogs | logs:PutResourcePolicy logs:DescribeResourcePolicies logs:DescribeLogGroups  | 
| Firehose | iam:CreateServiceLinkedRole firehose:TagDeliveryStream  | 
| S3 | s3:PutBucketPolicy s3:GetBucketPolicy [要使用启用了 SSE-KMS 加密的 Amazon S3 桶，需要执行额外操作](#flow-logs-s3-cmk-policy)。  | 

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogDelivery",
                "logs:GetLogDelivery",
                "logs:UpdateLogDelivery",
                "logs:DeleteLogDelivery",
                "logs:ListLogDeliveries"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:PutResourcePolicy",
                "logs:DescribeResourcePolicies",
                "logs:DescribeLogGroups"
            ],
            "Resource": [
                "arn:aws:logs:us-west-1:123456789012:SampleLogGroupName:*:*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iam:CreateServiceLinkedRole",
                "firehose:TagDeliveryStream"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutBucketPolicy",
                "s3:GetBucketPolicy"
            ],
            "Resource": [
                "arn:aws:s3:::bucket-name"
            ]
        }
    ]
}
```

------

#### 与 SSE-KMS 结合使用时必需的密钥策略
<a name="flow-logs-s3-cmk-policy"></a>

如果您使用 Amazon S3 存储桶作为日志目标，则可以通过使用 Amazon S3 托管密钥启用服务器端加密 (SSE-S3) 或使用 (SSE-KMS) 启用服务器端加密 (SSE-KMS) 来保护存储桶中的数据。 AWS KMS keys 有关详情，请参阅《Amazon S3 用户指南》中的[使用服务器端加密保护数据](https://docs.aws.amazon.com/AmazonS3/latest/userguide/serv-side-encryption.html)。

如果选择 SSE-S3，则不需要额外的配置。Amazon S3 处理加密密钥。

如果您选择 SSE-KMS，则必须使用客户托管密钥。您必须更新客户托管密钥的密钥策略，以便日志传输账户可以写入 S3 存储桶。有关与 SSE-KMS 一起使用的所需密钥策略的更多信息，请参阅《[亚马逊* CloudWatch 日志*用户指南》中的 Amazon S3 存储桶服务器端加密](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html#AWS-logs-SSE-KMS-S3)。

### 审计目标日志示例
<a name="data-protection-policy-audit-destination-log"></a>

在下例中，使用 `callerPrincipal` 来识别敏感内容的来源，并使用 `messageID` 作为参考来根据 `Publish` API 响应进行检查。

```
{
  "messageId": "34d9b400-c6dd-5444-820d-fbeb0f1f54cf",
  "auditTimestamp": "2022-05-12T2:10:44Z",
  "callerPrincipal": "arn:aws:iam::123412341234:role/Publisher",
  "resourceArn": "arn:aws:sns:us-east-1:123412341234:PII-data-topic",
  "dataIdentifiers": [
    {
      "name": "Name",
      "count": 1,
      "detections": [
        {
          "start": 1,
          "end": 2
        }
      ]
    },
    {
      "name": "PhoneNumber",
      "count": 2,
      "detections": [
        {
          "start": 3,
          "end": 4
        },
        {
          "start": 5,
          "end": 6
        }
      ]
    }
  ]
}
```

### 审计操作指标
<a name="data-protection-policy-audit-metrics"></a>

当审计操作指定`FindingsDestination`或`NoFindingsDestination`属性时，主题所有者还会收到 CloudWatch`MessagesWithFindings`和`MessagesWithNoFindings`指标。

![\[显示指定时间段内数据的审计示例。\]](http://docs.aws.amazon.com/zh_cn/sns/latest/dg/images/audit-operations-metrics.png)


## 去身份识别操作
<a name="statement-operation-json-properties-deidentify"></a>

**去身份识别**操作会遮蔽或去除所发布或已送达消息中的敏感数据。此操作既适用于入站消息，又适用于出站消息，需要以下类型的配置之一：
+ **MaskConfig**— 使用下表中支持的字符进行掩码。例如，ssn: `123-45-6789` 变成 ssn: `###########`。

  ```
  {
  "Operation": {
      "Deidentify": {
          "MaskConfig": {
              "MaskWithCharacter": "#"
            }
      }
  }
  ```    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/sns/latest/dg/sns-message-data-protection-operations.html)
+ **RedactConfig**— 通过完全删除数据来进行编辑。例如，ssn: `123-45-6789` 变成 ssn: ` `。

  ```
  {
  "Operation": {
      "Deidentify": {
          "RedactConfig": {}
      }
  }
  ```

对于入站消息，在审计操作之后会对敏感数据进行去身份识别处理，当整条消息全部为敏感数据时，`SNS:Publish` API 调用方会收到以下无效参数错误。

`Error code: AuthorizationError ...`

## 拒绝操作
<a name="statement-operation-json-properties-deny"></a>

如果消息包含敏感数据，**Deny**（拒绝）操作会中断 `Publish` API 请求，或者中断消息的传输。拒绝操作对象为空，因为它不需要额外配置。

```
"Operation": {
    "Deny": {}
}
```

在入站消息上，`SNS:Publish` API 调用方收到授权错误。

`Error code: AuthorizationError ...`

在出站消息上，Amazon SNS 主题不将消息传输到订阅。要跟踪未经授权的传输，请启用主题的[传输状态日志记录](sns-topic-attributes.md)。下面是传输状态日志示例：

```
{
    "notification": {
        "messageMD5Sum": "29638742ffb68b32cf56f42a79bcf16b",
        "messageId": "34d9b400-c6dd-5444-820d-fbeb0f1f54cf",
        "topicArn": "arn:aws:sns:us-east-1:123412341234:PII-data-topic",
        "timestamp": "2022-05-12T2:12:44Z"
    },
    "delivery": {
        "deliveryId": "98236591c-56aa-51ee-a5ed-0c7d43493170",
        "destination": "arn:aws:sqs:us-east-1:123456789012:NoNameAccess",
        "providerResponse": "The topic's data protection policy prohibits this message from being delivered to <subscription-arn>",
        "dwellTimeMs":20,
        "attempts":1,
        "statusCode": 403
    },
    "status": "FAILURE"
}
```

# Amazon SNS 数据保护策略示例
<a name="sns-message-data-protection-examples"></a>

**重要**  
从 2026 年 4 月 30 日起，Amazon SNS 消息数据保护将不再向新客户提供。有关替代方案的更多信息和指导，请参阅 [Amazon SNS 消息数据保护可用性变更](https://docs.aws.amazon.com/sns/latest/dg/sns-message-data-protection-availability-change.html)。

以下数据保护策略示例可用于审计和拒绝敏感数据。有关包含示例应用程序的完整教程，请参阅 [Introducing message data protection for Amazon SNS](https://aws.amazon.com/blogs/compute/introducing-message-data-protection-for-amazon-sns/)（Amazon SNS 消息数据保护简介）博客文章。

## 审计策略示例
<a name="sns-message-data-protection-audit-example"></a>

审计策略允许您审计多达 99% 的入站邮件，并将调查结果发送到[亚马逊 CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html)[和 Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)。[https://docs.aws.amazon.com/firehose/latest/dev/what-is-this-service.html](https://docs.aws.amazon.com/firehose/latest/dev/what-is-this-service.html)

例如，您可以创建审计策略，评估任何系统是否无意中发送或接收了敏感数据。如果您的审计结果表明系统将信用卡信息发送到了无需这些信息的系统，则可以实施数据保护策略来阻止传输此类数据。

以下示例通过查找信用卡号并将发现结果发送到 Lo CloudWatch gs、Firehose 和 Amazon S3 来审核通过该主题的 99% 的消息。

**数据保护策略**：

```
{
  "Name": "__example_data_protection_policy",
  "Description": "Example data protection policy",
  "Version": "2021-06-01",
  "Statement": [
    {
      "DataDirection": "Inbound",
      "Principal": ["*"],
      "DataIdentifier": [
        "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber"
      ],
      "Operation": {
        "Audit": {
          "SampleRate": "99",
          "FindingsDestination": {
            "CloudWatchLogs": {
              "LogGroup": "<example log name>"
            },
            "Firehose": {
              "DeliveryStream": "<example stream name>"
            },
            "S3": {
              "Bucket": "<example bucket name>"
            }
          }
        }
      }
    }
  ]
}
```

**审计结果格式示例**：

```
{
    "messageId": "...",
    "callerPrincipal": "arn:aws:sts::123456789012:assumed-role/ExampleRole",
    "resourceArn": "arn:aws:sns:us-east-1:123456789012:ExampleArn", 
    "dataIdentifiers": [
        {
            "name": "CreditCardNumber",
            "count": 1,
            "detections": [
                { "start": 1, "end": 2 }
            ]
        }
    ],
    "timestamp": "2021-04-20T00:33:40.241Z"
}
```

## 带有入站去身份识别遮蔽语句的策略示例
<a name="sns-message-data-protection-inbound-deidentify-mask-example"></a>

以下示例通过遮蔽消息内容中的敏感数据，阻止用户将带有 `CreditCardNumber` 的敏感消息发布到主题。

```
{
  "Name": "__example_data_protection_policy",
  "Description": "Example data protection policy",
  "Version": "2021-06-01",
  "Statement": [
    {
      "DataDirection": "Inbound",
      "Principal": [
        "arn:aws:iam::123456789012:user/ExampleUser"
      ],
      "DataIdentifier": [
        "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber"
      ],
      "Operation": {
        "Deidentify": {
          "MaskConfig": {
            "MaskWithCharacter": "#"
          }
        }
      }
    }
  ]
}
```

**入站去身份识别遮蔽结果示例：**

```
// original message
My credit card number is 4539894458086459

// delivered message
My credit card number is ################
```

## 带有入站去身份识别去除语句的策略示例
<a name="sns-message-data-protection-inbound-deidentify-redact-example"></a>

以下示例通过去除消息内容中的敏感数据，阻止用户将带有 `CreditCardNumber` 的敏感消息发布到主题。

```
{
  "Name": "__example_data_protection_policy",
  "Description": "Example data protection policy",
  "Version": "2021-06-01",
  "Statement": [
    {
      "DataDirection": "Inbound",
      "Principal": [
        "arn:aws:iam::123456789012:user/ExampleUser"
      ],
      "DataIdentifier": [
        "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber"
      ],
      "Operation": {
        "Deidentify": {
          "RedactConfig": {}
        }
      }
    }
  ]
}
```

**入站去身份识别去除结果示例：**

```
// original message
My credit card number is 4539894458086459

// delivered message
My credit card number is
```

## 带有出站去身份识别遮蔽语句的策略示例
<a name="sns-message-data-protection-outbound-deidentify-mask-example"></a>

以下示例通过遮蔽消息内容中的敏感数据，阻止用户使用 `CreditCardNumber` 接收消息。

```
{
  "Name": "__example_data_protection_policy",
  "Description": "Example data protection policy",
  "Version": "2021-06-01",
  "Statement": [
    {
      "DataDirection": "Outbound",
      "Principal": [
        "arn:aws:iam::123456789012:user/ExampleUser"
      ],
      "DataIdentifier": [
        "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber"
      ],
      "Operation": {
        "Deidentify": {
          "MaskConfig": {
            "MaskWithCharacter": "-"
          }
        }
      }
    }
  ]
}
```

**出站去身份识别遮蔽结果示例：**

```
// original message
My credit card number is 4539894458086459

// delivered message
My credit card number is ----------------
```

## 带有入站去身份识别去除语句的策略示例
<a name="sns-message-data-protection-outbound-deidentify-redact-example"></a>

以下示例通过去除消息内容中的敏感数据，阻止用户使用 `CreditCardNumber` 接收消息。

```
{
  "Name": "__example_data_protection_policy",
  "Description": "Example data protection policy",
  "Version": "2021-06-01",
  "Statement": [
    {
      "DataDirection": "Outbound",
      "Principal": [
        "arn:aws:iam::123456789012:user/ExampleUser"
      ],
      "DataIdentifier": [
        "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber"
      ],
      "Operation": {
        "Deidentify": {
          "RedactConfig": {}
        }
      }
    }
  ]
}
```

**出站去身份识别去除结果示例：**

```
// original message
My credit card number is 4539894458086459

// delivered message
My credit card number is
```

## 入站拒绝语句示例策略
<a name="sns-message-data-protection-inbound-deny-example"></a>

以下示例阻止用户将消息内容中带有 `CreditCardNumber` 的消息发布到主题。API 响应中被拒绝的负载的状态代码为“403 AuthorizationError”。

```
{
  "Name": "__example_data_protection_policy",
  "Description": "Example data protection policy",
  "Version": "2021-06-01",
  "Statement": [
    {
      "DataDirection": "Inbound",
      "Principal": [
        "arn:aws:iam::123456789012:user/ExampleUser"
      ],
      "DataIdentifier": [
        "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber"
      ],
      "Operation": {
        "Deny": {}
      }
    }
  ]
}
```

## 出站拒绝语句示例策略
<a name="sns-message-data-protection-outbound-deny-example"></a>

以下示例阻止一个 AWS 账户接收包含以下内容的消息`CreditCardNumber`。

```
{
  "Name": "__example_data_protection_policy",
  "Description": "Example data protection policy",
  "Version": "2021-06-01",
  "Statement": [
    {
      "DataDirection": "Outbound",
      "Principal": [
        "arn:aws:iam::123456789012:user/ExampleUser"
      ],
      "DataIdentifier": [
        "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber"
      ],
      "Operation": {
        "Deny": {}
      }
    }
  ]
}
```

**出站拒绝结果示例，已登录 Amazon CloudWatch：**

```
{
  "notification": {
    "messageMD5Sum": "2e8f58ff2eeed723b56b15493fbfb5a5",
    "messageId": "8747a956-ebf1-59da-b291-f2c2e4b87c9c",
    "topicArn": "arn:aws:sns:us-east-2:664555388960:test1",
    "timestamp": "2022-09-08 15:40:57.144"
  },
  "delivery": {
    "deliveryId": "6a422437-78cc-5171-ad64-7fa3778507aa",
    "destination": "arn:aws:sqs:us-east-2:664555388960:test",
    "providerResponse": "The topic's data protection policy prohibits this message from being delivered to <subscription arn>",
    "dwellTimeMs": 22,
    "attempts": 1,
    "statusCode": 403
  },
  "status": "FAILURE"
}
```

# 在 Amazon SNS 中创建数据保护策略
<a name="sns-message-data-protection-configure"></a>

**重要**  
从 2026 年 4 月 30 日起，Amazon SNS 消息数据保护将不再向新客户提供。有关替代方案的更多信息和指导，请参阅 [Amazon SNS 消息数据保护可用性变更](https://docs.aws.amazon.com/sns/latest/dg/sns-message-data-protection-availability-change.html)。

[数据保护策略](sns-message-data-protection-policies.md)通过审计、去身份识别（遮蔽或去除）和拒绝（阻止）敏感信息在应用程序或 AWS 服务之间传输，帮助您保护发布到 Amazon SNS 主题的数据。您可以使用 AWS API、 AWS CLI CloudFormation、或 AWS 管理控制台 在 Amazon SNS 中创建数据保护策略。每个 Amazon SNS 主题只能定义一个策略。每个数据保护策略可以有一个或多个去身份识别和拒绝语句，但只能有一个审计语句。

**Topics**
+ [使用 API](sns-message-data-protection-configure-api.md)
+ [使用 AWS CLI](sns-message-data-protection-configure-cli.md)
+ [使用 CloudFormation](sns-message-data-protection-configure-cfn.md)
+ [使用 AWS 管理控制台](sns-message-data-protection-configure-console.md)
+ [使用 AWS SDK](sns-message-data-protection-configure-sdk.md)

# 使用 API 在 Amazon SNS 中创建数据保护策略
<a name="sns-message-data-protection-configure-api"></a>

**重要**  
从 2026 年 4 月 30 日起，Amazon SNS 消息数据保护将不再向新客户提供。有关替代方案的更多信息和指导，请参阅 [Amazon SNS 消息数据保护可用性变更](https://docs.aws.amazon.com/sns/latest/dg/sns-message-data-protection-availability-change.html)。

一个 AWS 账户中 Amazon SNS 资源的数量和大小是有限的。有关更多信息，请参阅 [Amazon Simple Notification Service endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/sns.html)。

## 使用 API 创建数据保护策略
<a name="create-policies-api"></a>

使用 API 创建亚马逊 SNS 数据保护政策。 AWS 

**创建数据保护政策以及亚马逊 SNS 主题 (AWS API)**  
使用标准 Amazon SNS 主题的 `DataProtectionPolicy` 属性：
+ [https://docs.aws.amazon.com/sns/latest/api/API_CreateTopic.html](https://docs.aws.amazon.com/sns/latest/api/API_CreateTopic.html)

**为现有 Amazon SNS 主题 (AWS API) 检索或创建数据保护策略**  
调用下列一项操作：
+ [GetDataProtectionPolicy](https://docs.aws.amazon.com/sns/latest/api/API_GetDataProtectionPolicy.html)
+ [PutDataProtectionPolicy](https://docs.aws.amazon.com/sns/latest/api/API_PutDataProtectionPolicy.html)

# 使用 CLI 在 Amazon SNS 中创建数据保护策略
<a name="sns-message-data-protection-configure-cli"></a>

**重要**  
从 2026 年 4 月 30 日起，Amazon SNS 消息数据保护将不再向新客户提供。有关替代方案的更多信息和指导，请参阅 [Amazon SNS 消息数据保护可用性变更](https://docs.aws.amazon.com/sns/latest/dg/sns-message-data-protection-availability-change.html)。

一个 AWS 账户中 Amazon SNS 资源的数量和大小是有限的。有关更多信息，请参阅 [Amazon Simple Notification Service endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/sns.html)。

## 使用创建数据保护策略 AWS CLI
<a name="create-policies-cli"></a>

使用 AWS Command Line Interface创建 Amazon SNS 数据保护策略。

**与 Amazon SNS 主题一起创建数据保护策略 (AWS CLI)**  
使用此选项，与标准 Amazon SNS 主题一起创建新的数据保护策略：
+ [create-topic](https://docs.aws.amazon.com/cli/latest/reference/sns/create-topic.html)

**为现有 Amazon SNS 主题创建或检索数据保护策略 (AWS CLI)**  
调用下列一项操作：
+ [get-data-protection-policy](https://docs.aws.amazon.com/cli/latest/reference/sns/get-data-protection-policy.html)
+ [put-data-protection-policy](https://docs.aws.amazon.com/cli/latest/reference/sns/put-data-protection-policy.html)

# 使用在 Amazon SNS 中创建数据保护策略 CloudFormation
<a name="sns-message-data-protection-configure-cfn"></a>

**重要**  
从 2026 年 4 月 30 日起，Amazon SNS 消息数据保护将不再向新客户提供。有关替代方案的更多信息和指导，请参阅 [Amazon SNS 消息数据保护可用性变更](https://docs.aws.amazon.com/sns/latest/dg/sns-message-data-protection-availability-change.html)。

一个 AWS 账户中 Amazon SNS 资源的数量和大小是有限的。有关更多信息，请参阅 [Amazon Simple Notification Service endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/sns.html)。

## 创建数据保护策略 (CloudFormation)
<a name="create-policies-cfn"></a>

使用创建 Amazon SNS 数据保护政策。 CloudFormation

**与 Amazon SNS 主题一起创建数据保护策略 (CloudFormation)**  
使用此选项，与标准 Amazon SNS 主题一起创建新的数据保护策略：
+ [AWS::SNS::Topic](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sns-topic.html)

# 使用控制台在 Amazon SNS 中创建数据保护策略
<a name="sns-message-data-protection-configure-console"></a>

**重要**  
从 2026 年 4 月 30 日起，Amazon SNS 消息数据保护将不再向新客户提供。有关替代方案的更多信息和指导，请参阅 [Amazon SNS 消息数据保护可用性变更](https://docs.aws.amazon.com/sns/latest/dg/sns-message-data-protection-availability-change.html)。

一个 AWS 账户中 Amazon SNS 资源的数量和大小是有限的。有关更多信息，请参阅 [Amazon Simple Notification Service endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/sns.html)。

**与 Amazon SNS 主题一起创建数据保护策略（控制台）**  
使用此选项，与标准 Amazon SNS 主题一起创建新的数据保护策略。

1. 登录 [Amazon SNS 控制台](https://console.aws.amazon.com/sns/home)。

1. 选择一个主题或创建一个新主题。有关创建主题的详细信息，请参阅[创建 Amazon SNS 主题](sns-create-topic.md)。

1. 在 **Create topic**（创建主题）页面的 **Details**（详细信息）部分，选择 **Standard**（标准）。

   1. 输入主题的**名称**。

   1. （可选）输入主题的**显示名称**。

1. 展开 **Data protection policy**（数据保护策略）。

1. 选择一个 **Configuration mode**（配置模式）：
   + **Basic**（基本）– 使用简单菜单定义数据保护策略。
   + **Advanced**（高级）– 使用 JSON 定义自定义数据保护策略。

1. （可选）要创建您自己的**自定义数据标识符**，请展开**自定义数据标识符配置部分**，执行以下操作：

   1. 为自定义数据标识符输入唯一**名称**。自定义数据标识符名称支持字母数字、下划线（\$1）和连字符（-）等字符。最多支持 128 个字符。此名称不能与[托管式数据标识符](sns-message-data-protection-managed-data-identifiers.md)同名。有关自定义数据标识符限制的完整列表，请参阅[自定义数据标识符限制](sns-message-data-protection-custom-data-identifiers.md#custom-data-identifiers-limitations)。

   1. 输入自定义数据标识符的正则表达式 (RegEx)。 RegEx支持字母数字字符、 RegEx 保留字符和符号。 RegEx 最大长度为 200 个字符。如果太复杂，Amazon SNS 就会失败 API 调用。 RegEx 有关 RegEx限制的完整列表，请参阅[自定义数据标识符限制](sns-message-data-protection-custom-data-identifiers.md#custom-data-identifiers-limitations)。

   1. （可选）选择**添加自定义数据标识符**以根据需要添加其它数据标识符。每项数据保护策略最多支持 10 个自定义数据标识符。

1. 选择您要添加到数据保护策略中的语句。您可以将**审计**、**去身份识别**（遮蔽或去除）和**拒绝**（阻止）语句类型添加到同一数据保护策略中。

   1. **Add audit statement**（添加审计语句）– 配置要审计的敏感数据、要为该数据审计的消息百分比以及将审计日志发送到何处。
**注意**  
每个数据保护策略或主题仅允许使用一个审计语句。

      1. 选择 **data identifiers**（数据标识符）以定义要审计的敏感数据。

      1. 对于 **Audit sample rate**（审计采样率），输入要在其中审计敏感信息的消息百分比，最大值为 99%。

      1. 在 “**审计目标**” 中，选择 AWS 服务 要发送审计结果的目的地，然后为 AWS 服务 所使用的每个目标输入目标名称。您可以从以下 Amazon Web Services 中进行选择：
         + **Amazon CloudWatch** — CloudWatch Logs 是 AWS 标准的日志解决方案。使用 CloudWatch 日志，您可以使用 Logs Insights（[参见此处的示例](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax-examples.html)）执行日志分析，并创建指标和警报。 CloudWatch 日志是许多服务发布日志的地方，这使得使用一个解决方案可以更轻松地聚合所有日志。有关亚马逊的信息 CloudWatch，请参阅《[亚马逊 CloudWatch 用户指南》](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html)。
         + ****— Firehose 满足了实时直播到 Splunk 的需求，也满足了 OpenSearch Amazon Redshift 对进一步日志分析的需求。有关信息，请参阅[用户指南](https://docs.aws.amazon.com/firehose/latest/dev/what-is-this-service.html)。
         + **Amazon Simple Storage Service** – Amazon S3 是经济实惠的日志目标，可用于存档目的。您可能需要将日志保留数年。在这种情况下，您可以将日志放入 Amazon S3 中以节省成本。有关 Amazon Simple Storage Service 的信息，请参阅 [Amazon Simple Storage Service 用户指南](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)。

   1. **Add a de-identify statement**（添加去身份识别语句）– 配置要在消息中去身份识别的敏感数据（无论是遮蔽还是去除该数据），并且账户将停止传输该数据。

      1. 对于 **Data Identifiers**（数据标识符），选择要去身份识别的敏感数据。

      1. 在 “为其**定义此去身份化声明” 中，选择此去身份化声明适用的** AWS 账户或 IAM 委托人。您可以将其应用于**所有 AWS 账户**，也可以应用于使用** AWS 账户或 **IAM 实体的**特定**账户或 IAM 实体（账户根、角色 IDs 或用户） ARNs。分隔多个 IDs 或 ARNs 使用逗号 (,)。

         以下是受支持的 [IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) 主体：
         + **IAM account principals**（IAM 账户主体）– 例如 `arn:aws:iam::AWS-account-ID:root`。
         + **IAM role principals**（IAM 角色主体）– 例如 `arn:aws:iam::AWS-account-ID:role/role-name`。
         + **IAM use principals**（IAM 用户主体）– 例如 `arn:aws:iam::AWS-account-ID:user/user-name`。

      1. 对于 **De-identify Option**（去身份识别选项），请选择要如何对敏感数据去身份识别。支持以下选项：
         + **Redact**（去除）– 完全删除数据。例如，电子邮件 `classified@amazon.com` 将变为电子邮件 ` `。
         + **Mask**（遮蔽）– 使用单个字符替换数据。例如，电子邮件 `classified@amazon.com` 将变为电子邮件 `*********************`。

      1. （可选）根据需要继续添加去身份识别语句。

   1. **Add deny statement**（添加拒绝语句）– 配置要在您的主题中阻止传输哪些敏感数据，以及阻止哪些主体传输这些数据。

      1. 对于 **Data Direction**（数据方向），请选择拒绝语句的消息方向：
         + **Inbound messages**（入站消息）– 将此拒绝语句应用于发送到该主题的消息。
         + **Outbound messages**（出站消息）– 将此拒绝语句应用于主题传输到订阅端点的消息。

      1. 选择 **Data Identifiers**（数据标识符）以定义要拒绝的敏感数据。

      1. 选择应用到此拒绝语句的 **IAM principals**（IAM 主体）。您可以将其应用于使用** AWS 账户或 IAM 实体的所有账户 AWS 账户****、**特定**或 IAM 实体**（例如，账户根、角色 IDs 或用户） ARNs。分隔多个 IDs 或 ARNs 使用逗号 (,)。以下是受支持的 [IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) 主体：
         + **IAM account principals**（IAM 账户主体）– 例如 `arn:aws:iam::AWS-account-ID:root`。
         + **IAM role principals**（IAM 角色主体）– 例如 `arn:aws:iam::AWS-account-ID:role/role-name`。
         + **IAM use principals**（IAM 用户主体）– 例如 `arn:aws:iam::AWS-account-ID:user/user-name`。

      1. （可选）根据需要继续添加拒绝语句。

# 使用 SDK 创建 Amazon SNS 数据保护策略以保护消息数据
<a name="sns-message-data-protection-configure-sdk"></a>

**重要**  
从 2026 年 4 月 30 日起，Amazon SNS 消息数据保护将不再向新客户提供。有关替代方案的更多信息和指导，请参阅 [Amazon SNS 消息数据保护可用性变更](https://docs.aws.amazon.com/sns/latest/dg/sns-message-data-protection-availability-change.html)。

一个 AWS 账户中 Amazon SNS 资源的数量和大小是有限的。有关更多信息，请参阅 [Amazon Simple Notification Service endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/sns.html)。

## 使用 AWS SDK 创建数据保护策略
<a name="create-policies-sdk"></a>

使用软件开发工具包创建 Amazon SNS 数据保护政策。 AWS 

**将数据保护策略与 Amazon SNS 主题 (AWS SDK) 一起创建**  
使用以下选项，与标准 Amazon SNS 主题一起创建新的数据保护策略：

------
#### [ Java ]

```
/**
 * For information regarding CreateTopic see this documentation topic:
 *
 * https://docs.aws.amazon.com/code-samples/latest/catalog/javav2-sns-src-main-java-com-example-sns-CreateTopic.java.html
 */

public static String createSNSTopicWithDataProtectionPolicy(SnsClient snsClient, String topicName, String dataProtectionPolicy) {

    try {
        CreateTopicRequest request = CreateTopicRequest.builder()
                .name(topicName)
                .dataProtectionPolicy(dataProtectionPolicy)
                .build();

        CreateTopicResponse result = snsClient.createTopic(request);
        return result.topicArn();
    } catch (SnsException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
    return "";
}
```

------
#### [ JavaScript ]

```
// Import required AWS SDK clients and commands for Node.js
import {CreateTopicCommand } from "@aws-sdk/client-sns";
import {snsClient } from "./libs/snsClient.js";

// Set the parameters
const params = { Name: "TOPIC_NAME", DataProtectionPolicy: "DATA_PROTECTION_POLICY" };

const run = async () => {
  try {
    const data = await snsClient.send(new CreateTopicCommand(params));
    console.log("Success.",  data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err.stack);
  }
};
run();
```

------

**为现有 Amazon SNS 主题 (AWS SDK) 创建或检索数据保护策略**  
使用以下选项，与标准 Amazon SNS 主题一起创建新的数据保护策略或检索数据保护策略：

------
#### [ Java ]

```
public static void putDataProtectionPolicy(SnsClient snsClient, String topicName, String dataProtectionPolicy) {

    try {
        PutDataProtectionPolicyRequest request = PutDataProtectionPolicyRequest.builder()
                .resourceArn(topicName)
                .dataProtectionPolicy(dataProtectionPolicy)
                .build();

        PutDataProtectionPolicyResponse result = snsClient.putDataProtectionPolicy(request);
        System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode() 
                + "\n\nTopic " + request.resourceArn()
                + " DataProtectionPolicy " + request.dataProtectionPolicy());
    } catch (SnsException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
}


public static void getDataProtectionPolicy(SnsClient snsClient, String topicName) {

    try {
        GetDataProtectionPolicyRequest request = GetDataProtectionPolicyRequest.builder()
                .resourceArn(topicName)
                .build();
        
        GetDataProtectionPolicyResponse result = snsClient.getDataProtectionPolicy(request);
        
        System.out.println("\n\nStatus is " + result.sdkHttpResponse().statusCode() 
        + "\n\nDataProtectionPolicy: \n\n" + result.dataProtectionPolicy());
    } catch (SnsException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
}
```

------
#### [ JavaScript ]

```
// Import required AWS SDK clients and commands for Node.js
import {PutDataProtectionPolicyCommand, GetDataProtectionPolicyCommand } from "@aws-sdk/client-sns";
import {snsClient } from "./libs/snsClient.js";

// Set the parameters
const putParams = { ResourceArn: "TOPIC_ARN", DataProtectionPolicy: "DATA_PROTECTION_POLICY" };

const runPut = async () => {
  try {
    const data = await snsClient.send(new PutDataProtectionPolicyCommand(putParams));
    console.log("Success.",  data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err.stack);
  }
};
runPut();

// Set the parameters
const getParams = { ResourceArn: "TOPIC_ARN" };

const runGet = async () => {
  try {
    const data = await snsClient.send(new GetDataProtectionPolicyCommand(getParams));
    console.log("Success.",  data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err.stack);
  }
};
runGet();
```

------

# 在 Amazon SNS 中删除数据保护策略
<a name="sns-message-data-protection-delete"></a>

**重要**  
从 2026 年 4 月 30 日起，Amazon SNS 消息数据保护将不再向新客户提供。有关替代方案的更多信息和指导，请参阅 [Amazon SNS 消息数据保护可用性变更](https://docs.aws.amazon.com/sns/latest/dg/sns-message-data-protection-availability-change.html)。

您可以使用 AWS API、、** AWS CLI或删除** Amazon SNS 数据保护策略。 CloudFormation AWS 管理控制台

有关 Amazon SNS 数据保护策略的一般信息，请参阅 [了解 Amazon SNS 数据保护策略](sns-message-data-protection-policies.md)。

 AWS 账户中 Amazon SNS 数据保护策略资源的数量和大小是有限的。有关更多信息，请参阅《 AWS 一般参考》中的 [Amazon SNS API 节流](https://docs.aws.amazon.com/general/latest/gr/sns.html)。

## 使用控制台删除数据保护策略
<a name="sns-delete-data-protection-policy"></a>

**使用控制台删除托管数据保护策略**

1. 登录 [Amazon SNS 控制台](https://console.aws.amazon.com/sns/home)。

1. 选择包含您要删除的数据保护策略的主题。

1. 选择**编辑**。

1. 展开 **Data protection policy**（数据保护策略）部分。

1. 在您要删除的数据保护策略语句旁边，选择 **Remove**（删除）。

1. 选择**保存更改**。

## 使用空 JSON 字符串删除数据保护策略
<a name="sns-message-data-protection-remove-example-json"></a>

您可以通过将数据保护策略更新为空 JSON 字符串来删除数据保护策略。

## 使用删除数据保护策略 AWS CLI
<a name="sns-message-data-protection-remove-example-cli"></a>

您可以使用 AWS CLI删除数据保护策略。

`//aws sns put-data-protection-policy --resource-arn topic-arn --data-protection-policy ""`