Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 8784720

Browse files
committedSep 20, 2024··
m
1 parent a7c313f commit 8784720

14 files changed

+1180
-981
lines changed
 

‎DynamoDbEncryption/runtimes/rust/src/bin/example/basic_get_put_example.rs

Lines changed: 155 additions & 135 deletions
Large diffs are not rendered by default.

‎DynamoDbEncryption/runtimes/rust/src/bin/example/create_keystore_key.rs

Lines changed: 43 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2,51 +2,50 @@
22
// SPDX-License-Identifier: Apache-2.0
33

44
use crate::test_utils;
5+
use db_esdk::aws_cryptography_keyStore::client as keystore_client;
56
use db_esdk::aws_cryptography_keyStore::types::key_store_config::KeyStoreConfig;
67
use db_esdk::aws_cryptography_keyStore::types::KmsConfiguration;
7-
use db_esdk::aws_cryptography_keyStore::client as keystore_client;
88

99
/*
10-
The Hierarchical Keyring Example and Searchable Encryption Examples
11-
rely on the existence of a DDB-backed key store with pre-existing
12-
branch key material or beacon key material.
13-
14-
See the "Create KeyStore Table Example" for how to first set up
15-
the DDB Table that will back this KeyStore.
16-
17-
This example demonstrates configuring a KeyStore and then
18-
using a helper method to create a branch key and beacon key
19-
that share the same Id, then return that Id.
20-
We will always create a new beacon key alongside a new branch key,
21-
even if you are not using searchable encryption.
22-
23-
This key creation should occur within your control plane.
24-
*/
25-
pub async fn keystore_create_key() -> String
26-
{
27-
let key_store_table_name = test_utils::TEST_KEYSTORE_NAME;
28-
let logical_key_store_name = test_utils::TEST_LOGICAL_KEYSTORE_NAME;
29-
let kms_key_arn = test_utils::TEST_KEYSTORE_KMS_KEY_ID;
30-
31-
// 1. Configure your KeyStore resource.
32-
// This SHOULD be the same configuration that was used to create the DDB table
33-
// in the "Create KeyStore Table Example".
34-
let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
35-
let key_store_config = KeyStoreConfig::builder()
36-
.kms_client(aws_sdk_kms::Client::new(&sdk_config))
37-
.ddb_client(aws_sdk_dynamodb::Client::new(&sdk_config))
38-
.ddb_table_name(key_store_table_name)
39-
.logical_key_store_name(logical_key_store_name)
40-
.kms_configuration(KmsConfiguration::KmsKeyArn(kms_key_arn.to_string()))
41-
.build()
42-
.unwrap();
43-
44-
let keystore = keystore_client::Client::from_conf(key_store_config).unwrap();
45-
46-
// 2. Create a new branch key and beacon key in our KeyStore.
47-
// Both the branch key and the beacon key will share an Id.
48-
// This creation is eventually consistent.
49-
50-
let new_key = keystore.create_key().send().await.unwrap();
51-
return new_key.branch_key_identifier.unwrap();
52-
}
10+
The Hierarchical Keyring Example and Searchable Encryption Examples
11+
rely on the existence of a DDB-backed key store with pre-existing
12+
branch key material or beacon key material.
13+
14+
See the "Create KeyStore Table Example" for how to first set up
15+
the DDB Table that will back this KeyStore.
16+
17+
This example demonstrates configuring a KeyStore and then
18+
using a helper method to create a branch key and beacon key
19+
that share the same Id, then return that Id.
20+
We will always create a new beacon key alongside a new branch key,
21+
even if you are not using searchable encryption.
22+
23+
This key creation should occur within your control plane.
24+
*/
25+
pub async fn keystore_create_key() -> String {
26+
let key_store_table_name = test_utils::TEST_KEYSTORE_NAME;
27+
let logical_key_store_name = test_utils::TEST_LOGICAL_KEYSTORE_NAME;
28+
let kms_key_arn = test_utils::TEST_KEYSTORE_KMS_KEY_ID;
29+
30+
// 1. Configure your KeyStore resource.
31+
// This SHOULD be the same configuration that was used to create the DDB table
32+
// in the "Create KeyStore Table Example".
33+
let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
34+
let key_store_config = KeyStoreConfig::builder()
35+
.kms_client(aws_sdk_kms::Client::new(&sdk_config))
36+
.ddb_client(aws_sdk_dynamodb::Client::new(&sdk_config))
37+
.ddb_table_name(key_store_table_name)
38+
.logical_key_store_name(logical_key_store_name)
39+
.kms_configuration(KmsConfiguration::KmsKeyArn(kms_key_arn.to_string()))
40+
.build()
41+
.unwrap();
42+
43+
let keystore = keystore_client::Client::from_conf(key_store_config).unwrap();
44+
45+
// 2. Create a new branch key and beacon key in our KeyStore.
46+
// Both the branch key and the beacon key will share an Id.
47+
// This creation is eventually consistent.
48+
49+
let new_key = keystore.create_key().send().await.unwrap();
50+
new_key.branch_key_identifier.unwrap()
51+
}

‎DynamoDbEncryption/runtimes/rust/src/bin/example/get_encrypted_data_key_description.rs

Lines changed: 53 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -2,52 +2,64 @@
22
// SPDX-License-Identifier: Apache-2.0
33

