|
| 1 | +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +""" |
| 4 | +Example for using an EncryptedClient to put and get an encrypted item. |
| 5 | +
|
| 6 | +Running this example requires access to the DDB Table whose name |
| 7 | +is provided in the function arguments. |
| 8 | +This table must be configured with the following |
| 9 | +primary key configuration: |
| 10 | +- Partition key is named "partition_key" with type (S) |
| 11 | +- Sort key is named "sort_key" with type (N) |
| 12 | +""" |
| 13 | + |
| 14 | +import boto3 |
| 15 | +from aws_cryptographic_material_providers.mpl import AwsCryptographicMaterialProviders |
| 16 | +from aws_cryptographic_material_providers.mpl.config import MaterialProvidersConfig |
| 17 | +from aws_cryptographic_material_providers.mpl.models import ( |
| 18 | + CreateAwsKmsMrkMultiKeyringInput, |
| 19 | + DBEAlgorithmSuiteId, |
| 20 | +) |
| 21 | +from aws_cryptographic_material_providers.mpl.references import IKeyring |
| 22 | +from aws_dbesdk_dynamodb.encrypted.client import EncryptedClient |
| 23 | +from aws_dbesdk_dynamodb.structures.dynamodb import ( |
| 24 | + DynamoDbTableEncryptionConfig, |
| 25 | + DynamoDbTablesEncryptionConfig, |
| 26 | +) |
| 27 | +from aws_dbesdk_dynamodb.structures.structured_encryption import ( |
| 28 | + CryptoAction, |
| 29 | +) |
| 30 | + |
| 31 | + |
| 32 | +def encrypted_client_put_get_example( |
| 33 | + kms_key_id: str, |
| 34 | + dynamodb_table_name: str, |
| 35 | +): |
| 36 | + """Use an EncryptedClient to put and get an encrypted item.""" |
| 37 | + # 1. Create a Keyring. This Keyring will be responsible for protecting the data keys that protect your data. |
| 38 | + # For this example, we will create a AWS KMS Keyring with the AWS KMS Key we want to use. |
| 39 | + # We will use the `CreateMrkMultiKeyring` method to create this keyring, |
| 40 | + # as it will correctly handle both single region and Multi-Region KMS Keys. |
| 41 | + mat_prov: AwsCryptographicMaterialProviders = AwsCryptographicMaterialProviders(config=MaterialProvidersConfig()) |
| 42 | + kms_mrk_multi_keyring_input: CreateAwsKmsMrkMultiKeyringInput = CreateAwsKmsMrkMultiKeyringInput( |
| 43 | + generator=kms_key_id, |
| 44 | + ) |
| 45 | + kms_mrk_multi_keyring: IKeyring = mat_prov.create_aws_kms_mrk_multi_keyring(input=kms_mrk_multi_keyring_input) |
| 46 | + |
| 47 | + # 2. Configure which attributes are encrypted and/or signed when writing new items. |
| 48 | + # For each attribute that may exist on the items we plan to write to our DynamoDbTable, |
| 49 | + # we must explicitly configure how they should be treated during item encryption: |
| 50 | + # - ENCRYPT_AND_SIGN: The attribute is encrypted and included in the signature |
| 51 | + # - SIGN_ONLY: The attribute not encrypted, but is still included in the signature |
| 52 | + # - DO_NOTHING: The attribute is not encrypted and not included in the signature |
| 53 | + attribute_actions_on_encrypt = { |
| 54 | + "partition_key": CryptoAction.SIGN_ONLY, |
| 55 | + "sort_key": CryptoAction.SIGN_ONLY, |
| 56 | + "attribute1": CryptoAction.ENCRYPT_AND_SIGN, |
| 57 | + "attribute2": CryptoAction.SIGN_ONLY, |
| 58 | + ":attribute3": CryptoAction.DO_NOTHING, |
| 59 | + } |
| 60 | + |
| 61 | + # 3. Configure which attributes we expect to be included in the signature |
| 62 | + # when reading items. There are two options for configuring this: |
| 63 | + # |
| 64 | + # - (Recommended) Configure `allowedUnsignedAttributesPrefix`: |
| 65 | + # When defining your DynamoDb schema and deciding on attribute names, |
| 66 | + # choose a distinguishing prefix (such as ":") for all attributes that |
| 67 | + # you do not want to include in the signature. |
| 68 | + # This has two main benefits: |
| 69 | + # - It is easier to reason about the security and authenticity of data within your item |
| 70 | + # when all unauthenticated data is easily distinguishable by their attribute name. |
| 71 | + # - If you need to add new unauthenticated attributes in the future, |
| 72 | + # you can easily make the corresponding update to your `attributeActionsOnEncrypt` |
| 73 | + # and immediately start writing to that new attribute, without |
| 74 | + # any other configuration update needed. |
| 75 | + # Once you configure this field, it is not safe to update it. |
| 76 | + # |
| 77 | + # - Configure `allowedUnsignedAttributes`: You may also explicitly list |
| 78 | + # a set of attributes that should be considered unauthenticated when encountered |
| 79 | + # on read. Be careful if you use this configuration. Do not remove an attribute |
| 80 | + # name from this configuration, even if you are no longer writing with that attribute, |
| 81 | + # as old items may still include this attribute, and our configuration needs to know |
| 82 | + # to continue to exclude this attribute from the signature scope. |
| 83 | + # If you add new attribute names to this field, you must first deploy the update to this |
| 84 | + # field to all readers in your host fleet before deploying the update to start writing |
| 85 | + # with that new attribute. |
| 86 | + # |
| 87 | + # For this example, we have designed our DynamoDb table such that any attribute name with |
| 88 | + # the ":" prefix should be considered unauthenticated. |
| 89 | + unsignAttrPrefix: str = ":" |
| 90 | + |
| 91 | + # 4. Create the DynamoDb Encryption configuration for the table we will be writing to. |
| 92 | + table_configs = {} |
| 93 | + table_config = DynamoDbTableEncryptionConfig( |
| 94 | + logical_table_name=dynamodb_table_name, |
| 95 | + partition_key_name="partition_key", |
| 96 | + sort_key_name="sort_key", |
| 97 | + attribute_actions_on_encrypt=attribute_actions_on_encrypt, |
| 98 | + keyring=kms_mrk_multi_keyring, |
| 99 | + allowed_unsigned_attribute_prefix=unsignAttrPrefix, |
| 100 | + # Specifying an algorithm suite is not required, |
| 101 | + # but is done here to demonstrate how to do so. |
| 102 | + # We suggest using the |
| 103 | + # `ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384` suite, |
| 104 | + # which includes AES-GCM with key derivation, signing, and key commitment. |
| 105 | + # This is also the default algorithm suite if one is not specified in this config. |
| 106 | + # For more information on supported algorithm suites, see: |
| 107 | + # https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/supported-algorithms.html |
| 108 | + algorithm_suite_id=DBEAlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384, |
| 109 | + ) |
| 110 | + table_configs[dynamodb_table_name] = table_config |
| 111 | + tables_config = DynamoDbTablesEncryptionConfig(table_encryption_configs=table_configs) |
| 112 | + |
| 113 | + # 5. Create the EncryptedClient |
| 114 | + encrypted_client = EncryptedClient( |
| 115 | + client=boto3.client("dynamodb"), |
| 116 | + encryption_config=tables_config, |
| 117 | + ) |
| 118 | + |
| 119 | + # 6. Put an item into our table using the above client. |
| 120 | + # Before the item gets sent to DynamoDb, it will be encrypted |
| 121 | + # client-side, according to our configuration. |
| 122 | + item_to_encrypt = { |
| 123 | + "partition_key": {"S": "BasicPutGetExample"}, |
| 124 | + "sort_key": {"N": "0"}, |
| 125 | + "attribute1": {"S": "encrypt and sign me!"}, |
| 126 | + "attribute2": {"S": "sign me!"}, |
| 127 | + ":attribute3": {"S": "ignore me!"}, |
| 128 | + } |
| 129 | + |
| 130 | + put_item_request = { |
| 131 | + "TableName": dynamodb_table_name, |
| 132 | + "Item": item_to_encrypt, |
| 133 | + } |
| 134 | + |
| 135 | + put_item_response = encrypted_client.put_item(**put_item_request) |
| 136 | + |
| 137 | + # Demonstrate that PutItem succeeded |
| 138 | + assert put_item_response["ResponseMetadata"]["HTTPStatusCode"] == 200 |
| 139 | + |
| 140 | + # 7. Get the item back from our table using the same client. |
| 141 | + # The client will decrypt the item client-side, and return |
| 142 | + # back the original item. |
| 143 | + key_to_get = {"partition_key": {"S": "BasicPutGetExample"}, "sort_key": {"N": "0"}} |
| 144 | + |
| 145 | + get_item_request = {"TableName": dynamodb_table_name, "Key": key_to_get} |
| 146 | + |
| 147 | + get_item_response = encrypted_client.get_item(**get_item_request) |
| 148 | + |
| 149 | + # Demonstrate that GetItem succeeded and returned the decrypted item |
| 150 | + assert get_item_response["ResponseMetadata"]["HTTPStatusCode"] == 200 |
| 151 | + assert get_item_response["Item"] == item_to_encrypt |
| 152 | + |
| 153 | + # 8. Clean up the item we put into the table by deleting it. |
| 154 | + delete_item_request = {"TableName": dynamodb_table_name, "Key": key_to_get} |
| 155 | + delete_item_response = encrypted_client.delete_item(**delete_item_request) |
| 156 | + |
| 157 | + # Demonstrate that DeleteItem succeeded |
| 158 | + assert delete_item_response["ResponseMetadata"]["HTTPStatusCode"] == 200 |
| 159 | + get_item_response = encrypted_client.get_item(**get_item_request) |
| 160 | + assert "Item" not in get_item_response |
0 commit comments