main/keyring/
multi_keyring.rs

1// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::test_utils;
5use aws_db_esdk::dynamodb::types::DynamoDbTableEncryptionConfig;
6use aws_db_esdk::intercept::DbEsdkInterceptor;
7use aws_db_esdk::material_providers::client as mpl_client;
8use aws_db_esdk::material_providers::types::material_providers_config::MaterialProvidersConfig;
9use aws_db_esdk::material_providers::types::AesWrappingAlg;
10use aws_db_esdk::CryptoAction;
11use aws_db_esdk::DynamoDbTablesEncryptionConfig;
12use aws_sdk_dynamodb::types::AttributeValue;
13use std::collections::HashMap;
14
15/*
16 This example sets up DynamoDb Encryption for the AWS SDK client
17 using the multi-keyring. This keyring takes in multiple keyrings
18 and uses them to encrypt and decrypt data. Data encrypted with
19 a multi-keyring can be decrypted with any of its component keyrings.
20
21 For more information on multi-keyrings, see
22 https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-multi-keyring.html
23
24 This example creates a new multi-keyring consisting of an AWS KMS
25 keyring (labeled the "generator keyring") and a raw AES keyring
26 (labeled as the only "child keyring"). It encrypts a test item
27 using the multi-keyring and puts the encrypted item to the provided
28 DynamoDb table. Then, it gets the item from the table and decrypts it
29 using only the raw AES keyring.
30
31 This example takes in an `aesKeyBytes` parameter. This parameter
32 should be a ByteBuffer representing a 256-bit AES key. If this example
33 is run through the class' main method, it will create a new key.
34 In practice, users of this library should not randomly generate a key,
35 and should instead retrieve an existing key from a secure key
36 management system (e.g. an HSM).
37
38 Running this example requires access to the DDB Table whose name
39 is provided in CLI arguments.
40 This table must be configured with the following
41 primary key configuration:
42   - Partition key is named "partition_key" with type (S)
43   - Sort key is named "sort_key" with type (S)
44*/
45
46pub async fn put_item_get_item() -> Result<(), crate::BoxError> {
47    let ddb_table_name = test_utils::TEST_DDB_TABLE_NAME;
48    let key_arn = test_utils::TEST_KMS_KEY_ID;
49    let aes_key_bytes = generate_aes_key_bytes();
50
51    // 1. Create the raw AES keyring.
52    let mpl_config = MaterialProvidersConfig::builder().build()?;
53    let mpl = mpl_client::Client::from_conf(mpl_config)?;
54    let raw_aes_keyring = mpl
55        .create_raw_aes_keyring()
56        .key_name("my-aes-key-name")
57        .key_namespace("my-key-namespace")
58        .wrapping_key(aes_key_bytes)
59        .wrapping_alg(AesWrappingAlg::AlgAes256GcmIv12Tag16)
60        .send()
61        .await?;
62
63    // 2. Create the AWS KMS keyring.
64    //    We create a MRK multi keyring, as this interface also supports
65    //    single-region KMS keys (standard KMS keys),
66    //    and creates the KMS client for us automatically.
67    let aws_kms_mrk_multi_keyring = mpl
68        .create_aws_kms_mrk_multi_keyring()
69        .generator(key_arn)
70        .send()
71        .await?;
72
73    // 3. Create the multi-keyring.
74    //    We will label the AWS KMS keyring as the generator and the raw AES keyring as the
75    //        only child keyring.
76    //    You must provide a generator keyring to encrypt data.
77    //    You may provide additional child keyrings. Each child keyring will be able to
78    //        decrypt data encrypted with the multi-keyring on its own. It does not need
79    //        knowledge of any other child keyrings or the generator keyring to decrypt.
80
81    let multi_keyring = mpl
82        .create_multi_keyring()
83        .generator(aws_kms_mrk_multi_keyring)
84        .child_keyrings(vec![raw_aes_keyring.clone()])
85        .send()
86        .await?;
87
88    // 4. Configure which attributes are encrypted and/or signed when writing new items.
89    //    For each attribute that may exist on the items we plan to write to our DynamoDbTable,
90    //    we must explicitly configure how they should be treated during item encryption:
91    //      - ENCRYPT_AND_SIGN: The attribute is encrypted and included in the signature
92    //      - SIGN_ONLY: The attribute not encrypted, but is still included in the signature
93    //      - DO_NOTHING: The attribute is not encrypted and not included in the signature
94    let attribute_actions_on_encrypt = HashMap::from([
95        ("partition_key".to_string(), CryptoAction::SignOnly), // Our partition attribute must be SIGN_ONLY
96        ("sort_key".to_string(), CryptoAction::SignOnly), // Our sort attribute must be SIGN_ONLY
97        ("sensitive_data".to_string(), CryptoAction::EncryptAndSign),
98    ]);
99
100    // 5. Configure which attributes we expect to be included in the signature
101    //    when reading items. There are two options for configuring this:
102    //
103    //    - (Recommended) Configure `allowedUnsignedAttributesPrefix`:
104    //      When defining your DynamoDb schema and deciding on attribute names,
105    //      choose a distinguishing prefix (such as ":") for all attributes that
106    //      you do not want to include in the signature.
107    //      This has two main benefits:
108    //      - It is easier to reason about the security and authenticity of data within your item
109    //        when all unauthenticated data is easily distinguishable by their attribute name.
110    //      - If you need to add new unauthenticated attributes in the future,
111    //        you can easily make the corresponding update to your `attributeActionsOnEncrypt`
112    //        and immediately start writing to that new attribute, without
113    //        any other configuration update needed.
114    //      Once you configure this field, it is not safe to update it.
115    //
116    //    - Configure `allowedUnsignedAttributes`: You may also explicitly list
117    //      a set of attributes that should be considered unauthenticated when encountered
118    //      on read. Be careful if you use this configuration. Do not remove an attribute
119    //      name from this configuration, even if you are no longer writing with that attribute,
120    //      as old items may still include this attribute, and our configuration needs to know
121    //      to continue to exclude this attribute from the signature scope.
122    //      If you add new attribute names to this field, you must first deploy the update to this
123    //      field to all readers in your host fleet before deploying the update to start writing
124    //      with that new attribute.
125    //
126    //   For this example, we currently authenticate all attributes. To make it easier to
127    //   add unauthenticated attributes in the future, we define a prefix ":" for such attributes.
128    const UNSIGNED_ATTR_PREFIX: &str = ":";
129
130    // 6. Create the DynamoDb Encryption configuration for the table we will be writing to.
131    //    Note that this example creates one config/client combination for PUT, and another
132    //        for GET. The PUT config uses the multi-keyring, while the GET config uses the
133    //        raw AES keyring. This is solely done to demonstrate that a keyring included as
134    //        a child of a multi-keyring can be used to decrypt data on its own.
135    let table_config = DynamoDbTableEncryptionConfig::builder()
136        .logical_table_name(ddb_table_name)
137        .partition_key_name("partition_key")
138        .sort_key_name("sort_key")
139        .attribute_actions_on_encrypt(attribute_actions_on_encrypt.clone())
140        .keyring(multi_keyring)
141        .allowed_unsigned_attribute_prefix(UNSIGNED_ATTR_PREFIX)
142        .build()?;
143
144    let table_configs = DynamoDbTablesEncryptionConfig::builder()
145        .table_encryption_configs(HashMap::from([(ddb_table_name.to_string(), table_config)]))
146        .build()?;
147
148    // 7. Create a new AWS SDK DynamoDb client using the config above
149    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
150    let dynamo_config = aws_sdk_dynamodb::config::Builder::from(&sdk_config)
151        .interceptor(DbEsdkInterceptor::new(table_configs)?)
152        .build();
153    let ddb = aws_sdk_dynamodb::Client::from_conf(dynamo_config);
154
155    // 8. Put an item into our table using the above client.
156    //    Before the item gets sent to DynamoDb, it will be encrypted
157    //    client-side using the multi-keyring.
158    //    The item will be encrypted with all wrapping keys in the keyring,
159    //    so that it can be decrypted with any one of the keys.
160    let item = HashMap::from([
161        (
162            "partition_key".to_string(),
163            AttributeValue::S("multiKeyringItem".to_string()),
164        ),
165        ("sort_key".to_string(), AttributeValue::N("0".to_string())),
166        (
167            "sensitive_data".to_string(),
168            AttributeValue::S("encrypt and sign me!".to_string()),
169        ),
170    ]);
171
172    ddb.put_item()
173        .table_name(ddb_table_name)
174        .set_item(Some(item.clone()))
175        .send()
176        .await?;
177
178    // 9. Get the item back from our table using the above client.
179    //     The client will decrypt the item client-side using the AWS KMS
180    //     keyring, and return back the original item.
181    //     Since the generator key is the first available key in the keyring,
182    //     that is the key that will be used to decrypt this item.
183    let key_to_get = HashMap::from([
184        (
185            "partition_key".to_string(),
186            AttributeValue::S("multiKeyringItem".to_string()),
187        ),
188        ("sort_key".to_string(), AttributeValue::N("0".to_string())),
189    ]);
190
191    let resp = ddb
192        .get_item()
193        .table_name(ddb_table_name)
194        .set_key(Some(key_to_get.clone()))
195        .consistent_read(true)
196        .send()
197        .await?;
198
199    assert_eq!(resp.item, Some(item.clone()));
200
201    // 10. Create a new config and client with only the raw AES keyring to GET the item
202    //     This is the same setup as above, except the config uses the `rawAesKeyring`.
203    let only_aes_table_config = DynamoDbTableEncryptionConfig::builder()
204        .logical_table_name(ddb_table_name)
205        .partition_key_name("partition_key")
206        .sort_key_name("sort_key")
207        .attribute_actions_on_encrypt(attribute_actions_on_encrypt)
208        .keyring(raw_aes_keyring)
209        .allowed_unsigned_attribute_prefix(UNSIGNED_ATTR_PREFIX)
210        .build()?;
211
212    let only_aes_table_configs = DynamoDbTablesEncryptionConfig::builder()
213        .table_encryption_configs(HashMap::from([(
214            ddb_table_name.to_string(),
215            only_aes_table_config,
216        )]))
217        .build()?;
218
219    let only_aes_dynamo_config = aws_sdk_dynamodb::config::Builder::from(&sdk_config)
220        .interceptor(DbEsdkInterceptor::new(only_aes_table_configs)?)
221        .build();
222    let only_aes_ddb = aws_sdk_dynamodb::Client::from_conf(only_aes_dynamo_config);
223
224    // 11. Get the item back from our table using the client
225    //     configured with only the raw AES keyring.
226    //     The client will decrypt the item client-side using the raw
227    //     AES keyring, and return back the original item.
228    let resp = only_aes_ddb
229        .get_item()
230        .table_name(ddb_table_name)
231        .set_key(Some(key_to_get.clone()))
232        .consistent_read(true)
233        .send()
234        .await?;
235
236    assert_eq!(resp.item, Some(item.clone()));
237
238    println!("multi_keyring successful.");
239    Ok(())
240}
241
242fn generate_aes_key_bytes() -> Vec<u8> {
243    // This example returns a static key.
244    // In practice, you should not generate this key in your code, and should instead
245    //     retrieve this key from a secure key management system (e.g. HSM).
246    // This key is created here for example purposes only and should not be used for any other purpose.
247    vec![
248        1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
249        25, 26, 27, 28, 29, 30, 31, 32,
250    ]
251}