44
use crate::test_utils;
5+
use aws_sdk_dynamodb::types::AttributeValue;
56
use db_esdk::aws_cryptography_dbEncryptionSdk_dynamoDb::client as dbesdk_client;
67
use db_esdk::aws_cryptography_dbEncryptionSdk_dynamoDb::types::dynamo_db_encryption_config::DynamoDbEncryptionConfig;
7-
use std::collections::HashMap;
8-
use aws_sdk_dynamodb::types::AttributeValue;
98
use db_esdk::aws_cryptography_dbEncryptionSdk_dynamoDb::types::GetEncryptedDataKeyDescriptionUnion;
9+
use std::collections::HashMap;
10+
11+
pub async fn get_encrypted_data_key_description() {
12+
let kms_key_id = test_utils::TEST_KMS_KEY_ID;
13+
let ddb_table_name = test_utils::TEST_DDB_TABLE_NAME;
14+
let config = DynamoDbEncryptionConfig::builder().build().unwrap();
15+
let ddb_enc = dbesdk_client::Client::from_conf(config).unwrap();
16+
17+
// 1. Define keys that will be used to retrieve item from the DynamoDB table.
18+
let key_to_get = HashMap::from([
19+
(
20+
"partition_key".to_string(),
21+
AttributeValue::S("BasicPutGetExample".to_string()),
22+
),
23+
("sort_key".to_string(), AttributeValue::N("0".to_string())),
24+
]);
25+
26+
// 2. Create a Amazon DynamoDB Client and retrieve item from DynamoDB table
27+
let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
28+
let ddb = aws_sdk_dynamodb::Client::new(&sdk_config);
29+
let get_item_response = ddb
30+
.get_item()
31+
.set_key(Some(key_to_get))
32+
.table_name(ddb_table_name)
33+
.send()
34+
.await
35+
.unwrap();
1036

11-
pub async fn get_encrypted_data_key_description()
12-
{
13-
let kms_key_id = test_utils::TEST_KMS_KEY_ID;
14-
let ddb_table_name = test_utils::TEST_DDB_TABLE_NAME;
15-
let config = DynamoDbEncryptionConfig::builder().build().unwrap();
16-
let ddb_enc = dbesdk_client::Client::from_conf(config).unwrap();
17-
18-
// 1. Define keys that will be used to retrieve item from the DynamoDB table.
19-
let key_to_get = HashMap::from([
20-
("partition_key".to_string(), AttributeValue::S("BasicPutGetExample".to_string())),
21-
("sort_key".to_string(), AttributeValue::N("0".to_string())),
22-
]);
23-
24-
25-
// 2. Create a Amazon DynamoDB Client and retrieve item from DynamoDB table
26-
let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
27-
let ddb = aws_sdk_dynamodb::Client::new(&sdk_config);
28-
let get_item_response = ddb.get_item()
29-
.set_key(Some(key_to_get))
30-
.table_name(ddb_table_name)
31-
.send().await.unwrap();
32-
33-
34-
// 3. Extract the item from the dynamoDB table and prepare input for the GetEncryptedDataKeyDescription method.
35-
// Here, we are sending dynamodb item but you can also input the header itself by extracting the header from
36-
// "aws_dbe_head" attribute in the dynamoDB item. The part of the code where we send input as the header is commented.
37-
let returned_item = get_item_response.item.unwrap();
38-
let input_union = GetEncryptedDataKeyDescriptionUnion::Item(returned_item);
39-
let output = ddb_enc.get_encrypted_data_key_description()
37+
// 3. Extract the item from the dynamoDB table and prepare input for the GetEncryptedDataKeyDescription method.
38+
// Here, we are sending dynamodb item but you can also input the header itself by extracting the header from
39+
// "aws_dbe_head" attribute in the dynamoDB item. The part of the code where we send input as the header is commented.
40+
let returned_item = get_item_response.item.unwrap();
41+
let input_union = GetEncryptedDataKeyDescriptionUnion::Item(returned_item);
42+
let output = ddb_enc
43+
.get_encrypted_data_key_description()
4044
.input(input_union)
41-
.send().await.unwrap();
45+
.send()
46+
.await
47+
.unwrap();
4248

43-
// The code below shows how we can send header as the input to the DynamoDB. This code is written to demo the
44-
// alternative approach. So, it is commented.
45-
// let input_union = GetEncryptedDataKeyDescriptionUnion::Header(returned_item["aws_dbe_head"].as_b().unwrap().clone());
49+
// The code below shows how we can send header as the input to the DynamoDB. This code is written to demo the
50+
// alternative approach. So, it is commented.
51+
// let input_union = GetEncryptedDataKeyDescriptionUnion::Header(returned_item["aws_dbe_head"].as_b().unwrap().clone());
4652

47-
// 4. Get encrypted DataKey Descriptions from GetEncryptedDataKeyDescription method output and assert if its true.
48-
let encrypted_data_key_descriptions = output.encrypted_data_key_description_output.unwrap();
49-
assert_eq!(encrypted_data_key_descriptions[0].key_provider_id, Some("aws-kms".to_string()));
50-
assert_eq!(encrypted_data_key_descriptions[0].key_provider_info, Some(kms_key_id.to_string()));
53+
// 4. Get encrypted DataKey Descriptions from GetEncryptedDataKeyDescription method output and assert if its true.
54+
let encrypted_data_key_descriptions = output.encrypted_data_key_description_output.unwrap();
55+
assert_eq!(
56+
encrypted_data_key_descriptions[0].key_provider_id,
57+
Some("aws-kms".to_string())
58+
);
59+
assert_eq!(
60+
encrypted_data_key_descriptions[0].key_provider_info,
61+
Some(kms_key_id.to_string())
62+
);
5163

52-
println!("get_encrypted_data_key_description successful.");
53-
}
64+
println!("get_encrypted_data_key_description successful.");
65+
}

‎DynamoDbEncryption/runtimes/rust/src/bin/example/itemencryptor/item_encrypt_decrypt.rs

Lines changed: 156 additions & 128 deletions
Large diffs are not rendered by default.

‎DynamoDbEncryption/runtimes/rust/src/bin/example/main.rs

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,21 @@
66
#![deny(clippy::all)]
77

88
pub mod basic_get_put_example;
9-
pub mod test_utils;
10-
pub mod itemencryptor;
11-
pub mod searchableencryption;
129
pub mod create_keystore_key;
1310
pub mod get_encrypted_data_key_description;
11+
pub mod itemencryptor;
12+
pub mod keyring;
1413
pub mod multi_get_put_example;
14+
pub mod searchableencryption;
15+
pub mod test_utils;
1516

1617
#[tokio::main]
1718
pub async fn main() {
1819
basic_get_put_example::put_item_get_item().await;
1920
itemencryptor::item_encrypt_decrypt::encrypt_decrypt().await;
2021
get_encrypted_data_key_description::get_encrypted_data_key_description().await;
2122
multi_get_put_example::multi_put_get().await;
23+
keyring::raw_rsa_keyring::put_item_get_item().await;
2224

2325
// let key_id = create_keystore_key::keystore_create_key().await;
2426
// // let key_id2 = create_keystore_key::keystore_create_key().await;
@@ -29,22 +31,21 @@ pub async fn main() {
2931
// searchableencryption::basic_searchable_encryption::put_and_query_with_beacon(&key_id).await;
3032
// // FIXME : ScanError will have to wait until we have a reasonable error message strategy
3133

32-
/*
33-
await MultiPutGetExample.MultiPutGet();
34-
await ClientSupplierExample.ClientSupplierPutItemGetItem();
35-
await MultiMrkKeyringExample.MultiMrkKeyringGetItemPutItem();
36-
await RawAesKeyringExample.RawAesKeyringGetItemPutItem();
37-
await MrkDiscoveryMultiKeyringExample.MultiMrkDiscoveryKeyringGetItemPutItem();
38-
await MultiKeyringExample.MultiKeyringGetItemPutItem();
39-
await RawRsaKeyringExample.RawRsaKeyringGetItemPutItem();
40-
await KmsRsaKeyringExample.KmsRsaKeyringGetItemPutItem();
41-
42-
43-
await HierarchicalKeyringExample.HierarchicalKeyringGetItemPutItem(keyId, keyId2);
44-
await CompoundBeaconSearchableEncryptionExample.PutItemQueryItemWithCompoundBeacon(keyId);
45-
await VirtualBeaconSearchableEncryptionExample.PutItemQueryItemWithVirtualBeacon(keyId);
46-
await BeaconStylesSearchableEncryptionExample.PutItemQueryItemWithBeaconStyles(keyId);
47-
await ComplexSearchableEncryptionExample.RunExample(keyId);
48-
*/
34+
/*
35+
await ClientSupplierExample.ClientSupplierPutItemGetItem();
36+
await MultiMrkKeyringExample.MultiMrkKeyringGetItemPutItem();
37+
await RawAesKeyringExample.RawAesKeyringGetItemPutItem();
38+
await MrkDiscoveryMultiKeyringExample.MultiMrkDiscoveryKeyringGetItemPutItem();
39+
await MultiKeyringExample.MultiKeyringGetItemPutItem();
40+
await RawRsaKeyringExample.RawRsaKeyringGetItemPutItem();
41+
await KmsRsaKeyringExample.KmsRsaKeyringGetItemPutItem();
42+
43+
44+
await HierarchicalKeyringExample.HierarchicalKeyringGetItemPutItem(keyId, keyId2);
45+
await CompoundBeaconSearchableEncryptionExample.PutItemQueryItemWithCompoundBeacon(keyId);
46+
await VirtualBeaconSearchableEncryptionExample.PutItemQueryItemWithVirtualBeacon(keyId);
47+
await BeaconStylesSearchableEncryptionExample.PutItemQueryItemWithBeaconStyles(keyId);
48+
await ComplexSearchableEncryptionExample.RunExample(keyId);
49+
*/
4950
println!("All examples completed successfully.\n");
5051
}

‎DynamoDbEncryption/runtimes/rust/src/bin/example/multi_get_put_example.rs

Lines changed: 218 additions & 149 deletions
Large diffs are not rendered by default.

‎DynamoDbEncryption/runtimes/rust/src/bin/example/searchableencryption/basic_searchable_encryption.rs

Lines changed: 323 additions & 286 deletions
Large diffs are not rendered by default.
Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,46 @@
11
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
22
// SPDX-License-Identifier: Apache-2.0
33

4-
pub const TEST_KEYSTORE_NAME : &str = "KeyStoreDdbTable";
5-
pub const TEST_LOGICAL_KEYSTORE_NAME : &str = "KeyStoreDdbTable";
4+
pub const TEST_KEYSTORE_NAME: &str = "KeyStoreDdbTable";
5+
pub const TEST_LOGICAL_KEYSTORE_NAME: &str = "KeyStoreDdbTable";
66

7-
pub const TEST_KEYSTORE_KMS_KEY_ID : &str = "arn:aws:kms:us-west-2:370957321024:key/9d989aa2-2f9c-438c-a745-cc57d3ad0126";
7+
pub const TEST_KEYSTORE_KMS_KEY_ID: &str =
8+
"arn:aws:kms:us-west-2:370957321024:key/9d989aa2-2f9c-438c-a745-cc57d3ad0126";
89

9-
pub const TEST_AWS_ACCOUNT_ID : &str = "658956600833";
10+
pub const TEST_AWS_ACCOUNT_ID: &str = "658956600833";
1011

11-
pub const TEST_AWS_REGION : &str = "us-west-2";
12+
pub const TEST_AWS_REGION: &str = "us-west-2";
1213

1314
// These are public KMS Keys that MUST only be used for testing, and MUST NOT be used for any production data
14-
pub const TEST_KMS_KEY_ID : &str =
15+
pub const TEST_KMS_KEY_ID: &str =
1516
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
1617

17-
pub const TEST_MRK_KEY_ID : &str =
18+
pub const TEST_MRK_KEY_ID: &str =
1819
"arn:aws:kms:us-west-2:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7";
1920

20-
pub const TEST_KMS_RSA_KEY_ID : &str =
21+
pub const TEST_KMS_RSA_KEY_ID: &str =
2122
"arn:aws:kms:us-west-2:658956600833:key/8b432da4-dde4-4bc3-a794-c7d68cbab5a6";
2223

23-
pub const TEST_MRK_REPLICA_KEY_ID_US_EAST_1 : &str =
24+
pub const TEST_MRK_REPLICA_KEY_ID_US_EAST_1: &str =
2425
"arn:aws:kms:us-east-1:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7";
2526

26-
pub const TEST_MRK_REPLICA_KEY_ID_EU_WEST_1 : &str =
27+
pub const TEST_MRK_REPLICA_KEY_ID_EU_WEST_1: &str =
2728
"arn:aws:kms:eu-west-1:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7";
2829

2930
// Our tests require access to DDB Table with this name
30-
pub const TEST_DDB_TABLE_NAME : &str = "DynamoDbEncryptionInterceptorTestTableCS";
31-
pub const TEST_COMPLEX_TABLE_NAME : &str = "ComplexBeaconTestTableCS";
31+
pub const TEST_DDB_TABLE_NAME: &str = "DynamoDbEncryptionInterceptorTestTableCS";
32+
pub const TEST_COMPLEX_TABLE_NAME: &str = "ComplexBeaconTestTableCS";
3233

3334
// Our tests require access to DDB Tables with these name
34-
pub const SIMPLE_BEACON_TEST_DDB_TABLE_NAME : &str = "SimpleBeaconTestTable";
35-
pub const UNIT_INSPECTION_TEST_DDB_TABLE_NAME : &str = "UnitInspectionTestTableCS";
35+
pub const SIMPLE_BEACON_TEST_DDB_TABLE_NAME: &str = "SimpleBeaconTestTable";
36+
pub const UNIT_INSPECTION_TEST_DDB_TABLE_NAME: &str = "UnitInspectionTestTableCS";
3637

3738
// The branch key must have been created using this KMS key
3839
// Note: This is a public resource that anyone can access.
3940
// This MUST NOT be used to encrypt any production data.
40-
pub const TEST_BRANCH_KEY_WRAPPING_KMS_KEY_ARN : &str =
41+
pub const TEST_BRANCH_KEY_WRAPPING_KMS_KEY_ARN: &str =
4142
"arn:aws:kms:us-west-2:370957321024:key/9d989aa2-2f9c-438c-a745-cc57d3ad0126";
4243

4344
// Our tests require access to DDB Table with this name configured as a branch keystore
44-
pub const TEST_BRANCH_KEYSTORE_DDB_TABLE_NAME : &str = "KeyStoreDdbTable";
45-
pub const TEST_COMPLEX_DDB_TABLE_NAME : &str = "ComplexBeaconTestTable";
45+
pub const TEST_BRANCH_KEYSTORE_DDB_TABLE_NAME: &str = "KeyStoreDdbTable";
46+
pub const TEST_COMPLEX_DDB_TABLE_NAME: &str = "ComplexBeaconTestTable";
Lines changed: 41 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,57 @@
1-
use aws_config::Region;
1+
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
23

3-
fn dafny_tokio_runtime() -> tokio::runtime::Runtime
4-
{
5-
tokio::runtime::Builder::new_multi_thread()
6-
.enable_all()
7-
.build()
8-
.unwrap()
9-
}
4+
#![deny(warnings, unconditional_panic)]
5+
#![deny(nonstandard_style)]
6+
#![deny(clippy::all)]
7+
8+
use aws_config::Region;
109

1110
#[allow(non_snake_case)]
1211
impl crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::_default {
13-
pub fn DDBClientForRegion(region: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc<
12+
pub fn DDBClientForRegion(region: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc<
1413
crate::r#_Wrappers_Compile::Result<
1514
::dafny_runtime::Object<dyn crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IDynamoDBClient>,
1615
::std::rc::Rc<crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Error>
1716
>
18-
> {
19-
let region = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(region);
20-
let shared_config = dafny_tokio_runtime().block_on(aws_config::load_defaults(aws_config::BehaviorVersion::v2024_03_28()));
21-
let shared_config = shared_config.to_builder().region(Region::new(region)).build();
22-
let inner = aws_sdk_dynamodb::Client::new(&shared_config);
23-
let client = crate::deps::com_amazonaws_dynamodb::client::Client { inner };
24-
let dafny_client = ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(client));
25-
std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::Success { value: dafny_client })
26-
}
17+
>{
18+
let region =
19+
dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(
20+
region,
21+
);
22+
let shared_config = tokio::task::block_in_place(|| {
23+
tokio::runtime::Handle::current().block_on(async {
24+
aws_config::load_defaults(aws_config::BehaviorVersion::v2024_03_28()).await
25+
})
26+
});
27+
let shared_config = shared_config
28+
.to_builder()
29+
.region(Region::new(region))
30+
.build();
31+
let inner = aws_sdk_dynamodb::Client::new(&shared_config);
32+
let client = crate::deps::com_amazonaws_dynamodb::client::Client { inner };
33+
let dafny_client = ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(client));
34+
std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::Success {
35+
value: dafny_client,
36+
})
37+
}
2738

2839
pub fn DynamoDBClient() -> ::std::rc::Rc<
2940
crate::r#_Wrappers_Compile::Result<
3041
::dafny_runtime::Object<dyn crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IDynamoDBClient>,
3142
::std::rc::Rc<crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Error>
3243
>
33-
> {
34-
let shared_config = dafny_tokio_runtime().block_on(aws_config::load_defaults(aws_config::BehaviorVersion::v2024_03_28()));
35-
let inner = aws_sdk_dynamodb::Client::new(&shared_config);
36-
let client = crate::deps::com_amazonaws_dynamodb::client::Client { inner };
37-
let dafny_client = ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(client));
38-
std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::Success { value: dafny_client })
44+
>{
45+
let shared_config = tokio::task::block_in_place(|| {
46+
tokio::runtime::Handle::current().block_on(async {
47+
aws_config::load_defaults(aws_config::BehaviorVersion::v2024_03_28()).await
48+
})
49+
});
50+
let inner = aws_sdk_dynamodb::Client::new(&shared_config);
51+
let client = crate::deps::com_amazonaws_dynamodb::client::Client { inner };
52+
let dafny_client = ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(client));
53+
std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::Success {
54+
value: dafny_client,
55+
})
3956
}
40-
4157
}

‎DynamoDbEncryption/runtimes/rust/src/ecdh.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,10 +94,8 @@ pub mod ECDH {
9494
if ec_group.is_null() {
9595
return Err("Error in EC_KEY_get0_group in X509_to_X962.".to_string());
9696
}
97-
if nid.is_some() {
98-
if nid.unwrap() != unsafe { EC_GROUP_get_curve_name(ec_group) } {
99-
return Err("Curve type mismatch in X509_to_X962.".to_string());
100-
}
97+
if nid.is_some() && nid.unwrap() != unsafe { EC_GROUP_get_curve_name(ec_group) } {
98+
return Err("Curve type mismatch in X509_to_X962.".to_string());
10199
}
102100
let ec_point = unsafe { EC_KEY_get0_public_key(ec_key) };
103101
if ec_point.is_null() {

‎DynamoDbEncryption/runtimes/rust/src/intercept.rs

Lines changed: 59 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
#![deny(warnings, unconditional_panic)]
5+
#![deny(nonstandard_style)]
6+
#![deny(clippy::all)]
7+
18
use aws_sdk_dynamodb::{
29
config::{
310
interceptors::{BeforeSerializationInterceptorContextMut, FinalizerInterceptorContextMut},
@@ -7,94 +14,81 @@ use aws_sdk_dynamodb::{
714
};
815
use aws_smithy_runtime_api::client::interceptors::context::Input;
916
use aws_smithy_types::config_bag::{Storable, StoreReplace};
10-
use std::sync::LazyLock;
11-
12-
/// A runtime for executing operations on the asynchronous client in a blocking manner.
13-
/// Necessary because Dafny only generates synchronous code.
14-
static dafny_tokio_runtime: LazyLock<tokio::runtime::Runtime> = LazyLock::new(|| {
15-
tokio::runtime::Builder::new_multi_thread()
16-
.enable_all()
17-
.build()
18-
.unwrap()
19-
});
20-
2117

2218
#[macro_export]
2319
macro_rules! modify_request {
24-
($cfg:ident,$request:ident,$self:ident,$transform:ident) => {
25-
{
26-
// store the original request
27-
$cfg.interceptor_state().store_put(OriginalRequest(Input::erase($request.clone())));
28-
29-
// transform the request
30-
// *$request = tokio::task::block_in_place(|| {
31-
let result = tokio::task::block_in_place(|| {
32-
tokio::runtime::Handle::current().block_on(async {
33-
$self.client
20+
($cfg:ident,$request:ident,$self:ident,$transform:ident) => {{
21+
// store the original request
22+
$cfg.interceptor_state()
23+
.store_put(OriginalRequest(Input::erase($request.clone())));
24+
25+
// transform the request
26+
// *$request = tokio::task::block_in_place(|| {
27+
let result = tokio::task::block_in_place(|| {
28+
tokio::runtime::Handle::current().block_on(async {
29+
$self
30+
.client
3431
.$transform()
3532
.sdk_input($request.clone())
3633
.send()
3734
.await
38-
})
39-
});
40-
match result {
41-
Ok(x) => *$request = x.transformed_input.unwrap(),
42-
Err(x) => {
43-
let s = format!("{:?}", x);
44-
return Err(s.into());
45-
}
46-
};
47-
}
48-
};
35+
})
36+
});
37+
match result {
38+
Ok(x) => *$request = x.transformed_input.unwrap(),
39+
Err(x) => {
40+
let s = format!("{:?}", x);
41+
return Err(s.into());
42+
}
43+
};
44+
}};
4945
}
5046

51-
52-
53-
5447
#[macro_export]
5548
macro_rules! modify_response {
56-
($cfg:ident,$type:ty,$response:ident,$self:ident,$transform:ident) => {
57-
{
58-
// retrieve the original request
59-
let original = $cfg
60-
.load::<OriginalRequest>()
61-
.expect("we put this in ourselves");
62-
let original = original
63-
.0
64-
.downcast_ref::<$type>()
65-
.expect("we know this type corresponds to the output type");
66-
67-
// transform the response
68-
let result = tokio::task::block_in_place(|| {
69-
tokio::runtime::Handle::current().block_on(async {
70-
$self.client
49+
($cfg:ident,$type:ty,$response:ident,$self:ident,$transform:ident) => {{
50+
// retrieve the original request
51+
let original = $cfg
52+
.load::<OriginalRequest>()
53+
.expect("we put this in ourselves");
54+
let original = original
55+
.0
56+
.downcast_ref::<$type>()
57+
.expect("we know this type corresponds to the output type");
58+
59+
// transform the response
60+
let result = tokio::task::block_in_place(|| {
61+
tokio::runtime::Handle::current().block_on(async {
62+
$self
63+
.client
7164
.$transform()
7265
.original_input(original.clone())
7366
.sdk_output($response.clone())
7467
.send()
7568
.await
76-
})
77-
});
78-
match result {
79-
Ok(x) => *$response = x.transformed_output.unwrap(),
80-
Err(x) => {
81-
let s = format!("{:?}", x);
82-
return Err(s.into());
83-
}
84-
};
85-
}
86-
};
69+
})
70+
});
71+
match result {
72+
Ok(x) => *$response = x.transformed_output.unwrap(),
73+
Err(x) => {
74+
let s = format!("{:?}", x);
75+
return Err(s.into());
76+
}
77+
};
78+
}};
8779
}
8880

8981
#[derive(Debug)]
9082
pub struct DbEsdkInterceptor {
91-
client : crate::client::Client
83+
client: crate::client::Client,
9284
}
9385

9486
impl DbEsdkInterceptor {
95-
pub fn new(config : crate::types::dynamo_db_tables_encryption_config::DynamoDbTablesEncryptionConfig) -> Self {
87+
pub fn new(
88+
config: crate::types::dynamo_db_tables_encryption_config::DynamoDbTablesEncryptionConfig,
89+
) -> Self {
9690
let client = crate::client::Client::from_conf(config).unwrap(); // FIXME
97-
DbEsdkInterceptor {client}
91+
DbEsdkInterceptor { client }
9892
}
9993
}
10094

@@ -152,7 +146,7 @@ impl Intercept for DbEsdkInterceptor {
152146

153147
// macro_rules! modify_response {
154148
// ($cfg:ident,$type:ty,$output:ident,$self:ident,$transform:ident) => {
155-
149+
156150
fn modify_before_attempt_completion(
157151
&self,
158152
context: &mut FinalizerInterceptorContextMut,
Lines changed: 61 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,64 +1,68 @@
1-
use aws_config::Region;
2-
use std::any::Any;
1+
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
33

4-
fn dafny_tokio_runtime() -> tokio::runtime::Runtime
5-
{
6-
tokio::runtime::Builder::new_multi_thread()
7-
.enable_all()
8-
.build()
9-
.unwrap()
10-
}
4+
#![deny(warnings, unconditional_panic)]
5+
#![deny(nonstandard_style)]
6+
#![deny(clippy::all)]
117

12-
impl crate::r#software::amazon::cryptography::services::kms::internaldafny::_default {
13-
#[allow(non_snake_case)]
14-
pub fn KMSClientForRegion(region: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc<crate::r#_Wrappers_Compile::Result<::dafny_runtime::Object<dyn crate::software::amazon::cryptography::services::kms::internaldafny::types::IKMSClient>, ::std::rc::Rc<crate::software::amazon::cryptography::services::kms::internaldafny::types::Error>>>{
15-
let region = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(region);
16-
// let shared_config = dafny_tokio_runtime().block_on(aws_config::load_defaults(aws_config::BehaviorVersion::v2024_03_28()));
17-
let shared_config = tokio::task::block_in_place(|| {
18-
tokio::runtime::Handle::current().block_on(async {
19-
aws_config::load_defaults(aws_config::BehaviorVersion::v2024_03_28()).await
20-
})
21-
});
8+
use aws_config::Region;
229

23-
let shared_config = shared_config.to_builder().region(Region::new(region)).build();
24-
let inner = aws_sdk_kms::Client::new(&shared_config);
25-
let client = crate::deps::com_amazonaws_kms::client::Client { inner };
26-
let dafny_client = ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(client));
27-
std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::Success { value: dafny_client })
28-
}
29-
/*
30-
let res = task::spawn_blocking(move || {
31-
// Stand-in for compute-heavy work or using synchronous APIs
32-
v.push_str("world");
33-
// Pass ownership of the value back to the asynchronous context
34-
v
35-
}).await?;
10+
impl crate::r#software::amazon::cryptography::services::kms::internaldafny::_default {
11+
#[allow(non_snake_case)]
12+
pub fn KMSClientForRegion(region: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc<crate::r#_Wrappers_Compile::Result<::dafny_runtime::Object<dyn crate::software::amazon::cryptography::services::kms::internaldafny::types::IKMSClient>, ::std::rc::Rc<crate::software::amazon::cryptography::services::kms::internaldafny::types::Error>>>{
13+
let region =
14+
dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(
15+
region,
16+
);
17+
let shared_config = tokio::task::block_in_place(|| {
18+
tokio::runtime::Handle::current().block_on(async {
19+
aws_config::load_defaults(aws_config::BehaviorVersion::v2024_03_28()).await
20+
})
21+
});
3622

37-
*/
23+
let shared_config = shared_config
24+
.to_builder()
25+
.region(Region::new(region))
26+
.build();
27+
let inner = aws_sdk_kms::Client::new(&shared_config);
28+
let client = crate::deps::com_amazonaws_kms::client::Client { inner };
29+
let dafny_client = ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(client));
30+
std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::Success {
31+
value: dafny_client,
32+
})
33+
}
3834

39-
#[allow(non_snake_case)]
40-
pub fn KMSClient() -> ::std::rc::Rc<crate::r#_Wrappers_Compile::Result<::dafny_runtime::Object<dyn crate::software::amazon::cryptography::services::kms::internaldafny::types::IKMSClient>, ::std::rc::Rc<crate::software::amazon::cryptography::services::kms::internaldafny::types::Error>>>{
41-
let shared_config = dafny_tokio_runtime().block_on(aws_config::load_defaults(aws_config::BehaviorVersion::v2024_03_28()));
42-
let inner = aws_sdk_kms::Client::new(&shared_config);
43-
let client = crate::deps::com_amazonaws_kms::client::Client { inner };
44-
let dafny_client = ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(client));
45-
std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::Success { value: dafny_client })
46-
}
35+
#[allow(non_snake_case)]
36+
pub fn KMSClient() -> ::std::rc::Rc<crate::r#_Wrappers_Compile::Result<::dafny_runtime::Object<dyn crate::software::amazon::cryptography::services::kms::internaldafny::types::IKMSClient>, ::std::rc::Rc<crate::software::amazon::cryptography::services::kms::internaldafny::types::Error>>>{
37+
let shared_config = tokio::task::block_in_place(|| {
38+
tokio::runtime::Handle::current().block_on(async {
39+
aws_config::load_defaults(aws_config::BehaviorVersion::v2024_03_28()).await
40+
})
41+
});
42+
let inner = aws_sdk_kms::Client::new(&shared_config);
43+
let client = crate::deps::com_amazonaws_kms::client::Client { inner };
44+
let dafny_client = ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(client));
45+
std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::Success {
46+
value: dafny_client,
47+
})
48+
}
4749

48-
#[allow(non_snake_case)]
49-
pub fn RegionMatch(
50-
kmsClient: &::dafny_runtime::Object<dyn crate::software::amazon::cryptography::services::kms::internaldafny::types::IKMSClient>,
51-
region: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>,
52-
) -> ::std::rc::Rc<crate::r#_Wrappers_Compile::Option<bool>> {
53-
let region = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(region);
54-
let any = dafny_runtime::cast_any_object!(kmsClient);
55-
let client = dafny_runtime::cast_object!(any, crate::deps::com_amazonaws_kms::client::Client);
56-
let flag = match client.as_ref().inner.config().region() {
57-
Some(r) => {
58-
r.as_ref() == &region
59-
},
60-
None => false
61-
};
62-
::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::Some{value : flag})
63-
}
50+
#[allow(non_snake_case)]
51+
pub fn RegionMatch(
52+
kmsClient: &::dafny_runtime::Object<dyn crate::software::amazon::cryptography::services::kms::internaldafny::types::IKMSClient>,
53+
region: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>,
54+
) -> ::std::rc::Rc<crate::r#_Wrappers_Compile::Option<bool>> {
55+
let region =
56+
dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(
57+
region,
58+
);
59+
let any = dafny_runtime::cast_any_object!(kmsClient);
60+
let client =
61+
dafny_runtime::cast_object!(any, crate::deps::com_amazonaws_kms::client::Client);
62+
let flag = match client.as_ref().inner.config().region() {
63+
Some(r) => r.as_ref() == region,
64+
None => false,
65+
};
66+
::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::Some { value: flag })
67+
}
6468
}

‎DynamoDbEncryption/runtimes/rust/src/rsa.rs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,20 +9,20 @@
99
#[allow(non_snake_case)]
1010
pub mod RSAEncryption {
1111
pub mod RSA {
12+
use crate::_Wrappers_Compile as Wrappers;
1213
use crate::software::amazon::cryptography::primitives::internaldafny::types::RSAPaddingMode;
1314
use crate::*;
1415
use ::std::rc::Rc;
1516
use aws_lc_rs::encoding::{AsDer, Pkcs8V1Der, PublicKeyX509Der};
16-
use crate::_Wrappers_Compile as Wrappers;
1717

1818
use aws_lc_rs::rsa::KeySize;
1919
use aws_lc_rs::rsa::OaepAlgorithm;
2020
use aws_lc_rs::rsa::OaepPrivateDecryptingKey;
2121
use aws_lc_rs::rsa::OaepPublicEncryptingKey;
22+
use aws_lc_rs::rsa::Pkcs1PrivateDecryptingKey;
23+
use aws_lc_rs::rsa::Pkcs1PublicEncryptingKey;
2224
use aws_lc_rs::rsa::PrivateDecryptingKey;
2325
use aws_lc_rs::rsa::PublicEncryptingKey;
24-
use aws_lc_rs::rsa::Pkcs1PublicEncryptingKey;
25-
use aws_lc_rs::rsa::Pkcs1PrivateDecryptingKey;
2626
use pem;
2727
use software::amazon::cryptography::primitives::internaldafny::types::Error as DafnyError;
2828

@@ -196,9 +196,10 @@ pub mod RSAEncryption {
196196
}
197197

198198
pub fn encrypt_pkcs1(public_key: &[u8], plain_text: &[u8]) -> Result<Vec<u8>, String> {
199-
let public_key = PublicEncryptingKey::from_der(public_key)
200-
.map_err(|e| format!("{:?}", e))?;
201-
let public_key = Pkcs1PublicEncryptingKey::new(public_key).map_err(|e| format!("{:?}", e))?;
199+
let public_key =
200+
PublicEncryptingKey::from_der(public_key).map_err(|e| format!("{:?}", e))?;
201+
let public_key =
202+
Pkcs1PublicEncryptingKey::new(public_key).map_err(|e| format!("{:?}", e))?;
202203
let mut ciphertext: Vec<u8> = vec![0; plain_text.len() + public_key.key_size_bytes()];
203204
let cipher_text = public_key
204205
.encrypt(plain_text, &mut ciphertext)
@@ -209,7 +210,8 @@ pub mod RSAEncryption {
209210
pub fn decrypt_pkcs1(private_key: &[u8], cipher_text: &[u8]) -> Result<Vec<u8>, String> {
210211
let private_key = PrivateDecryptingKey::from_pkcs8(private_key)
211212
.map_err(|e| format!("from_pkcs8 : {:?}", e))?;
212-
let private_key = Pkcs1PrivateDecryptingKey::new(private_key).map_err(|e| format!("new : {:?}", e))?;
213+
let private_key = Pkcs1PrivateDecryptingKey::new(private_key)
214+
.map_err(|e| format!("new : {:?}", e))?;
213215
let mut message: Vec<u8> = vec![0; cipher_text.len()];
214216
let message = private_key
215217
.decrypt(cipher_text, &mut message)

‎DynamoDbEncryption/runtimes/rust/src/software_externs.rs

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ pub mod software {
2525
use crate::software::amazon::cryptography::dbencryptionsdk::dynamodb::itemencryptor::internaldafny::types::Error as DafnyError;
2626
use crate::software::amazon::cryptography::dbencryptionsdk::dynamodb::internaldafny::types::LegacyPolicy;
2727
use ::std::rc::Rc;
28+
type Legacy = ::dafny_runtime::Object<crate::software::amazon::cryptography::dbencryptionsdk::dynamodb::itemencryptor::internaldafny::legacy::InternalLegacyOverride>;
2829

2930
fn error(s: &str) -> Rc<DafnyError> {
3031
Rc::new(DafnyError::DynamoDbItemEncryptorException {
@@ -35,19 +36,36 @@ pub mod software {
3536
pub struct InternalLegacyOverride {
3637
pub r#__i_policy: Rc<LegacyPolicy>,
3738
}
38-
fn fail_override() -> Rc<crate::_Wrappers_Compile::Result<Rc<crate::_Wrappers_Compile::Option<::dafny_runtime::Object<crate::software::amazon::cryptography::dbencryptionsdk::dynamodb::itemencryptor::internaldafny::legacy::InternalLegacyOverride>>>, Rc<DafnyError>>>{
39+
fn fail_override() -> Rc<
40+
crate::_Wrappers_Compile::Result<
41+
Rc<crate::_Wrappers_Compile::Option<Legacy>>,
42+
Rc<DafnyError>,
43+
>,
44+
> {
3945
Rc::new(crate::_Wrappers_Compile::Result::Failure {
4046
error: error("Legacy configuration unsupported."),
4147
})
4248
}
43-
fn success_override() -> Rc<crate::_Wrappers_Compile::Result<Rc<crate::_Wrappers_Compile::Option<::dafny_runtime::Object<crate::software::amazon::cryptography::dbencryptionsdk::dynamodb::itemencryptor::internaldafny::legacy::InternalLegacyOverride>>>, Rc<DafnyError>>>{
49+
fn success_override() -> Rc<
50+
crate::_Wrappers_Compile::Result<
51+
Rc<crate::_Wrappers_Compile::Option<Legacy>>,
52+
Rc<DafnyError>,
53+
>,
54+
> {
4455
Rc::new(crate::_Wrappers_Compile::Result::Success {
4556
value: Rc::new(crate::_Wrappers_Compile::Option::None {}),
4657
})
4758
}
4859

4960
impl InternalLegacyOverride {
50-
pub fn Build(config: &Rc<crate::software::amazon::cryptography::dbencryptionsdk::dynamodb::itemencryptor::internaldafny::types::DynamoDbItemEncryptorConfig>) -> Rc<crate::_Wrappers_Compile::Result<Rc<crate::_Wrappers_Compile::Option<::dafny_runtime::Object<crate::software::amazon::cryptography::dbencryptionsdk::dynamodb::itemencryptor::internaldafny::legacy::InternalLegacyOverride>>>, Rc<DafnyError>>>{
61+
pub fn Build(
62+
config: &Rc<crate::software::amazon::cryptography::dbencryptionsdk::dynamodb::itemencryptor::internaldafny::types::DynamoDbItemEncryptorConfig>,
63+
) -> Rc<
64+
crate::_Wrappers_Compile::Result<
65+
Rc<crate::_Wrappers_Compile::Option<Legacy>>,
66+
Rc<DafnyError>,
67+
>,
68+
> {
5169
match &**config.legacyOverride() {
5270
crate::_Wrappers_Compile::Option::Some{value} => {
5371
match &**value.policy() {

0 commit comments

Comments
 (0)
Please sign in to comment.